Phase 1 of docs/plans/formatters.md: single and double CP437 boxes from
one /print element, and a way to see a receipt without using paper.
- receipt: box, rule and kv elements, laid out when the job renders from
the printer profile, size and font (never fixed widths). Boxes take a
title (inline or capped), a footer, padding, fit and columns, and a
body of text or children (text, feed, kv, and rules as dividers joined
to the borders). Glyphs a code page lacks fall back per set: double-h
and double-v to double, then single, then ascii; a missing junction
switches line weight first.
- Validation names nested elements (elements[0].children[3] (qr)),
checks fields per block type, allows one level of children and counts
them toward the 500-element limit. Block fields on the older types are
problems, as they were unknown fields before.
- Text is composed to NFC and characters the code page lacks fold to
look-alikes (curly quotes, dashes, ellipsis, arrows, check marks, euro,
trademark), as the owner approved on 2026-11-29. An emoji sequence
prints as one '?'. Encodable text is untouched.
- escpos: CodePage.CanEncode and Decode, and Interpret, which reads a
command stream back as the printer would print it. It takes the
profile so that it can follow the printer's own wrapping and
alignment; raw spans stay opaque.
- POST /api/v1/preview and `uberbringer preview` show the lines a job
prints, as text or JSON with styles, without fetching images.
- Config: [format] max_lines (default 2000), refused with 422
too_many_lines on preview; printer.box_line_spacing (default 0).
Byte compatibility: testdata/compat fixtures were rendered by 9b91109
before the renderer changed, and still match it and the new renderer.
examples/blocks.json was printed on the TM-T88IV; the owner judged the
border gaps at the default spacing fine (2026-11-30), so
box_line_spacing stays 0, and TestPaperReceipts pins its bytes.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
145 lines
5.5 KiB
Go
145 lines
5.5 KiB
Go
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"}
|
|
codeTooManyLines = errorCode{fiber.StatusUnprocessableEntity, "too_many_lines", "receipt would print too many lines"}
|
|
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}
|
|
}
|