Breaking: a job with a raw element prints only with a token issued with uberbringer token --raw. Every other token, every existing one included, gets 403 token_scope for it, with the raw elements in details, and keeps every other route. The notify module prints a notification card from a title, message, priority and tags, with topic, click, up to three actions, image, markdown and time as options; it decodes strictly and refuses a payload over its length caps. The ntfy module takes one ntfy message as ntfy sends it, such as the ntfy client's $NTFY_RAW, ignores fields it does not know, cuts text over the caps, and answers 204 for other events and binary bodies. Both print every message plain: one message cannot tell the first of a sequence from a replacement, since a publisher may choose the sequence ID. internal/pkg/ntfy holds ntfy's message types. Both print the same card. The priority picks the form: a dark URGENT rule and a double box, a double box headed HIGH, a single box with the title in its border, or a rule with no box. Tags print as markers in front of the title, the rest on a Tags row; links print as QR codes with their labels; attached PNG, JPEG, GIF and WebP images print after the card. A line-level markdown subset is laid out without a dependency, keeping marks inside code spans and URLs, and emoji are removed after a few typed ones become markers. A card that cannot be laid out prints as a plain receipt, and the server logs the fault once at ERROR and reports it to Sentry once. [ntfy.format] and [ntfy.markers] shape the cards; the markers table is a setting with the user's own keys, also settable as UBERBRINGER_NTFY_MARKERS=name=value,... uberbringer token --modules issues a token limited to those modules' print and preview routes, job status and the module list; each route in the table says which tokens it takes, and a scope claim that could read as absent makes the token invalid. image elements take optional, which also shrinks a too-wide image to the paper; a QR code that could be too wide for the paper prints with smaller modules; box takes title_bold. Submit takes a Meta whose source shows in job status and, with a copy of the request ID, in every worker log line of the job. The four ntfy cards passed on the TM-T88IV, posted as the client recipe posts them, and their bytes are pinned in TestPaperReceipts. docs/api.md describes the modules, the card and the client recipe, with tokens read from a header file; docs/swagger.json is regenerated. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
257 lines
7.6 KiB
Go
257 lines
7.6 KiB
Go
// Package server exposes the Überbringer HTTP API on Fiber.
|
|
package server
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"log/slog"
|
|
"net"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/getsentry/sentry-go"
|
|
"github.com/gofiber/fiber/v3"
|
|
"github.com/gofiber/fiber/v3/middleware/compress"
|
|
"github.com/gofiber/fiber/v3/middleware/limiter"
|
|
recoverer "github.com/gofiber/fiber/v3/middleware/recover" // avoids shadowing the recover builtin
|
|
"github.com/gofiber/fiber/v3/middleware/requestid"
|
|
|
|
"uberbringer/internal/pkg/escpos"
|
|
"uberbringer/internal/pkg/modules"
|
|
"uberbringer/internal/pkg/printqueue"
|
|
"uberbringer/internal/pkg/receipt"
|
|
)
|
|
|
|
// shutdownTimeout bounds how long in-flight requests may take to finish.
|
|
const shutdownTimeout = 10 * time.Second
|
|
|
|
// Jobs is the print queue as seen by the HTTP handlers.
|
|
type Jobs interface {
|
|
Submit(job receipt.Job, meta printqueue.Meta) (printqueue.Status, error)
|
|
Status(id printqueue.JobID) (printqueue.Status, error)
|
|
Pending() int
|
|
}
|
|
|
|
// Printer reports the printer's real-time status.
|
|
type Printer interface {
|
|
Status(ctx context.Context) (escpos.Status, error)
|
|
}
|
|
|
|
// Previewer renders a job as the lines it would print, without printing it.
|
|
type Previewer interface {
|
|
Preview(ctx context.Context, job receipt.Job) (receipt.Preview, error)
|
|
}
|
|
|
|
// Modules are the modules the module routes build jobs with.
|
|
type Modules interface {
|
|
Get(name string) (modules.Module, bool)
|
|
List() []modules.Info
|
|
}
|
|
|
|
// Deps are the services the handlers use.
|
|
type Deps struct {
|
|
Jobs Jobs
|
|
Printer Printer
|
|
Previewer Previewer
|
|
Modules Modules
|
|
|
|
// ModuleEnv returns what a module may know when it builds a job: the
|
|
// time now, and the zone and layout times print in.
|
|
ModuleEnv func() modules.Env
|
|
}
|
|
|
|
// Info describes the running build for the index route.
|
|
type Info struct {
|
|
Project string
|
|
Description string
|
|
Authors string
|
|
Version string
|
|
Build string
|
|
}
|
|
|
|
// Config configures the HTTP server.
|
|
type Config struct {
|
|
Info Info
|
|
|
|
// Secret is the HS256 key bearer tokens must be signed with.
|
|
Secret []byte
|
|
|
|
// RateLimit requests per RateWindow are allowed per client IP on /api.
|
|
RateLimit int
|
|
RateWindow time.Duration
|
|
|
|
// TrustedProxies may set ProxyHeader to the real client IP.
|
|
TrustedProxies []string
|
|
ProxyHeader string
|
|
|
|
BodyLimit int
|
|
ReadTimeout time.Duration
|
|
WriteTimeout time.Duration
|
|
IdleTimeout time.Duration
|
|
|
|
// RequestID generates request IDs.
|
|
RequestID func() string
|
|
|
|
// OpenAPI is the API's OpenAPI document, which GET /openapi.json
|
|
// answers with.
|
|
OpenAPI []byte
|
|
|
|
// HealthRecheckDelay is how long /healthz waits before re-reading a
|
|
// printer that looked not ready. Zero means defaultHealthRecheckDelay.
|
|
HealthRecheckDelay time.Duration
|
|
}
|
|
|
|
// defaultHealthRecheckDelay is long enough for a cut or paper feed to finish
|
|
// and short enough to stay well inside healthTimeout.
|
|
const defaultHealthRecheckDelay = 750 * time.Millisecond
|
|
|
|
// Server is the HTTP API.
|
|
type Server struct {
|
|
app *fiber.App
|
|
config Config
|
|
jobs Jobs
|
|
printer Printer
|
|
previewer Previewer
|
|
modules Modules
|
|
moduleEnv func() modules.Env
|
|
logger *slog.Logger
|
|
}
|
|
|
|
// New builds the server and its routes.
|
|
func New(config Config, deps Deps, logger *slog.Logger) *Server {
|
|
switch {
|
|
case deps.Jobs == nil || deps.Printer == nil || deps.Previewer == nil || logger == nil:
|
|
panic("server.New: jobs, printer, previewer and logger must not be nil")
|
|
case deps.Modules == nil || deps.ModuleEnv == nil:
|
|
panic("server.New: modules and module env must not be nil")
|
|
case len(config.Secret) == 0:
|
|
panic("server.New: secret must not be empty")
|
|
case config.RequestID == nil:
|
|
panic("server.New: RequestID must not be nil")
|
|
}
|
|
if config.HealthRecheckDelay <= 0 {
|
|
config.HealthRecheckDelay = defaultHealthRecheckDelay
|
|
}
|
|
s := &Server{
|
|
config: config,
|
|
jobs: deps.Jobs,
|
|
printer: deps.Printer,
|
|
previewer: deps.Previewer,
|
|
modules: deps.Modules,
|
|
moduleEnv: deps.ModuleEnv,
|
|
logger: logger,
|
|
}
|
|
|
|
s.app = fiber.New(fiber.Config{
|
|
AppName: config.Info.Project,
|
|
BodyLimit: config.BodyLimit,
|
|
ReadTimeout: config.ReadTimeout,
|
|
WriteTimeout: config.WriteTimeout,
|
|
IdleTimeout: config.IdleTimeout,
|
|
ErrorHandler: s.handleError,
|
|
TrustProxy: len(config.TrustedProxies) > 0,
|
|
ProxyHeader: config.ProxyHeader,
|
|
EnableIPValidation: true,
|
|
TrustProxyConfig: fiber.TrustProxyConfig{Proxies: config.TrustedProxies},
|
|
})
|
|
|
|
// logRequests is outermost so that it logs the status the client got for
|
|
// every request, a recovered panic included: the recover middleware
|
|
// inside it has turned the panic into an error by then.
|
|
s.app.Use(s.logRequests)
|
|
s.app.Use(recoverer.New(recoverer.Config{
|
|
EnableStackTrace: true,
|
|
StackTraceHandler: s.reportPanic,
|
|
PanicHandler: recoveredPanic,
|
|
}))
|
|
s.app.Use(attachSentryHub)
|
|
s.app.Use(requestid.New(requestid.Config{Generator: config.RequestID}))
|
|
s.app.Use(compress.New(compress.Config{Level: compress.LevelBestSpeed}))
|
|
|
|
api := s.app.Group(BasePath,
|
|
noStore,
|
|
limiter.New(limiter.Config{
|
|
Max: config.RateLimit,
|
|
Expiration: config.RateWindow,
|
|
KeyGenerator: func(c fiber.Ctx) string { return c.IP() },
|
|
LimitReached: func(fiber.Ctx) error { return newAPIError(codeRateLimited) },
|
|
}),
|
|
requireBearerToken(config.Secret),
|
|
)
|
|
s.registerRoutes(api)
|
|
|
|
return s
|
|
}
|
|
|
|
// Serve accepts connections on ln until ctx is cancelled, then shuts down
|
|
// gracefully.
|
|
func (s *Server) Serve(ctx context.Context, ln net.Listener) error {
|
|
err := s.app.Listener(ln, fiber.ListenConfig{
|
|
GracefulContext: ctx,
|
|
ShutdownTimeout: shutdownTimeout,
|
|
DisableStartupMessage: true,
|
|
})
|
|
if err != nil && !errors.Is(err, net.ErrClosed) {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// logRequests logs one line per request with the status the client got. It
|
|
// hands errors to handleError itself so that the line carries the final
|
|
// status. A 5xx line is a warning so that outages stand out; the cause of an
|
|
// unexpected failure is logged once, by handleError or reportPanic. Only the
|
|
// path is logged, never the query string.
|
|
func (s *Server) logRequests(c fiber.Ctx) error {
|
|
start := time.Now()
|
|
if err := c.Next(); err != nil {
|
|
if err := s.handleError(c, err); err != nil {
|
|
c.Status(fiber.StatusInternalServerError)
|
|
}
|
|
}
|
|
status := c.Response().StatusCode()
|
|
level := slog.LevelInfo
|
|
if status >= fiber.StatusInternalServerError {
|
|
level = slog.LevelWarn
|
|
}
|
|
s.logger.LogAttrs(c.Context(), level, "request",
|
|
slog.String("method", c.Method()),
|
|
slog.String("path", c.Path()),
|
|
slog.Int("status", status),
|
|
slog.Duration("latency", time.Since(start)),
|
|
slog.String("ip", c.IP()),
|
|
slog.String("request_id", requestid.FromContext(c)),
|
|
)
|
|
return nil
|
|
}
|
|
|
|
// sentryHubKey stores the per-request Sentry hub in fiber Locals.
|
|
type sentryHubKey struct{}
|
|
|
|
// attachSentryHub gives each request its own Sentry hub, tagged with the
|
|
// method and path, for handleError and reportPanic to report with. Request
|
|
// bodies are deliberately not attached: they hold the text being printed.
|
|
func attachSentryHub(c fiber.Ctx) error {
|
|
hub := sentry.CurrentHub().Clone()
|
|
hub.Scope().SetTag("method", c.Method())
|
|
// Clone: the path points into a buffer fasthttp reuses for the next
|
|
// request, and the SDK may send the event after this one has ended.
|
|
hub.Scope().SetTag("path", strings.Clone(c.Path()))
|
|
c.Locals(sentryHubKey{}, hub)
|
|
return c.Next()
|
|
}
|
|
|
|
// noStore keeps caches from storing a response: health and job status
|
|
// change from one request to the next.
|
|
func noStore(c fiber.Ctx) error {
|
|
c.Set(fiber.HeaderCacheControl, "no-store")
|
|
return c.Next()
|
|
}
|
|
|
|
func hubFrom(c fiber.Ctx) *sentry.Hub {
|
|
if hub, ok := c.Locals(sentryHubKey{}).(*sentry.Hub); ok {
|
|
return hub
|
|
}
|
|
return sentry.CurrentHub()
|
|
}
|