Adopt norn's CI, release, API and docs practices; bare module path
Test / Lint, test and build (push) Successful in 3m17s
Test / Lint, test and build (push) Successful in 3m17s
Module
- The module path is now the bare "uberbringer"; imports read
uberbringer/internal/... The banner keeps the Gitea URL.
CI and releases
- Workflows move to .gitea/workflows: test.yml (every branch push:
gofmt, goimports, tidy, vet, staticcheck, race tests, goreleaser
snapshot), security.yml (govulncheck weekly and on main) and a hardened
release.yml (v* tags on main only, tags fetched, goreleaser pinned to
2.20.3). The broken labeler workflow is removed.
- go.mod pins toolchain go1.27.4, which fixes GO-2026-6859; workflows
check that the running Go matches it.
- .goreleaser.yaml: tidy check that never writes, reproducible file times,
prerelease: auto, a release header linking CHANGELOG.md, and archives
that ship CHANGELOG.md, the example config and the systemd unit.
- Makefile mirrors the CI gate; .dockerignore is an allowlist.
API and tests
- Every error answers {"error", "code", "details"} with a stable code from
server/errors.go; the framework's own error text is never sent.
- Panics and unexpected errors are logged and reported to Sentry once;
refusals are not logged as failures. /healthz sends no-store.
- TestRoutesConform requires auth, rate limiting and the body limit on
every /api/v1 route.
- Race-prone tests no longer rely on freed ports or sleeps; serve takes
an injected listener.
- The test config uses a placeholder secret instead of a real one.
Install and packaging
- install.sh resolves the latest release through the Gitea API, verifies
checksums, requests a certificate only when none exists, installs the
hardened packaging/uberbringer.service and writes the first token to a
0600 file instead of printing it. It is now executable in git.
Docs
- CLAUDE.md, CHANGELOG.md (0.2.0 with breaking changes and upgrade
steps), docs/design.md, and docs/plans/formatters.md for the planned
CP437 blocks, modules and ntfy printing. README updated throughout.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
afcf96431f
commit
9b91109550
39 files changed
+3197
-433
No files matched your search
@@ -14,7 +14,7 @@ import (
|
||||
"github.com/liamg/tml"
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/config"
|
||||
"uberbringer/internal/pkg/config"
|
||||
)
|
||||
|
||||
// Project information shown by the banner, the version command and the API
|
||||
|
||||
@@ -14,25 +14,39 @@ import (
|
||||
"go.jetify.com/typeid"
|
||||
"golang.org/x/sync/errgroup"
|
||||
|
||||
"git.anomalous.dev/57_Wolve/uberbringer/internal/app/uberbringer/server"
|
||||
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/config"
|
||||
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/escpos"
|
||||
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/printer"
|
||||
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/printqueue"
|
||||
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/receipt"
|
||||
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/safehttp"
|
||||
"uberbringer/internal/app/uberbringer/server"
|
||||
"uberbringer/internal/pkg/config"
|
||||
"uberbringer/internal/pkg/escpos"
|
||||
"uberbringer/internal/pkg/printer"
|
||||
"uberbringer/internal/pkg/printqueue"
|
||||
"uberbringer/internal/pkg/receipt"
|
||||
"uberbringer/internal/pkg/safehttp"
|
||||
)
|
||||
|
||||
// sentryFlushTimeout bounds how long shutdown waits for queued error reports.
|
||||
const sentryFlushTimeout = 2 * time.Second
|
||||
|
||||
// serve loads the config, wires every component and runs until ctx is
|
||||
// cancelled.
|
||||
// serve loads the config at configPath and runs the daemon on the address it
|
||||
// names until ctx is cancelled.
|
||||
func serve(ctx context.Context, configPath string, build BuildInfo, out io.Writer) error {
|
||||
cfg, err := config.Load(configPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return run(ctx, cfg, build, out, listenTCP)
|
||||
}
|
||||
|
||||
// listenFunc opens the HTTP listener on addr.
|
||||
type listenFunc func(ctx context.Context, addr string) (net.Listener, error)
|
||||
|
||||
func listenTCP(ctx context.Context, addr string) (net.Listener, error) {
|
||||
var lc net.ListenConfig
|
||||
return lc.Listen(ctx, "tcp", addr)
|
||||
}
|
||||
|
||||
// run wires every component from cfg, opens the HTTP listener with listen
|
||||
// once the wiring has succeeded, and serves until ctx is cancelled.
|
||||
func run(ctx context.Context, cfg *config.Config, build BuildInfo, out io.Writer, listen listenFunc) error {
|
||||
logger := newLogger(cfg.Log, os.Stderr)
|
||||
printBanner(out, build)
|
||||
|
||||
@@ -98,8 +112,7 @@ func serve(ctx context.Context, configPath string, build BuildInfo, out io.Write
|
||||
}, queue, printerClient, logger)
|
||||
|
||||
addr := net.JoinHostPort(cfg.WebServer.BindIP, strconv.Itoa(cfg.WebServer.Port))
|
||||
var lc net.ListenConfig
|
||||
ln, err := lc.Listen(ctx, "tcp", addr)
|
||||
ln, err := listen(ctx, addr)
|
||||
if err != nil {
|
||||
return fmt.Errorf("listening on %s: %w", addr, err)
|
||||
}
|
||||
|
||||
@@ -14,6 +14,8 @@ import (
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"uberbringer/internal/pkg/config"
|
||||
)
|
||||
|
||||
// fakePrinter records everything sent to it.
|
||||
@@ -55,26 +57,15 @@ func (p *fakePrinter) received() []byte {
|
||||
return bytes.Clone(p.data.Bytes())
|
||||
}
|
||||
|
||||
func freePort(t *testing.T) int {
|
||||
t.Helper()
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer ln.Close()
|
||||
return ln.Addr().(*net.TCPAddr).Port
|
||||
}
|
||||
|
||||
// TestServeEndToEnd runs the real wiring: config, queue, renderer, printer
|
||||
// client and HTTP server, then checks a graceful shutdown.
|
||||
// client and HTTP server, then checks a graceful shutdown. The HTTP listener
|
||||
// is bound before the daemon starts and handed to it, so no other process can
|
||||
// take its port in between.
|
||||
func TestServeEndToEnd(t *testing.T) {
|
||||
printer := startFakePrinter(t)
|
||||
port := freePort(t)
|
||||
const secret = "end-to-end-secret-end-to-end-secret!"
|
||||
path := filepath.Join(t.TempDir(), "config.toml")
|
||||
cfg := fmt.Sprintf(`
|
||||
[webserver]
|
||||
port = %d
|
||||
body := fmt.Sprintf(`
|
||||
[api]
|
||||
secret = %q
|
||||
[printer]
|
||||
@@ -82,17 +73,27 @@ address = "127.0.0.1"
|
||||
port = %d
|
||||
[log]
|
||||
level = "error"
|
||||
`, port, secret, printer.addr.Port)
|
||||
if err := os.WriteFile(path, []byte(cfg), 0o600); err != nil {
|
||||
`, secret, printer.addr.Port)
|
||||
if err := os.WriteFile(path, []byte(body), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg, err := config.Load(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = ln.Close() })
|
||||
listen := func(context.Context, string) (net.Listener, error) { return ln, nil }
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
served := make(chan error, 1)
|
||||
go func() { served <- serve(ctx, path, BuildInfo{Version: "test"}, io.Discard) }()
|
||||
go func() { served <- run(ctx, cfg, BuildInfo{Version: "test"}, io.Discard, listen) }()
|
||||
|
||||
base := fmt.Sprintf("http://127.0.0.1:%d", port)
|
||||
base := "http://" + ln.Addr().String()
|
||||
waitFor(t, func() bool {
|
||||
resp, err := http.Get(base + "/")
|
||||
if err != nil {
|
||||
|
||||
@@ -18,11 +18,11 @@ func requireBearerToken(secret []byte) fiber.Handler {
|
||||
token, ok := bearerToken(c.Get(fiber.HeaderAuthorization))
|
||||
if !ok {
|
||||
c.Set(fiber.HeaderWWWAuthenticate, `Bearer realm="uberbringer"`)
|
||||
return fiber.NewError(fiber.StatusUnauthorized, "missing bearer token")
|
||||
return newAPIError(codeUnauthorized.withMessage("missing bearer token"))
|
||||
}
|
||||
if _, err := parser.Parse(token, keyFunc); err != nil {
|
||||
c.Set(fiber.HeaderWWWAuthenticate, `Bearer realm="uberbringer", error="invalid_token"`)
|
||||
return fiber.NewError(fiber.StatusUnauthorized, "invalid or expired token")
|
||||
return newAPIError(codeUnauthorized.withMessage("invalid or expired token"))
|
||||
}
|
||||
return c.Next()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"runtime/debug"
|
||||
"strconv"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/gofiber/fiber/v3/middleware/requestid"
|
||||
)
|
||||
|
||||
// errorCode is a stable, machine-readable error identifier together with its
|
||||
// HTTP status and the message sent when no more specific one is given.
|
||||
// Clients match on code; the message is for people and may change.
|
||||
type errorCode struct {
|
||||
status int
|
||||
code string
|
||||
message string
|
||||
}
|
||||
|
||||
// The codes the API answers with.
|
||||
var (
|
||||
codeBadRequest = errorCode{fiber.StatusBadRequest, "bad_request", "malformed request"}
|
||||
codeInvalidJob = errorCode{fiber.StatusBadRequest, "invalid_job", "invalid job"}
|
||||
codeUnauthorized = errorCode{fiber.StatusUnauthorized, "unauthorized", "missing or invalid bearer token"}
|
||||
codeNotFound = errorCode{fiber.StatusNotFound, "not_found", "not found"}
|
||||
codeJobNotFound = errorCode{fiber.StatusNotFound, "job_not_found", "job not found"}
|
||||
codeMethodNotAllowed = errorCode{fiber.StatusMethodNotAllowed, "method_not_allowed", "method not allowed"}
|
||||
codeRequestTimeout = errorCode{fiber.StatusRequestTimeout, "request_timeout", "request was not received in time"}
|
||||
codeBodyTooLarge = errorCode{fiber.StatusRequestEntityTooLarge, "body_too_large", "request body is too large"}
|
||||
codeRateLimited = errorCode{fiber.StatusTooManyRequests, "rate_limited", "too many requests, try again later"}
|
||||
codeHeadersTooLarge = errorCode{fiber.StatusRequestHeaderFieldsTooLarge, "headers_too_large", "request headers are too large"}
|
||||
codeInternal = errorCode{fiber.StatusInternalServerError, "internal_error", "internal server error"}
|
||||
codeNotImplemented = errorCode{fiber.StatusNotImplemented, "not_implemented", "not implemented"}
|
||||
codeQueueFull = errorCode{fiber.StatusServiceUnavailable, "queue_full", "print queue is full, try again shortly"}
|
||||
codeShuttingDown = errorCode{fiber.StatusServiceUnavailable, "shutting_down", "server is shutting down"}
|
||||
)
|
||||
|
||||
// fiberCodes are the codes for the statuses Fiber and fasthttp answer with on
|
||||
// their own, e.g. for an unknown route or a body over the limit.
|
||||
var fiberCodes = []errorCode{
|
||||
codeBadRequest, codeNotFound, codeMethodNotAllowed, codeRequestTimeout, codeBodyTooLarge,
|
||||
codeRateLimited, codeHeadersTooLarge, codeInternal, codeNotImplemented,
|
||||
}
|
||||
|
||||
// fiberCode returns the code for a status Fiber raised itself, or http_<status>
|
||||
// for one without its own code.
|
||||
func fiberCode(status int) errorCode {
|
||||
for _, c := range fiberCodes {
|
||||
if c.status == status {
|
||||
return c
|
||||
}
|
||||
}
|
||||
return errorCode{status, "http_" + strconv.Itoa(status), http.StatusText(status)}
|
||||
}
|
||||
|
||||
// withMessage returns c with message in place of its default message.
|
||||
func (c errorCode) withMessage(message string) errorCode {
|
||||
c.message = message
|
||||
return c
|
||||
}
|
||||
|
||||
// apiError is a refusal: an answer the client caused or has to wait out. It
|
||||
// is sent with its code and is not logged as a failure.
|
||||
type apiError struct {
|
||||
errorCode
|
||||
details []string
|
||||
}
|
||||
|
||||
func newAPIError(code errorCode, details ...string) *apiError {
|
||||
return &apiError{errorCode: code, details: details}
|
||||
}
|
||||
|
||||
func (e *apiError) Error() string { return e.message }
|
||||
|
||||
// errorResponse is the JSON body of every error.
|
||||
type errorResponse struct {
|
||||
Error string `json:"error"`
|
||||
Code string `json:"code"`
|
||||
Details []string `json:"details,omitempty"`
|
||||
}
|
||||
|
||||
// panicError carries a value recovered from a panic in a handler.
|
||||
type panicError struct{ value any }
|
||||
|
||||
func (e *panicError) Error() string { return fmt.Sprintf("panic: %v", e.value) }
|
||||
|
||||
// handleError is the Fiber error handler: it answers every error with an
|
||||
// errorResponse. Refusals, the server's own and Fiber's, are expected, so the
|
||||
// request line is their only log. Any other error is a failure the server
|
||||
// did not expect; it is logged and reported to Sentry here, once. Fiber's own
|
||||
// message is never sent, since it can quote bytes of the request.
|
||||
func (s *Server) handleError(c fiber.Ctx, err error) error {
|
||||
var (
|
||||
panicErr *panicError
|
||||
apiErr *apiError
|
||||
fiberErr *fiber.Error
|
||||
)
|
||||
switch {
|
||||
case errors.As(err, &panicErr):
|
||||
// reportPanic has already logged and reported it.
|
||||
apiErr = newAPIError(codeInternal)
|
||||
case errors.As(err, &apiErr):
|
||||
case errors.As(err, &fiberErr):
|
||||
apiErr = newAPIError(fiberCode(fiberErr.Code))
|
||||
default:
|
||||
s.logger.LogAttrs(c.Context(), slog.LevelError, "request failed",
|
||||
slog.String("method", c.Method()),
|
||||
slog.String("path", c.Path()),
|
||||
slog.String("request_id", requestid.FromContext(c)),
|
||||
slog.Any("err", err),
|
||||
)
|
||||
hubFrom(c).CaptureException(err)
|
||||
apiErr = newAPIError(codeInternal)
|
||||
}
|
||||
return c.Status(apiErr.status).JSON(errorResponse{
|
||||
Error: apiErr.message,
|
||||
Code: apiErr.code,
|
||||
Details: apiErr.details,
|
||||
})
|
||||
}
|
||||
|
||||
// reportPanic logs a recovered panic with its stack and reports it to Sentry.
|
||||
// The recover middleware calls it from its deferred function, before the
|
||||
// stack unwinds, so both show where the panic happened.
|
||||
func (s *Server) reportPanic(c fiber.Ctx, r any) {
|
||||
s.logger.LogAttrs(c.Context(), slog.LevelError, "panic",
|
||||
slog.String("method", c.Method()),
|
||||
slog.String("path", c.Path()),
|
||||
slog.String("request_id", requestid.FromContext(c)),
|
||||
slog.String("panic", fmt.Sprint(r)),
|
||||
slog.String("stack", string(debug.Stack())),
|
||||
)
|
||||
hubFrom(c).Recover(r)
|
||||
}
|
||||
|
||||
// recoveredPanic turns a recovered panic into the error handleError answers.
|
||||
func recoveredPanic(_ fiber.Ctx, r any) error {
|
||||
return &panicError{value: r}
|
||||
}
|
||||
@@ -12,53 +12,15 @@ import (
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
|
||||
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/escpos"
|
||||
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/printer"
|
||||
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/printqueue"
|
||||
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/receipt"
|
||||
"uberbringer/internal/pkg/escpos"
|
||||
"uberbringer/internal/pkg/printer"
|
||||
"uberbringer/internal/pkg/printqueue"
|
||||
"uberbringer/internal/pkg/receipt"
|
||||
)
|
||||
|
||||
// healthTimeout bounds the printer status check behind /healthz.
|
||||
const healthTimeout = 3 * time.Second
|
||||
|
||||
// apiError is an error with an HTTP status and optional details.
|
||||
type apiError struct {
|
||||
status int
|
||||
message string
|
||||
details []string
|
||||
}
|
||||
|
||||
func (e *apiError) Error() string { return e.message }
|
||||
|
||||
// errorResponse is the JSON body of every error.
|
||||
type errorResponse struct {
|
||||
Error string `json:"error"`
|
||||
Details []string `json:"details,omitempty"`
|
||||
}
|
||||
|
||||
// handleError turns errors into JSON responses. Server errors are logged and
|
||||
// reported to Sentry here, once, at the HTTP boundary.
|
||||
func (s *Server) handleError(c fiber.Ctx, err error) error {
|
||||
resp := errorResponse{Error: "internal server error"}
|
||||
status := fiber.StatusInternalServerError
|
||||
|
||||
var (
|
||||
apiErr *apiError
|
||||
fiberErr *fiber.Error
|
||||
)
|
||||
switch {
|
||||
case errors.As(err, &apiErr):
|
||||
status, resp.Error, resp.Details = apiErr.status, apiErr.message, apiErr.details
|
||||
case errors.As(err, &fiberErr):
|
||||
status, resp.Error = fiberErr.Code, fiberErr.Message
|
||||
}
|
||||
if status >= fiber.StatusInternalServerError {
|
||||
s.logger.Error("request failed", "path", c.Path(), "err", err)
|
||||
hubFrom(c).CaptureException(err)
|
||||
}
|
||||
return c.Status(status).JSON(resp)
|
||||
}
|
||||
|
||||
func (s *Server) handleIndex(c fiber.Ctx) error {
|
||||
info := s.config.Info
|
||||
return c.JSON(fiber.Map{
|
||||
@@ -83,7 +45,7 @@ func (s *Server) handlePrint(c fiber.Ctx) error {
|
||||
if err := job.Validate(); err != nil {
|
||||
var ve *receipt.ValidationError
|
||||
if errors.As(err, &ve) {
|
||||
return &apiError{status: fiber.StatusBadRequest, message: "invalid job", details: ve.Problems}
|
||||
return newAPIError(codeInvalidJob, ve.Problems...)
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -92,9 +54,9 @@ func (s *Server) handlePrint(c fiber.Ctx) error {
|
||||
switch {
|
||||
case errors.Is(err, printqueue.ErrQueueFull):
|
||||
c.Set(fiber.HeaderRetryAfter, "10")
|
||||
return fiber.NewError(fiber.StatusServiceUnavailable, "print queue is full, try again shortly")
|
||||
return newAPIError(codeQueueFull)
|
||||
case errors.Is(err, printqueue.ErrClosed):
|
||||
return fiber.NewError(fiber.StatusServiceUnavailable, "server is shutting down")
|
||||
return newAPIError(codeShuttingDown)
|
||||
case err != nil:
|
||||
return fmt.Errorf("submitting job: %w", err)
|
||||
}
|
||||
@@ -102,8 +64,9 @@ func (s *Server) handlePrint(c fiber.Ctx) error {
|
||||
return c.Status(fiber.StatusAccepted).JSON(status)
|
||||
}
|
||||
|
||||
// decodeJob strictly decodes a job body. Unknown fields are rejected so typos
|
||||
// and the pre-refactor {"data": [...]} format fail loudly.
|
||||
// decodeJob strictly decodes a job body. Unknown fields are rejected so that
|
||||
// typos fail loudly. An unknown "data" field gets a message that points to
|
||||
// "elements" and the README instead of the decoder's text.
|
||||
func decodeJob(body []byte) (receipt.Job, error) {
|
||||
var job receipt.Job
|
||||
dec := json.NewDecoder(bytes.NewReader(body))
|
||||
@@ -113,10 +76,10 @@ func decodeJob(body []byte) (receipt.Job, error) {
|
||||
if strings.Contains(err.Error(), `unknown field "data"`) {
|
||||
msg = `the {"data": [...]} format was replaced by {"elements": [...]}; see the README for the element format`
|
||||
}
|
||||
return job, &apiError{status: fiber.StatusBadRequest, message: msg}
|
||||
return job, newAPIError(codeInvalidJob.withMessage(msg))
|
||||
}
|
||||
if _, err := dec.Token(); !errors.Is(err, io.EOF) {
|
||||
return job, &apiError{status: fiber.StatusBadRequest, message: "request body has trailing data after the job"}
|
||||
return job, newAPIError(codeInvalidJob.withMessage("request body has trailing data after the job"))
|
||||
}
|
||||
return job, nil
|
||||
}
|
||||
@@ -126,11 +89,11 @@ func (s *Server) handleJob(c fiber.Ctx) error {
|
||||
// Clone: fasthttp reuses the buffer behind route params.
|
||||
id, err := printqueue.ParseJobID(strings.Clone(c.Params("id")))
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusNotFound, "job not found")
|
||||
return newAPIError(codeJobNotFound)
|
||||
}
|
||||
status, err := s.jobs.Status(id)
|
||||
if errors.Is(err, printqueue.ErrNotFound) {
|
||||
return fiber.NewError(fiber.StatusNotFound, "job not found")
|
||||
return newAPIError(codeJobNotFound)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/getsentry/sentry-go"
|
||||
@@ -15,9 +16,9 @@ import (
|
||||
recoverer "github.com/gofiber/fiber/v3/middleware/recover" // avoids shadowing the recover builtin
|
||||
"github.com/gofiber/fiber/v3/middleware/requestid"
|
||||
|
||||
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/escpos"
|
||||
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/printqueue"
|
||||
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/receipt"
|
||||
"uberbringer/internal/pkg/escpos"
|
||||
"uberbringer/internal/pkg/printqueue"
|
||||
"uberbringer/internal/pkg/receipt"
|
||||
)
|
||||
|
||||
// shutdownTimeout bounds how long in-flight requests may take to finish.
|
||||
@@ -113,22 +114,30 @@ func New(config Config, jobs Jobs, printer Printer, logger *slog.Logger) *Server
|
||||
TrustProxyConfig: fiber.TrustProxyConfig{Proxies: config.TrustedProxies},
|
||||
})
|
||||
|
||||
s.app.Use(recoverer.New())
|
||||
s.app.Use(sentryMiddleware)
|
||||
s.app.Use(requestid.New(requestid.Config{Generator: config.RequestID}))
|
||||
// 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}))
|
||||
|
||||
s.app.Get("/", s.handleIndex)
|
||||
s.app.Get("/robots.txt", handleRobots)
|
||||
s.app.Get("/healthz", s.handleHealth)
|
||||
s.app.Get("/healthz", noStore, s.handleHealth)
|
||||
|
||||
api := s.app.Group("/api/v1",
|
||||
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 fiber.ErrTooManyRequests },
|
||||
LimitReached: func(fiber.Ctx) error { return newAPIError(codeRateLimited) },
|
||||
}),
|
||||
requireBearerToken(config.Secret),
|
||||
)
|
||||
@@ -152,19 +161,22 @@ func (s *Server) Serve(ctx context.Context, ln net.Listener) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// logRequests logs every request once, after the error handler has set the
|
||||
// final status. Only the path is logged, never the query string.
|
||||
// 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 handlerErr := s.handleError(c, err); handlerErr != nil {
|
||||
return handlerErr
|
||||
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.LevelError
|
||||
level = slog.LevelWarn
|
||||
}
|
||||
s.logger.LogAttrs(c.Context(), level, "request",
|
||||
slog.String("method", c.Method()),
|
||||
@@ -180,20 +192,23 @@ func (s *Server) logRequests(c fiber.Ctx) error {
|
||||
// sentryHubKey stores the per-request Sentry hub in fiber Locals.
|
||||
type sentryHubKey struct{}
|
||||
|
||||
// sentryMiddleware reports panics to Sentry with a per-request hub, then
|
||||
// re-panics so the recover middleware can turn them into a 500. Request
|
||||
// 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 sentryMiddleware(c fiber.Ctx) error {
|
||||
func attachSentryHub(c fiber.Ctx) error {
|
||||
hub := sentry.CurrentHub().Clone()
|
||||
hub.Scope().SetTag("method", c.Method())
|
||||
hub.Scope().SetTag("path", c.Path())
|
||||
// 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)
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
hub.Recover(r)
|
||||
panic(r)
|
||||
}
|
||||
}()
|
||||
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()
|
||||
}
|
||||
|
||||
|
||||
@@ -1,25 +1,30 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/getsentry/sentry-go"
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
|
||||
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/escpos"
|
||||
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/printer"
|
||||
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/printqueue"
|
||||
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/receipt"
|
||||
"uberbringer/internal/pkg/escpos"
|
||||
"uberbringer/internal/pkg/printer"
|
||||
"uberbringer/internal/pkg/printqueue"
|
||||
"uberbringer/internal/pkg/receipt"
|
||||
)
|
||||
|
||||
var testSecret = []byte("0123456789abcdef0123456789abcdef")
|
||||
@@ -28,6 +33,7 @@ type fakeJobs struct {
|
||||
mu sync.Mutex
|
||||
submitted []receipt.Job
|
||||
submitErr error
|
||||
statusErr error
|
||||
statuses map[printqueue.JobID]printqueue.Status
|
||||
nextID printqueue.JobID
|
||||
}
|
||||
@@ -47,6 +53,9 @@ func (f *fakeJobs) Submit(job receipt.Job) (printqueue.Status, error) {
|
||||
func (f *fakeJobs) Status(id printqueue.JobID) (printqueue.Status, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
if f.statusErr != nil {
|
||||
return printqueue.Status{}, f.statusErr
|
||||
}
|
||||
st, ok := f.statuses[id]
|
||||
if !ok {
|
||||
return printqueue.Status{}, printqueue.ErrNotFound
|
||||
@@ -89,12 +98,26 @@ func newJobID(t *testing.T) printqueue.JobID {
|
||||
return id
|
||||
}
|
||||
|
||||
func newTestServer(t *testing.T, jobs *fakeJobs, p Printer) *Server {
|
||||
// newTestServer returns a server that discards its logs. opts adjust the
|
||||
// config before the server is built.
|
||||
func newTestServer(t *testing.T, jobs *fakeJobs, p Printer, opts ...func(*Config)) *Server {
|
||||
t.Helper()
|
||||
return newServer(t, jobs, p, slog.New(slog.NewTextHandler(io.Discard, nil)), opts)
|
||||
}
|
||||
|
||||
// newLoggedServer is newTestServer with its JSON log lines kept for the test.
|
||||
func newLoggedServer(t *testing.T, jobs *fakeJobs, p Printer, opts ...func(*Config)) (*Server, *logBuffer) {
|
||||
t.Helper()
|
||||
logs := &logBuffer{}
|
||||
return newServer(t, jobs, p, slog.New(slog.NewJSONHandler(logs, nil)), opts), logs
|
||||
}
|
||||
|
||||
func newServer(t *testing.T, jobs *fakeJobs, p Printer, logger *slog.Logger, opts []func(*Config)) *Server {
|
||||
t.Helper()
|
||||
if jobs.statuses == nil {
|
||||
jobs.statuses = map[printqueue.JobID]printqueue.Status{}
|
||||
}
|
||||
return New(Config{
|
||||
cfg := Config{
|
||||
Info: Info{Project: "Überbringer", Version: "test"},
|
||||
Secret: testSecret,
|
||||
RateLimit: 1000,
|
||||
@@ -108,7 +131,101 @@ func newTestServer(t *testing.T, jobs *fakeJobs, p Printer) *Server {
|
||||
RequestID: func() string { return "req_test" },
|
||||
|
||||
HealthRecheckDelay: time.Millisecond,
|
||||
}, jobs, p, slog.New(slog.NewTextHandler(io.Discard, nil)))
|
||||
}
|
||||
for _, opt := range opts {
|
||||
opt(&cfg)
|
||||
}
|
||||
return New(cfg, jobs, p, logger)
|
||||
}
|
||||
|
||||
// logBuffer collects the server's JSON log lines.
|
||||
type logBuffer struct {
|
||||
mu sync.Mutex
|
||||
buf bytes.Buffer
|
||||
}
|
||||
|
||||
func (b *logBuffer) Write(p []byte) (int, error) {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
return b.buf.Write(p)
|
||||
}
|
||||
|
||||
// lines returns every log line written so far, decoded.
|
||||
func (b *logBuffer) lines(t *testing.T) []map[string]any {
|
||||
t.Helper()
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
var lines []map[string]any
|
||||
for line := range bytes.Lines(b.buf.Bytes()) {
|
||||
var parsed map[string]any
|
||||
if err := json.Unmarshal(line, &parsed); err != nil {
|
||||
t.Fatalf("log line %q: %v", line, err)
|
||||
}
|
||||
lines = append(lines, parsed)
|
||||
}
|
||||
return lines
|
||||
}
|
||||
|
||||
// linesAt returns the lines with message msg at level, or at any level when
|
||||
// level is empty.
|
||||
func linesAt(lines []map[string]any, level, msg string) []map[string]any {
|
||||
var found []map[string]any
|
||||
for _, line := range lines {
|
||||
if line["msg"] == msg && (level == "" || line["level"] == level) {
|
||||
found = append(found, line)
|
||||
}
|
||||
}
|
||||
return found
|
||||
}
|
||||
|
||||
func errorLines(lines []map[string]any) []map[string]any {
|
||||
var found []map[string]any
|
||||
for _, line := range lines {
|
||||
if line["level"] == slog.LevelError.String() {
|
||||
found = append(found, line)
|
||||
}
|
||||
}
|
||||
return found
|
||||
}
|
||||
|
||||
// fakeTransport records the events sent to Sentry.
|
||||
type fakeTransport struct {
|
||||
mu sync.Mutex
|
||||
events []*sentry.Event
|
||||
}
|
||||
|
||||
func (f *fakeTransport) Flush(time.Duration) bool { return true }
|
||||
func (f *fakeTransport) FlushWithContext(context.Context) bool { return true }
|
||||
func (f *fakeTransport) Configure(sentry.ClientOptions) {}
|
||||
func (f *fakeTransport) Close() {}
|
||||
|
||||
func (f *fakeTransport) SendEvent(event *sentry.Event) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.events = append(f.events, event)
|
||||
}
|
||||
|
||||
func (f *fakeTransport) count() int {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
return len(f.events)
|
||||
}
|
||||
|
||||
// captureSentryEvents binds a Sentry client that records its events to the
|
||||
// current hub until the test ends.
|
||||
func captureSentryEvents(t *testing.T) *fakeTransport {
|
||||
t.Helper()
|
||||
t.Setenv("SENTRY_DSN", "")
|
||||
transport := &fakeTransport{}
|
||||
client, err := sentry.NewClient(sentry.ClientOptions{Transport: transport})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
hub := sentry.CurrentHub()
|
||||
previous := hub.Client()
|
||||
hub.BindClient(client)
|
||||
t.Cleanup(func() { hub.BindClient(previous) })
|
||||
return transport
|
||||
}
|
||||
|
||||
func token(t *testing.T, secret []byte, method jwt.SigningMethod, claims jwt.Claims) string {
|
||||
@@ -120,23 +237,62 @@ func token(t *testing.T, secret []byte, method jwt.SigningMethod, claims jwt.Cla
|
||||
return signed
|
||||
}
|
||||
|
||||
// validToken returns a token whose only claim is user_id.
|
||||
func validToken(t *testing.T) string {
|
||||
return token(t, testSecret, jwt.SigningMethodHS256, jwt.MapClaims{"user_id": "uberbringer"})
|
||||
}
|
||||
|
||||
func do(t *testing.T, s *Server, req *http.Request) (*http.Response, map[string]any) {
|
||||
// send runs req through the server and returns the response and its body.
|
||||
func send(t *testing.T, s *Server, req *http.Request) (*http.Response, []byte) {
|
||||
t.Helper()
|
||||
resp, err := s.app.Test(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return resp, body
|
||||
}
|
||||
|
||||
// do is send with a JSON body decoded; it is nil for routes that answer
|
||||
// plain text.
|
||||
func do(t *testing.T, s *Server, req *http.Request) (*http.Response, map[string]any) {
|
||||
t.Helper()
|
||||
resp, body := send(t, s, req)
|
||||
var parsed map[string]any
|
||||
_ = json.Unmarshal(body, &parsed) // some routes return plain text
|
||||
if strings.HasPrefix(resp.Header.Get(fiber.HeaderContentType), fiber.MIMEApplicationJSON) {
|
||||
if err := json.Unmarshal(body, &parsed); err != nil {
|
||||
t.Fatalf("response body %q: %v", body, err)
|
||||
}
|
||||
}
|
||||
return resp, parsed
|
||||
}
|
||||
|
||||
// expectError checks that the response is an error with the given status
|
||||
// and code, in the shape every error has, and returns the decoded body.
|
||||
func expectError(t *testing.T, resp *http.Response, body []byte, status int, code string) errorResponse {
|
||||
t.Helper()
|
||||
if resp.StatusCode != status {
|
||||
t.Fatalf("status = %d, want %d (%s)", resp.StatusCode, status, body)
|
||||
}
|
||||
if ct := resp.Header.Get(fiber.HeaderContentType); !strings.HasPrefix(ct, fiber.MIMEApplicationJSON) {
|
||||
t.Fatalf("Content-Type = %q, want JSON", ct)
|
||||
}
|
||||
var e errorResponse
|
||||
dec := json.NewDecoder(bytes.NewReader(body))
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(&e); err != nil {
|
||||
t.Fatalf("error body %s: %v", body, err)
|
||||
}
|
||||
if e.Code != code || e.Error == "" {
|
||||
t.Fatalf("error body %s, want code %q and a message", body, code)
|
||||
}
|
||||
return e
|
||||
}
|
||||
|
||||
func printRequest(t *testing.T, body, auth string) *http.Request {
|
||||
t.Helper()
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/print", strings.NewReader(body))
|
||||
@@ -155,6 +311,7 @@ func TestPrintAuth(t *testing.T) {
|
||||
})
|
||||
wrongKey := token(t, []byte("another-secret-another-secret-xx"), jwt.SigningMethodHS256, jwt.MapClaims{})
|
||||
hs512 := token(t, testSecret, jwt.SigningMethodHS512, jwt.MapClaims{})
|
||||
withSubject := token(t, testSecret, jwt.SigningMethodHS256, jwt.RegisteredClaims{Subject: "till-1"})
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
@@ -167,17 +324,22 @@ func TestPrintAuth(t *testing.T) {
|
||||
{"wrong key", "Bearer " + wrongKey, http.StatusUnauthorized},
|
||||
{"expired", "Bearer " + expired, http.StatusUnauthorized},
|
||||
{"wrong algorithm", "Bearer " + hs512, http.StatusUnauthorized},
|
||||
{"legacy install.sh token", "Bearer " + validToken(t), http.StatusAccepted},
|
||||
{"token with a subject", "Bearer " + withSubject, http.StatusAccepted},
|
||||
{"token with only user_id", "Bearer " + validToken(t), http.StatusAccepted},
|
||||
{"lowercase scheme", "bearer " + validToken(t), http.StatusAccepted},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
s := newTestServer(t, &fakeJobs{nextID: newJobID(t)}, &fakePrinter{})
|
||||
resp, body := do(t, s, printRequest(t, validJob, tt.auth))
|
||||
if resp.StatusCode != tt.want {
|
||||
t.Fatalf("status = %d, want %d (%v)", resp.StatusCode, tt.want, body)
|
||||
resp, body := send(t, s, printRequest(t, validJob, tt.auth))
|
||||
if tt.want != http.StatusUnauthorized {
|
||||
if resp.StatusCode != tt.want {
|
||||
t.Fatalf("status = %d, want %d (%s)", resp.StatusCode, tt.want, body)
|
||||
}
|
||||
return
|
||||
}
|
||||
if tt.want == http.StatusUnauthorized && resp.Header.Get("WWW-Authenticate") == "" {
|
||||
expectError(t, resp, body, http.StatusUnauthorized, "unauthorized")
|
||||
if resp.Header.Get("WWW-Authenticate") == "" {
|
||||
t.Error("401 without WWW-Authenticate")
|
||||
}
|
||||
})
|
||||
@@ -187,9 +349,8 @@ func TestPrintAuth(t *testing.T) {
|
||||
func TestPrintQueryTokenIsNotAccepted(t *testing.T) {
|
||||
s := newTestServer(t, &fakeJobs{nextID: newJobID(t)}, &fakePrinter{})
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/print?token="+validToken(t), strings.NewReader(validJob))
|
||||
if resp, _ := do(t, s, req); resp.StatusCode != http.StatusUnauthorized {
|
||||
t.Errorf("status = %d, want 401", resp.StatusCode)
|
||||
}
|
||||
resp, body := send(t, s, req)
|
||||
expectError(t, resp, body, http.StatusUnauthorized, "unauthorized")
|
||||
}
|
||||
|
||||
func TestPrintAccepted(t *testing.T) {
|
||||
@@ -205,6 +366,9 @@ func TestPrintAccepted(t *testing.T) {
|
||||
if loc := resp.Header.Get("Location"); loc != "/api/v1/jobs/job_01h455vb4pex5vsknk084sn02q" {
|
||||
t.Errorf("Location = %q", loc)
|
||||
}
|
||||
if cc := resp.Header.Get(fiber.HeaderCacheControl); cc != "no-store" {
|
||||
t.Errorf("Cache-Control = %q, want no-store", cc)
|
||||
}
|
||||
if len(jobs.submitted) != 1 || jobs.submitted[0].Elements[0].Text != "Hello" {
|
||||
t.Errorf("submitted %+v", jobs.submitted)
|
||||
}
|
||||
@@ -215,7 +379,7 @@ func TestPrintBadRequests(t *testing.T) {
|
||||
name, body, wantErr string
|
||||
}{
|
||||
{"not json", `nope`, "not a valid job"},
|
||||
{"old format", `{"data":[{"type":1,"size":1,"text":"hi"}]}`, `replaced by {"elements": [...]}`},
|
||||
{"data instead of elements", `{"data":[{"type":1,"size":1,"text":"hi"}]}`, `replaced by {"elements": [...]}`},
|
||||
{"unknown element field", `{"elements":[{"type":"text","colour":"red"}]}`, `unknown field "colour"`},
|
||||
{"trailing data", validJob + `{}`, "trailing data"},
|
||||
{"invalid element", `{"elements":[{"type":"text","size":12}]}`, "invalid job"},
|
||||
@@ -224,12 +388,10 @@ func TestPrintBadRequests(t *testing.T) {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
jobs := &fakeJobs{nextID: newJobID(t)}
|
||||
s := newTestServer(t, jobs, &fakePrinter{})
|
||||
resp, body := do(t, s, printRequest(t, tt.body, "Bearer "+validToken(t)))
|
||||
if resp.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("status = %d, want 400 (%v)", resp.StatusCode, body)
|
||||
}
|
||||
if msg, _ := body["error"].(string); !strings.Contains(msg, tt.wantErr) {
|
||||
t.Errorf("error = %q, want it to contain %q", msg, tt.wantErr)
|
||||
resp, body := send(t, s, printRequest(t, tt.body, "Bearer "+validToken(t)))
|
||||
e := expectError(t, resp, body, http.StatusBadRequest, "invalid_job")
|
||||
if !strings.Contains(e.Error, tt.wantErr) {
|
||||
t.Errorf("error = %q, want it to contain %q", e.Error, tt.wantErr)
|
||||
}
|
||||
if len(jobs.submitted) != 0 {
|
||||
t.Error("invalid job was submitted")
|
||||
@@ -240,18 +402,31 @@ func TestPrintBadRequests(t *testing.T) {
|
||||
|
||||
func TestPrintValidationDetails(t *testing.T) {
|
||||
s := newTestServer(t, &fakeJobs{nextID: newJobID(t)}, &fakePrinter{})
|
||||
_, body := do(t, s, printRequest(t, `{"elements":[{"type":"text","size":12},{"type":"qr"}]}`, "Bearer "+validToken(t)))
|
||||
details, _ := body["details"].([]any)
|
||||
if len(details) != 2 {
|
||||
t.Errorf("details = %v, want 2 problems", body["details"])
|
||||
resp, body := send(t, s, printRequest(t, `{"elements":[{"type":"text","size":12},{"type":"qr"}]}`, "Bearer "+validToken(t)))
|
||||
if e := expectError(t, resp, body, http.StatusBadRequest, "invalid_job"); len(e.Details) != 2 {
|
||||
t.Errorf("details = %v, want 2 problems", e.Details)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrintQueueFull(t *testing.T) {
|
||||
s := newTestServer(t, &fakeJobs{submitErr: printqueue.ErrQueueFull}, &fakePrinter{})
|
||||
resp, _ := do(t, s, printRequest(t, validJob, "Bearer "+validToken(t)))
|
||||
if resp.StatusCode != http.StatusServiceUnavailable || resp.Header.Get("Retry-After") == "" {
|
||||
t.Errorf("status = %d, Retry-After = %q", resp.StatusCode, resp.Header.Get("Retry-After"))
|
||||
func TestPrintQueueRefusals(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
err error
|
||||
code string
|
||||
wantRetryAfter bool
|
||||
}{
|
||||
{"queue full", printqueue.ErrQueueFull, "queue_full", true},
|
||||
{"shutting down", printqueue.ErrClosed, "shutting_down", false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
s := newTestServer(t, &fakeJobs{submitErr: tt.err}, &fakePrinter{})
|
||||
resp, body := send(t, s, printRequest(t, validJob, "Bearer "+validToken(t)))
|
||||
expectError(t, resp, body, http.StatusServiceUnavailable, tt.code)
|
||||
if got := resp.Header.Get("Retry-After") != ""; got != tt.wantRetryAfter {
|
||||
t.Errorf("Retry-After = %q", resp.Header.Get("Retry-After"))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -261,32 +436,28 @@ func TestJobStatus(t *testing.T) {
|
||||
id: {ID: id, State: printqueue.StateDone, Attempts: 1},
|
||||
}}
|
||||
s := newTestServer(t, jobs, &fakePrinter{})
|
||||
get := func(path, auth string) *http.Request {
|
||||
req := httptest.NewRequest(http.MethodGet, path, nil)
|
||||
if auth != "" {
|
||||
req.Header.Set("Authorization", auth)
|
||||
}
|
||||
return req
|
||||
}
|
||||
auth := "Bearer " + validToken(t)
|
||||
|
||||
tests := []struct {
|
||||
path string
|
||||
want int
|
||||
}{
|
||||
{"/api/v1/jobs/" + id.String(), http.StatusOK},
|
||||
{"/api/v1/jobs/job_01h455vb4pex5vsknk084sn02r", http.StatusNotFound},
|
||||
{"/api/v1/jobs/not-an-id", http.StatusNotFound},
|
||||
resp, body := do(t, s, get("/api/v1/jobs/"+id.String(), auth))
|
||||
if resp.StatusCode != http.StatusOK || body["status"] != "done" {
|
||||
t.Errorf("GET known job = %d %v", resp.StatusCode, body)
|
||||
}
|
||||
for _, tt := range tests {
|
||||
req := httptest.NewRequest(http.MethodGet, tt.path, nil)
|
||||
req.Header.Set("Authorization", auth)
|
||||
resp, body := do(t, s, req)
|
||||
if resp.StatusCode != tt.want {
|
||||
t.Errorf("GET %s = %d, want %d", tt.path, resp.StatusCode, tt.want)
|
||||
}
|
||||
if tt.want == http.StatusOK && body["status"] != "done" {
|
||||
t.Errorf("body = %v", body)
|
||||
}
|
||||
if cc := resp.Header.Get(fiber.HeaderCacheControl); cc != "no-store" {
|
||||
t.Errorf("Cache-Control = %q, want no-store", cc)
|
||||
}
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/jobs/"+id.String(), nil)
|
||||
if resp, _ := do(t, s, req); resp.StatusCode != http.StatusUnauthorized {
|
||||
t.Errorf("unauthenticated status lookup = %d, want 401", resp.StatusCode)
|
||||
for _, path := range []string{"/api/v1/jobs/job_01h455vb4pex5vsknk084sn02r", "/api/v1/jobs/not-an-id"} {
|
||||
resp, raw := send(t, s, get(path, auth))
|
||||
expectError(t, resp, raw, http.StatusNotFound, "job_not_found")
|
||||
}
|
||||
resp, raw := send(t, s, get("/api/v1/jobs/"+id.String(), ""))
|
||||
expectError(t, resp, raw, http.StatusUnauthorized, "unauthorized")
|
||||
}
|
||||
|
||||
func TestHealth(t *testing.T) {
|
||||
@@ -319,6 +490,9 @@ func TestHealth(t *testing.T) {
|
||||
if resp.StatusCode != tt.want {
|
||||
t.Fatalf("status = %d, want %d (%v)", resp.StatusCode, tt.want, body)
|
||||
}
|
||||
if cc := resp.Header.Get(fiber.HeaderCacheControl); cc != "no-store" {
|
||||
t.Errorf("Cache-Control = %q, want no-store", cc)
|
||||
}
|
||||
if got := tt.printer.Calls(); got != tt.wantCalls {
|
||||
t.Errorf("printer queried %d times, want %d", got, tt.wantCalls)
|
||||
}
|
||||
@@ -342,47 +516,334 @@ func TestIndexAndRobotsAndNotFound(t *testing.T) {
|
||||
if resp.StatusCode != 200 || body["Project"] != "Überbringer" || body["Version"] != "test" {
|
||||
t.Errorf("index = %d %v", resp.StatusCode, body)
|
||||
}
|
||||
if resp, _ := do(t, s, httptest.NewRequest(http.MethodGet, "/robots.txt", nil)); resp.StatusCode != 200 {
|
||||
if resp, _ := send(t, s, httptest.NewRequest(http.MethodGet, "/robots.txt", nil)); resp.StatusCode != 200 {
|
||||
t.Errorf("robots = %d", resp.StatusCode)
|
||||
}
|
||||
resp, body = do(t, s, httptest.NewRequest(http.MethodGet, "/nope", nil))
|
||||
if resp.StatusCode != 404 || body["error"] == nil {
|
||||
t.Errorf("404 = %d %v, want JSON error", resp.StatusCode, body)
|
||||
resp, raw := send(t, s, httptest.NewRequest(http.MethodGet, "/nope", nil))
|
||||
if e := expectError(t, resp, raw, http.StatusNotFound, "not_found"); strings.Contains(e.Error, "/nope") {
|
||||
t.Errorf("error = %q; Fiber's own text must not reach the client", e.Error)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMethodNotAllowed(t *testing.T) {
|
||||
s := newTestServer(t, &fakeJobs{}, &fakePrinter{})
|
||||
req := httptest.NewRequest(http.MethodDelete, "/api/v1/print", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+validToken(t))
|
||||
resp, body := send(t, s, req)
|
||||
expectError(t, resp, body, http.StatusMethodNotAllowed, "method_not_allowed")
|
||||
if allow := resp.Header.Get(fiber.HeaderAllow); !strings.Contains(allow, http.MethodPost) {
|
||||
t.Errorf("Allow = %q, want it to list POST", allow)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRateLimitPerClientBehindProxy(t *testing.T) {
|
||||
jobs := &fakeJobs{nextID: newJobID(t), statuses: map[printqueue.JobID]printqueue.Status{}}
|
||||
s := New(Config{
|
||||
Info: Info{Project: "Überbringer"},
|
||||
Secret: testSecret,
|
||||
RateLimit: 2,
|
||||
RateWindow: time.Minute,
|
||||
TrustedProxies: []string{"0.0.0.0/0"},
|
||||
ProxyHeader: "X-Real-IP",
|
||||
BodyLimit: 1 << 20,
|
||||
ReadTimeout: time.Second,
|
||||
WriteTimeout: time.Second,
|
||||
IdleTimeout: time.Second,
|
||||
RequestID: func() string { return "req_test" },
|
||||
}, jobs, &fakePrinter{}, slog.New(slog.NewTextHandler(io.Discard, nil)))
|
||||
|
||||
send := func(clientIP string) int {
|
||||
s := newTestServer(t, &fakeJobs{nextID: newJobID(t)}, &fakePrinter{}, func(c *Config) {
|
||||
c.RateLimit = 2
|
||||
c.TrustedProxies = []string{"0.0.0.0/0"}
|
||||
})
|
||||
sendFrom := func(clientIP string) (*http.Response, []byte) {
|
||||
req := printRequest(t, validJob, "Bearer "+validToken(t))
|
||||
req.Header.Set("X-Real-IP", clientIP)
|
||||
resp, _ := do(t, s, req)
|
||||
return resp.StatusCode
|
||||
return send(t, s, req)
|
||||
}
|
||||
for range 2 {
|
||||
if code := send("203.0.113.1"); code != http.StatusAccepted {
|
||||
t.Fatalf("status = %d, want 202", code)
|
||||
if resp, body := sendFrom("203.0.113.1"); resp.StatusCode != http.StatusAccepted {
|
||||
t.Fatalf("status = %d, want 202 (%s)", resp.StatusCode, body)
|
||||
}
|
||||
}
|
||||
if code := send("203.0.113.1"); code != http.StatusTooManyRequests {
|
||||
t.Errorf("third request status = %d, want 429", code)
|
||||
resp, body := sendFrom("203.0.113.1")
|
||||
expectError(t, resp, body, http.StatusTooManyRequests, "rate_limited")
|
||||
if resp.Header.Get("Retry-After") == "" {
|
||||
t.Error("429 without Retry-After")
|
||||
}
|
||||
if code := send("203.0.113.2"); code != http.StatusAccepted {
|
||||
t.Errorf("other client status = %d, want 202 (limits must be per client)", code)
|
||||
if resp, body := sendFrom("203.0.113.2"); resp.StatusCode != http.StatusAccepted {
|
||||
t.Errorf("other client status = %d, want 202 (limits must be per client): %s", resp.StatusCode, body)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRoutesConform walks every registered route. Each /api/v1 route must
|
||||
// refuse a request without a token, be rate limited and keep to the body
|
||||
// limit; the other routes are public. A route without a case here fails the
|
||||
// test, so none is added without being checked and documented.
|
||||
func TestRoutesConform(t *testing.T) {
|
||||
id := newJobID(t)
|
||||
public := map[string]bool{
|
||||
"GET /": true,
|
||||
"GET /robots.txt": true,
|
||||
"GET /healthz": true,
|
||||
}
|
||||
// Each authenticated route maps to a path that reaches it.
|
||||
authenticated := map[string]string{
|
||||
"POST /api/v1/print": "/api/v1/print",
|
||||
"GET /api/v1/jobs/:id": "/api/v1/jobs/" + id.String(),
|
||||
}
|
||||
|
||||
s := newTestServer(t, &fakeJobs{}, &fakePrinter{})
|
||||
seen := map[string]bool{}
|
||||
for _, route := range s.app.GetRoutes(true) {
|
||||
key := route.Method + " " + route.Path
|
||||
if route.Method == http.MethodHead || seen[key] {
|
||||
continue
|
||||
}
|
||||
seen[key] = true
|
||||
switch path, ok := authenticated[key]; {
|
||||
case ok:
|
||||
t.Run(key, func(t *testing.T) { checkAuthenticatedRoute(t, route.Method, path) })
|
||||
case public[key]:
|
||||
t.Run(key, func(t *testing.T) {
|
||||
resp, body := send(t, s, httptest.NewRequest(route.Method, route.Path, nil))
|
||||
if resp.StatusCode == http.StatusUnauthorized {
|
||||
t.Errorf("public route answered 401: %s", body)
|
||||
}
|
||||
})
|
||||
default:
|
||||
t.Errorf("%s has no conformance case: add one here and a row to the README's API table", key)
|
||||
}
|
||||
}
|
||||
for key := range authenticated {
|
||||
if !seen[key] {
|
||||
t.Errorf("conformance case %s has no route", key)
|
||||
}
|
||||
}
|
||||
for key := range public {
|
||||
if !seen[key] {
|
||||
t.Errorf("conformance case %s has no route", key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// checkAuthenticatedRoute checks the refusals every /api/v1 route shares.
|
||||
func checkAuthenticatedRoute(t *testing.T, method, path string) {
|
||||
request := func(body string, withToken bool) *http.Request {
|
||||
req := httptest.NewRequest(method, path, strings.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
if withToken {
|
||||
req.Header.Set("Authorization", "Bearer "+validToken(t))
|
||||
}
|
||||
return req
|
||||
}
|
||||
// fasthttp does not read the body of a GET, so only other methods send one.
|
||||
body := validJob
|
||||
if method == http.MethodGet {
|
||||
body = ""
|
||||
}
|
||||
|
||||
t.Run("requires a token", func(t *testing.T) {
|
||||
s := newTestServer(t, &fakeJobs{nextID: newJobID(t)}, &fakePrinter{})
|
||||
resp, raw := send(t, s, request(body, false))
|
||||
expectError(t, resp, raw, http.StatusUnauthorized, "unauthorized")
|
||||
if resp.Header.Get("WWW-Authenticate") == "" {
|
||||
t.Error("401 without WWW-Authenticate")
|
||||
}
|
||||
if cc := resp.Header.Get(fiber.HeaderCacheControl); cc != "no-store" {
|
||||
t.Errorf("Cache-Control = %q, want no-store", cc)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("is rate limited", func(t *testing.T) {
|
||||
s := newTestServer(t, &fakeJobs{nextID: newJobID(t)}, &fakePrinter{}, func(c *Config) { c.RateLimit = 1 })
|
||||
if resp, raw := send(t, s, request(body, true)); resp.StatusCode == http.StatusTooManyRequests {
|
||||
t.Fatalf("first request was rate limited: %s", raw)
|
||||
}
|
||||
resp, raw := send(t, s, request(body, true))
|
||||
expectError(t, resp, raw, http.StatusTooManyRequests, "rate_limited")
|
||||
if n, err := strconv.Atoi(resp.Header.Get("Retry-After")); err != nil || n < 1 {
|
||||
t.Errorf("Retry-After = %q, want a positive number of seconds", resp.Header.Get("Retry-After"))
|
||||
}
|
||||
})
|
||||
|
||||
if method == http.MethodGet {
|
||||
return
|
||||
}
|
||||
t.Run("keeps to the body limit", func(t *testing.T) {
|
||||
// The token is valid so that the request is refused for its size
|
||||
// alone, and is logged with that status.
|
||||
s, logs := newLoggedServer(t, &fakeJobs{nextID: newJobID(t)}, &fakePrinter{}, func(c *Config) { c.BodyLimit = 512 })
|
||||
req := request(strings.Repeat(" ", 1024)+body, true)
|
||||
req.URL.Scheme, req.URL.Host, req.RequestURI = "http", "uberbringer.test", ""
|
||||
resp, err := serveInMemory(t, s).Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
raw, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
expectError(t, resp, raw, http.StatusRequestEntityTooLarge, "body_too_large")
|
||||
requests := linesAt(logs.lines(t), "", "request")
|
||||
if len(requests) != 1 || requests[0]["status"] != float64(http.StatusRequestEntityTooLarge) {
|
||||
t.Errorf("request lines = %v, want one with status 413", requests)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// serveInMemory serves s on an in-memory listener until the test ends and
|
||||
// returns a client connected to it. Requests then pass through the whole
|
||||
// fasthttp server, which refuses some itself, such as a body over the
|
||||
// limit; app.Test returns those refusals as errors instead of responses.
|
||||
func serveInMemory(t *testing.T, s *Server) *http.Client {
|
||||
t.Helper()
|
||||
ln := &pipeListener{conns: make(chan net.Conn), closed: make(chan struct{})}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
served := make(chan error, 1)
|
||||
go func() { served <- s.Serve(ctx, ln) }()
|
||||
transport := &http.Transport{DialContext: ln.dial}
|
||||
t.Cleanup(func() {
|
||||
transport.CloseIdleConnections()
|
||||
cancel()
|
||||
if err := <-served; err != nil {
|
||||
t.Errorf("Serve: %v", err)
|
||||
}
|
||||
})
|
||||
return &http.Client{Transport: transport}
|
||||
}
|
||||
|
||||
// pipeListener is a net.Listener whose connections are net.Pipe pairs.
|
||||
type pipeListener struct {
|
||||
conns chan net.Conn
|
||||
closed chan struct{}
|
||||
closeOnce sync.Once
|
||||
}
|
||||
|
||||
func (l *pipeListener) Accept() (net.Conn, error) {
|
||||
select {
|
||||
case conn := <-l.conns:
|
||||
return conn, nil
|
||||
case <-l.closed:
|
||||
return nil, net.ErrClosed
|
||||
}
|
||||
}
|
||||
|
||||
func (l *pipeListener) Close() error {
|
||||
l.closeOnce.Do(func() { close(l.closed) })
|
||||
return nil
|
||||
}
|
||||
|
||||
func (l *pipeListener) Addr() net.Addr { return pipeAddr{} }
|
||||
|
||||
func (l *pipeListener) dial(ctx context.Context, _, _ string) (net.Conn, error) {
|
||||
server, client := net.Pipe()
|
||||
select {
|
||||
case l.conns <- server:
|
||||
return client, nil
|
||||
case <-l.closed:
|
||||
return nil, net.ErrClosed
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
}
|
||||
|
||||
type pipeAddr struct{}
|
||||
|
||||
func (pipeAddr) Network() string { return "pipe" }
|
||||
func (pipeAddr) String() string { return "pipe" }
|
||||
|
||||
func TestRefusalsAreNotLoggedAsFailures(t *testing.T) {
|
||||
events := captureSentryEvents(t)
|
||||
tests := []struct {
|
||||
name string
|
||||
jobs *fakeJobs
|
||||
printer *fakePrinter
|
||||
request func(t *testing.T) *http.Request
|
||||
status int
|
||||
level slog.Level
|
||||
}{
|
||||
{
|
||||
name: "queue full",
|
||||
jobs: &fakeJobs{submitErr: printqueue.ErrQueueFull},
|
||||
printer: &fakePrinter{},
|
||||
request: func(t *testing.T) *http.Request { return printRequest(t, validJob, "Bearer "+validToken(t)) },
|
||||
status: http.StatusServiceUnavailable,
|
||||
level: slog.LevelWarn,
|
||||
},
|
||||
{
|
||||
name: "printer unreachable",
|
||||
jobs: &fakeJobs{},
|
||||
printer: &fakePrinter{err: errors.New("connection refused")},
|
||||
request: func(*testing.T) *http.Request { return httptest.NewRequest(http.MethodGet, "/healthz", nil) },
|
||||
status: http.StatusServiceUnavailable,
|
||||
level: slog.LevelWarn,
|
||||
},
|
||||
{
|
||||
name: "no token",
|
||||
jobs: &fakeJobs{},
|
||||
printer: &fakePrinter{},
|
||||
request: func(t *testing.T) *http.Request { return printRequest(t, validJob, "") },
|
||||
status: http.StatusUnauthorized,
|
||||
level: slog.LevelInfo,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
s, logs := newLoggedServer(t, tt.jobs, tt.printer)
|
||||
if resp, body := send(t, s, tt.request(t)); resp.StatusCode != tt.status {
|
||||
t.Fatalf("status = %d, want %d (%s)", resp.StatusCode, tt.status, body)
|
||||
}
|
||||
lines := logs.lines(t)
|
||||
requests := linesAt(lines, "", "request")
|
||||
if len(requests) != 1 || requests[0]["level"] != tt.level.String() || requests[0]["status"] != float64(tt.status) {
|
||||
t.Errorf("request lines = %v, want one at %s with status %d", requests, tt.level, tt.status)
|
||||
}
|
||||
if failures := errorLines(lines); len(failures) != 0 {
|
||||
t.Errorf("a refusal was logged as a failure: %v", failures)
|
||||
}
|
||||
})
|
||||
}
|
||||
if n := events.count(); n != 0 {
|
||||
t.Errorf("%d Sentry events for refusals, want none", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnexpectedErrorIsLoggedAndReportedOnce(t *testing.T) {
|
||||
events := captureSentryEvents(t)
|
||||
id := newJobID(t)
|
||||
s, logs := newLoggedServer(t, &fakeJobs{statusErr: errors.New("status store broke")}, &fakePrinter{})
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/jobs/"+id.String(), nil)
|
||||
req.Header.Set("Authorization", "Bearer "+validToken(t))
|
||||
|
||||
resp, body := send(t, s, req)
|
||||
expectError(t, resp, body, http.StatusInternalServerError, "internal_error")
|
||||
if bytes.Contains(body, []byte("status store broke")) {
|
||||
t.Errorf("body %s repeats the internal error", body)
|
||||
}
|
||||
lines := logs.lines(t)
|
||||
failures := errorLines(lines)
|
||||
if len(failures) != 1 || failures[0]["msg"] != "request failed" || failures[0]["err"] != "status store broke" {
|
||||
t.Errorf("error lines = %v, want one request failed line with the error", failures)
|
||||
}
|
||||
if requests := linesAt(lines, slog.LevelWarn.String(), "request"); len(requests) != 1 {
|
||||
t.Errorf("request lines = %v, want one warning", linesAt(lines, "", "request"))
|
||||
}
|
||||
if n := events.count(); n != 1 {
|
||||
t.Errorf("%d Sentry events, want 1", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPanicIsLoggedAndReportedOnce(t *testing.T) {
|
||||
events := captureSentryEvents(t)
|
||||
s, logs := newLoggedServer(t, &fakeJobs{}, &fakePrinter{})
|
||||
s.app.Get("/panic", func(fiber.Ctx) error { panic("handler exploded") })
|
||||
|
||||
resp, body := send(t, s, httptest.NewRequest(http.MethodGet, "/panic", nil))
|
||||
expectError(t, resp, body, http.StatusInternalServerError, "internal_error")
|
||||
if bytes.Contains(body, []byte("exploded")) {
|
||||
t.Errorf("body %s repeats the panic", body)
|
||||
}
|
||||
lines := logs.lines(t)
|
||||
failures := errorLines(lines)
|
||||
if len(failures) != 1 || failures[0]["msg"] != "panic" || failures[0]["panic"] != "handler exploded" {
|
||||
t.Fatalf("error lines = %v, want one panic line", failures)
|
||||
}
|
||||
if stack, _ := failures[0]["stack"].(string); !strings.Contains(stack, "TestPanicIsLoggedAndReportedOnce") {
|
||||
t.Errorf("stack does not show where the panic happened:\n%s", stack)
|
||||
}
|
||||
requests := linesAt(lines, "", "request")
|
||||
if len(requests) != 1 || requests[0]["status"] != float64(http.StatusInternalServerError) {
|
||||
t.Errorf("request lines = %v, want one with status 500", requests)
|
||||
}
|
||||
if n := events.count(); n != 1 {
|
||||
t.Errorf("%d Sentry events, want 1", n)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -7,10 +7,11 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/config"
|
||||
"uberbringer/internal/pkg/config"
|
||||
)
|
||||
|
||||
const validSecret = "xTw8qdxTy7Ng4DiptTqmeVy506xWLht3OhFn4kdawmM="
|
||||
// validSecret is a placeholder that satisfies the 32-byte minimum.
|
||||
const validSecret = "test-only-secret-test-only-secret-0123"
|
||||
|
||||
func writeConfig(t *testing.T, body string) string {
|
||||
t.Helper()
|
||||
@@ -21,9 +22,10 @@ func writeConfig(t *testing.T, body string) string {
|
||||
return path
|
||||
}
|
||||
|
||||
func TestLoadLegacyConfigGetsDefaults(t *testing.T) {
|
||||
func TestLoadInstallScriptConfigGetsDefaults(t *testing.T) {
|
||||
t.Setenv("SENTRY_DSN", "")
|
||||
// The exact shape written by the original install.sh, plus a printer.
|
||||
// The shape install.sh writes; every other setting comes from the
|
||||
// defaults.
|
||||
path := writeConfig(t, `
|
||||
[webserver]
|
||||
bind_ip = "127.0.0.1"
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/escpos"
|
||||
"uberbringer/internal/pkg/escpos"
|
||||
)
|
||||
|
||||
// Byte-exact checks against the Epson ESC/POS command reference.
|
||||
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/escpos"
|
||||
"uberbringer/internal/pkg/escpos"
|
||||
)
|
||||
|
||||
// statusTimeout bounds how long the printer may take to answer one real-time
|
||||
|
||||
@@ -9,8 +9,8 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/escpos"
|
||||
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/printer"
|
||||
"uberbringer/internal/pkg/escpos"
|
||||
"uberbringer/internal/pkg/printer"
|
||||
)
|
||||
|
||||
// fakePrinter accepts one connection per handle call.
|
||||
@@ -71,8 +71,10 @@ func TestSendUnreachable(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestSendRespectsCancelledContextWhileBusy(t *testing.T) {
|
||||
accepted := make(chan struct{}, 1)
|
||||
release := make(chan struct{})
|
||||
addr := fakePrinter(t, func(conn net.Conn) {
|
||||
accepted <- struct{}{}
|
||||
<-release
|
||||
_, _ = io.Copy(io.Discard, conn)
|
||||
})
|
||||
@@ -80,9 +82,15 @@ func TestSendRespectsCancelledContextWhileBusy(t *testing.T) {
|
||||
client := printer.NewClient(addr, time.Second, 5*time.Second)
|
||||
|
||||
// Hold the single connection slot with a status query that never gets
|
||||
// an answer, then try to send with a short deadline.
|
||||
// an answer, then try to send with a short deadline. The client takes
|
||||
// the slot before it dials, so once the printer has accepted the status
|
||||
// query's connection the slot is held.
|
||||
go func() { _, _ = client.Status(context.Background()) }()
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
select {
|
||||
case <-accepted:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("the status query never connected")
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
|
||||
defer cancel()
|
||||
@@ -168,14 +176,17 @@ func TestStatusUnsupported(t *testing.T) {
|
||||
|
||||
func TestStatusContextDeadlineIsNotUnsupported(t *testing.T) {
|
||||
// A printer that answers, just later than the caller is willing to wait,
|
||||
// e.g. while it works through a large buffered image.
|
||||
// e.g. while it works through a large buffered image. It answers only
|
||||
// once the test is over, after the caller's deadline has passed.
|
||||
late := make(chan struct{})
|
||||
t.Cleanup(func() { close(late) })
|
||||
addr := fakePrinter(t, func(conn net.Conn) {
|
||||
req := make([]byte, 3)
|
||||
for {
|
||||
if _, err := io.ReadFull(conn, req); err != nil {
|
||||
return
|
||||
}
|
||||
time.Sleep(300 * time.Millisecond)
|
||||
<-late
|
||||
_, _ = conn.Write([]byte{0x1A}) // offline
|
||||
}
|
||||
})
|
||||
|
||||
@@ -12,7 +12,7 @@ import (
|
||||
|
||||
"go.jetify.com/typeid"
|
||||
|
||||
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/receipt"
|
||||
"uberbringer/internal/pkg/receipt"
|
||||
)
|
||||
|
||||
// jobTimeout bounds rendering and sending one job, including retries.
|
||||
|
||||
@@ -10,8 +10,8 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/printqueue"
|
||||
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/receipt"
|
||||
"uberbringer/internal/pkg/printqueue"
|
||||
"uberbringer/internal/pkg/receipt"
|
||||
)
|
||||
|
||||
type fakeRenderer struct{ err error }
|
||||
@@ -72,11 +72,11 @@ func newQueue(r printqueue.Renderer, s printqueue.Sender, opts printqueue.Option
|
||||
return printqueue.New(r, s, discardLogger(), opts)
|
||||
}
|
||||
|
||||
// startQueue runs q until the test ends and returns a func that stops it and
|
||||
// waits for Run to return.
|
||||
func startQueue(t *testing.T, q *printqueue.Queue) (stop func()) {
|
||||
// startQueue runs q until the test ends. cancel cancels Run's context and
|
||||
// wait blocks until Run has returned.
|
||||
func startQueue(t *testing.T, q *printqueue.Queue) (cancel, wait func()) {
|
||||
t.Helper()
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
ctx, cancelRun := context.WithCancel(context.Background())
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
@@ -84,10 +84,9 @@ func startQueue(t *testing.T, q *printqueue.Queue) (stop func()) {
|
||||
t.Error(err)
|
||||
}
|
||||
}()
|
||||
var once sync.Once
|
||||
stop = func() { once.Do(func() { cancel(); <-done }) }
|
||||
t.Cleanup(stop)
|
||||
return stop
|
||||
wait = func() { <-done }
|
||||
t.Cleanup(func() { cancelRun(); wait() })
|
||||
return cancelRun, wait
|
||||
}
|
||||
|
||||
func waitForState(t *testing.T, q *printqueue.Queue, id printqueue.JobID, want printqueue.State) printqueue.Status {
|
||||
@@ -145,27 +144,31 @@ func TestRetriesThenSucceeds(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestFailsAfterRetries(t *testing.T) {
|
||||
var reported []printqueue.JobID
|
||||
var mu sync.Mutex
|
||||
reported := make(chan printqueue.JobID, 2)
|
||||
sender := &fakeSender{failures: 10}
|
||||
q := newQueue(fakeRenderer{}, sender, printqueue.Options{
|
||||
Retries: 2,
|
||||
OnFailure: func(id printqueue.JobID, _ error) {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
reported = append(reported, id)
|
||||
},
|
||||
Retries: 2,
|
||||
OnFailure: func(id printqueue.JobID, _ error) { reported <- id },
|
||||
})
|
||||
startQueue(t, q)
|
||||
cancel, wait := startQueue(t, q)
|
||||
st, _ := q.Submit(job("x"))
|
||||
failed := waitForState(t, q, st.ID, printqueue.StateFailed)
|
||||
if failed.Attempts != 3 || !strings.Contains(failed.Error, "printer offline") {
|
||||
t.Errorf("failed status = %+v", failed)
|
||||
}
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if len(reported) != 1 || reported[0] != st.ID {
|
||||
t.Errorf("OnFailure got %v", reported)
|
||||
// OnFailure runs after the job is marked failed, so wait for it.
|
||||
select {
|
||||
case id := <-reported:
|
||||
if id != st.ID {
|
||||
t.Errorf("OnFailure got %s, want %s", id, st.ID)
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("OnFailure was not called")
|
||||
}
|
||||
cancel()
|
||||
wait()
|
||||
if n := len(reported); n != 0 {
|
||||
t.Errorf("OnFailure called %d more times, want once", n)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -199,17 +202,17 @@ func TestQueueFull(t *testing.T) {
|
||||
func TestShutdownFinishesCurrentJobAndFailsWaiting(t *testing.T) {
|
||||
sender := &fakeSender{block: make(chan struct{})}
|
||||
q := newQueue(fakeRenderer{}, sender, printqueue.Options{})
|
||||
stop := startQueue(t, q)
|
||||
cancel, wait := startQueue(t, q)
|
||||
|
||||
first, _ := q.Submit(job("first"))
|
||||
waitForState(t, q, first.ID, printqueue.StatePrinting)
|
||||
second, _ := q.Submit(job("second"))
|
||||
|
||||
stopped := make(chan struct{})
|
||||
go func() { stop(); close(stopped) }()
|
||||
time.Sleep(20 * time.Millisecond) // let Run observe the cancellation
|
||||
close(sender.block) // the in-flight send completes
|
||||
<-stopped
|
||||
// Cancel while the first send is still blocked, so Run is shutting down
|
||||
// by the time that send completes.
|
||||
cancel()
|
||||
close(sender.block)
|
||||
wait()
|
||||
|
||||
if st, _ := q.Status(first.ID); st.State != printqueue.StateDone {
|
||||
t.Errorf("in-flight job state = %s, want done", st.State)
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"image/png"
|
||||
"testing"
|
||||
|
||||
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/raster"
|
||||
"uberbringer/internal/pkg/raster"
|
||||
)
|
||||
|
||||
func encodePNG(t *testing.T, img image.Image) []byte {
|
||||
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/escpos"
|
||||
"uberbringer/internal/pkg/escpos"
|
||||
)
|
||||
|
||||
// Element types.
|
||||
|
||||
@@ -3,7 +3,7 @@ package receipt
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/escpos"
|
||||
"uberbringer/internal/pkg/escpos"
|
||||
)
|
||||
|
||||
// tabWidth matches the printer's default horizontal tab stops.
|
||||
|
||||
@@ -11,8 +11,8 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/escpos"
|
||||
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/receipt"
|
||||
"uberbringer/internal/pkg/escpos"
|
||||
"uberbringer/internal/pkg/receipt"
|
||||
)
|
||||
|
||||
type fakeFetcher struct {
|
||||
|
||||
@@ -8,8 +8,8 @@ import (
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/escpos"
|
||||
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/raster"
|
||||
"uberbringer/internal/pkg/escpos"
|
||||
"uberbringer/internal/pkg/raster"
|
||||
)
|
||||
|
||||
// Fetcher downloads remote image data.
|
||||
|
||||
@@ -11,7 +11,7 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/safehttp"
|
||||
"uberbringer/internal/pkg/safehttp"
|
||||
)
|
||||
|
||||
func newServer(t *testing.T, body string) *httptest.Server {
|
||||
|
||||
Reference in new issue
Block a user