// 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() }