Add the list block and the module layer with the note module
The list block prints items with a dot, dash, number or checkbox bullet,
wrapping a long item with a hanging indent; a checkbox list ticks its
done items as [√], or [x] on code pages without √. It stands alone or
inside a box, and its items, bullet and done fields carry their enums
and limits as jsonschema tags.
internal/pkg/modules holds modules that build ordinary jobs from their
own payloads: a registry by name, an Env with the clock, time zone and
time layout, strict payload decoding that reports every problem, ErrSkip
and PayloadError. The note module prints a boxed note with an optional
checklist and a time stamp in the footer.
Three routes join the route table: POST /api/v1/print/{module} and
POST /api/v1/preview/{module}, which take ?copies and a reserved
?printer, and GET /api/v1/modules. Print and the module route share one
submit path, and preview shares one too. New error codes:
invalid_payload, invalid_query, unknown_printer, module_not_found and
module_failed; a module that builds an invalid receipt is logged and
reported to Sentry once. [format] gains timezone and time_layout, the
binary embeds the time zone database, and uberbringer preview takes
--module.
The note receipt passed on the TM-T88IV, and its bytes are pinned in
TestPaperReceipts. docs/api.md describes the list block, the module
routes and the note payload; docs/swagger.json is regenerated.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
6b2e402f1a
commit
3e9779f71a
69 files changed
+3092
-262
No files matched your search
@@ -0,0 +1,27 @@
|
||||
package uberbringer
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"uberbringer/internal/pkg/config"
|
||||
"uberbringer/internal/pkg/modules"
|
||||
)
|
||||
|
||||
// newModules returns the registry of every module the daemon offers.
|
||||
func newModules() (*modules.Registry, error) {
|
||||
return modules.NewRegistry(modules.Note())
|
||||
}
|
||||
|
||||
// moduleEnv returns a func that gives modules the time now, in the zone and
|
||||
// layout cfg's [format] names.
|
||||
func moduleEnv(cfg *config.Config) (func() modules.Env, error) {
|
||||
loc, err := time.LoadLocation(cfg.Format.Timezone)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("config format.timezone: %w", err)
|
||||
}
|
||||
layout := cfg.Format.TimeLayout
|
||||
return func() modules.Env {
|
||||
return modules.Env{Now: time.Now(), Location: loc, TimeLayout: layout}
|
||||
}, nil
|
||||
}
|
||||
@@ -13,17 +13,20 @@ import (
|
||||
|
||||
"uberbringer/internal/pkg/config"
|
||||
"uberbringer/internal/pkg/escpos"
|
||||
"uberbringer/internal/pkg/modules"
|
||||
"uberbringer/internal/pkg/receipt"
|
||||
)
|
||||
|
||||
func newPreviewCommand(configPath *string) *cobra.Command {
|
||||
return &cobra.Command{
|
||||
Use: "preview [file.json|-]",
|
||||
var module string
|
||||
cmd := &cobra.Command{
|
||||
Use: "preview [--module name] [file.json|-]",
|
||||
Short: "Shows the lines a job would print, without printing it.",
|
||||
Long: "Reads a job, as POST /api/v1/print takes it, from the file or from standard input,\n" +
|
||||
"lays it out for the printer in the config and writes the lines it would print.\n" +
|
||||
"On a terminal, bold, underlined and inverted text is shown as such. Images are\n" +
|
||||
"not loaded; each shows as a placeholder.",
|
||||
"With --module, the input is that module's payload, as POST /api/v1/print/<module>\n" +
|
||||
"takes it. On a terminal, bold, underlined and inverted text is shown as such.\n" +
|
||||
"Images are not loaded; each shows as a placeholder.",
|
||||
Args: cobra.MaximumNArgs(1),
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
cfg, err := config.Load(*configPath)
|
||||
@@ -35,9 +38,11 @@ func newPreviewCommand(configPath *string) *cobra.Command {
|
||||
return err
|
||||
}
|
||||
out := cmd.OutOrStdout()
|
||||
return preview(cmd.Context(), cfg, data, out, cmd.ErrOrStderr(), isTerminal(out))
|
||||
return preview(cmd.Context(), cfg, data, module, out, cmd.ErrOrStderr(), isTerminal(out))
|
||||
},
|
||||
}
|
||||
cmd.Flags().StringVar(&module, "module", "", "read the input as this module's payload, e.g. note")
|
||||
return cmd
|
||||
}
|
||||
|
||||
// readJobInput reads the job from the file named in args, or from stdin when
|
||||
@@ -59,10 +64,15 @@ func readJobInput(stdin io.Reader, args []string) ([]byte, error) {
|
||||
|
||||
// preview writes the lines the job in data would print on the printer cfg
|
||||
// describes to out, styled when styled is set, and its warnings to errOut.
|
||||
func preview(ctx context.Context, cfg *config.Config, data []byte, out, errOut io.Writer, styled bool) error {
|
||||
job, err := receipt.DecodeJob(data)
|
||||
// With a module name, data is that module's payload.
|
||||
func preview(ctx context.Context, cfg *config.Config, data []byte, module string, out, errOut io.Writer, styled bool) error {
|
||||
job, ok, err := previewJob(ctx, cfg, data, module)
|
||||
if err != nil {
|
||||
return fmt.Errorf("not a valid job: %w", err)
|
||||
return err
|
||||
}
|
||||
if !ok {
|
||||
_, err := fmt.Fprintf(errOut, "module %s has nothing to print\n", module)
|
||||
return err
|
||||
}
|
||||
options, err := rendererOptions(cfg)
|
||||
if err != nil {
|
||||
@@ -71,6 +81,8 @@ func preview(ctx context.Context, cfg *config.Config, data []byte, out, errOut i
|
||||
p, err := receipt.NewRenderer(options, noFetch{}).Preview(ctx, job)
|
||||
var ve *receipt.ValidationError
|
||||
switch {
|
||||
case errors.As(err, &ve) && module != "":
|
||||
return fmt.Errorf("module %q built an invalid receipt:\n %s", module, strings.Join(ve.Problems, "\n "))
|
||||
case errors.As(err, &ve):
|
||||
return fmt.Errorf("invalid job:\n %s", strings.Join(ve.Problems, "\n "))
|
||||
case err != nil:
|
||||
@@ -87,6 +99,46 @@ func preview(ctx context.Context, cfg *config.Config, data []byte, out, errOut i
|
||||
return nil
|
||||
}
|
||||
|
||||
// previewJob returns the job to preview: data itself, or with a module name,
|
||||
// the job that module builds from data as its payload, at the time now. ok
|
||||
// is false when the module has nothing to print.
|
||||
func previewJob(ctx context.Context, cfg *config.Config, data []byte, module string) (job receipt.Job, ok bool, err error) {
|
||||
if module == "" {
|
||||
job, err := receipt.DecodeJob(data)
|
||||
if err != nil {
|
||||
return job, false, fmt.Errorf("not a valid job: %w", err)
|
||||
}
|
||||
return job, true, nil
|
||||
}
|
||||
registry, err := newModules()
|
||||
if err != nil {
|
||||
return job, false, err
|
||||
}
|
||||
m, found := registry.Get(module)
|
||||
if !found {
|
||||
var names []string
|
||||
for _, info := range registry.List() {
|
||||
names = append(names, info.Name)
|
||||
}
|
||||
return job, false, fmt.Errorf("unknown module %q; the modules are: %s", module, strings.Join(names, ", "))
|
||||
}
|
||||
env, err := moduleEnv(cfg)
|
||||
if err != nil {
|
||||
return job, false, err
|
||||
}
|
||||
job, err = m.Build(ctx, data, env())
|
||||
var pe *modules.PayloadError
|
||||
switch {
|
||||
case errors.Is(err, modules.ErrSkip):
|
||||
return job, false, nil
|
||||
case errors.As(err, &pe):
|
||||
return job, false, fmt.Errorf("invalid payload for module %q:\n %s", module, strings.Join(pe.Problems, "\n "))
|
||||
case err != nil:
|
||||
return job, false, fmt.Errorf("module %s: %w", module, err)
|
||||
}
|
||||
return job, true, nil
|
||||
}
|
||||
|
||||
// noFetch refuses image fetches. A preview loads no images, but a renderer
|
||||
// needs a fetcher.
|
||||
type noFetch struct{}
|
||||
|
||||
@@ -3,10 +3,12 @@ package uberbringer
|
||||
import (
|
||||
"bytes"
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"uberbringer/internal/pkg/escpos"
|
||||
"uberbringer/internal/pkg/receipt"
|
||||
@@ -110,6 +112,70 @@ func TestPreviewCommandErrors(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreviewCommandModule(t *testing.T) {
|
||||
cmd := newRootCommand(BuildInfo{})
|
||||
var out, errOut bytes.Buffer
|
||||
cmd.SetOut(&out)
|
||||
cmd.SetErr(&errOut)
|
||||
cmd.SetIn(strings.NewReader(`{"title":"Shopping","text":"Bread.","items":["Milk","Eggs"],"done":[1],"footer":"kitchen"}`))
|
||||
cmd.SetArgs([]string{"preview", "-c", writePreviewConfig(t, ""), "--module", "note"})
|
||||
if err := cmd.Execute(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := "" +
|
||||
"┌─ Shopping ─────────────────────────────┐\n" +
|
||||
"│ Bread. │\n" +
|
||||
"│ │\n" +
|
||||
"│ [ ] Milk │\n" +
|
||||
"│ [√] Eggs │\n" +
|
||||
"└───────────────────────────── kitchen ──┘\n" +
|
||||
" - - - - - - - partial cut - - - - - - - -\n"
|
||||
if out.String() != want || errOut.Len() != 0 {
|
||||
t.Errorf("output:\n%s\nwant:\n%s\nstandard error: %q", out.String(), want, errOut.String())
|
||||
}
|
||||
}
|
||||
|
||||
// The note's stamp is the time now in format.timezone and time_layout.
|
||||
func TestPreviewCommandModuleStamp(t *testing.T) {
|
||||
cmd := newRootCommand(BuildInfo{})
|
||||
var out bytes.Buffer
|
||||
cmd.SetOut(&out)
|
||||
cmd.SetIn(strings.NewReader(`{"text":"x"}`))
|
||||
cmd.SetArgs([]string{"preview", "-c", writePreviewConfig(t, "[format]\ntimezone = \"UTC\"\ntime_layout = \"2006\"\n"), "--module", "note"})
|
||||
before := time.Now().UTC().Year()
|
||||
if err := cmd.Execute(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
after := time.Now().UTC().Year()
|
||||
lines := strings.Split(out.String(), "\n")
|
||||
if len(lines) < 3 || (!strings.Contains(lines[2], fmt.Sprintf(" %d ", before)) && !strings.Contains(lines[2], fmt.Sprintf(" %d ", after))) {
|
||||
t.Errorf("bottom border %q, want the year in it", lines[2])
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreviewCommandModuleErrors(t *testing.T) {
|
||||
tests := []struct {
|
||||
name, module, payload, want string
|
||||
}{
|
||||
{"unknown module", "notx", `{}`, `unknown module "notx"; the modules are: note`},
|
||||
{"invalid payload", "note", `{"title":"x","items":["a"],"done":[1,2]}`,
|
||||
"invalid payload for module \"note\":\n text: required\n done[0]: index 1 is out of range\n done[1]: index 2 is out of range"},
|
||||
{"not an object", "note", `[]`, "invalid payload for module \"note\":\n body: expected a JSON object, got array"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
cmd := newRootCommand(BuildInfo{})
|
||||
cmd.SetOut(&bytes.Buffer{})
|
||||
cmd.SetIn(strings.NewReader(tt.payload))
|
||||
cmd.SetArgs([]string{"preview", "-c", writePreviewConfig(t, ""), "--module", tt.module})
|
||||
err := cmd.Execute()
|
||||
if err == nil || !strings.Contains(err.Error(), tt.want) {
|
||||
t.Errorf("err = %v, want it to contain %q", err, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestWritePreviewStyled(t *testing.T) {
|
||||
p := receipt.Preview{Lines: []escpos.PreviewLine{
|
||||
{Kind: escpos.LineText, Text: "a <b> c", Runs: []escpos.Run{
|
||||
|
||||
@@ -56,6 +56,14 @@ func run(ctx context.Context, cfg *config.Config, build BuildInfo, out io.Writer
|
||||
return err
|
||||
}
|
||||
profile, codePage := options.Profile, options.CodePage
|
||||
registry, err := newModules()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
env, err := moduleEnv(cfg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
flushSentry, err := initSentry(cfg.Sentry, build, logger)
|
||||
if err != nil {
|
||||
@@ -99,7 +107,13 @@ func run(ctx context.Context, cfg *config.Config, build BuildInfo, out io.Writer
|
||||
IdleTimeout: cfg.WebServer.IdleTimeout,
|
||||
RequestID: newRequestID,
|
||||
OpenAPI: docs.OpenAPI(),
|
||||
}, server.Deps{Jobs: queue, Printer: printerClient, Previewer: renderer}, logger)
|
||||
}, server.Deps{
|
||||
Jobs: queue,
|
||||
Printer: printerClient,
|
||||
Previewer: renderer,
|
||||
Modules: registry,
|
||||
ModuleEnv: env,
|
||||
}, logger)
|
||||
|
||||
addr := net.JoinHostPort(cfg.WebServer.BindIP, strconv.Itoa(cfg.WebServer.Port))
|
||||
ln, err := listen(ctx, addr)
|
||||
|
||||
@@ -141,6 +141,37 @@ level = "error"
|
||||
return bytes.Contains(printer.received(), []byte("Gr\x81\xE1e aus dem Test"))
|
||||
})
|
||||
|
||||
req, _ = http.NewRequest(http.MethodGet, base+"/api/v1/modules", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
resp, err = http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var listed []struct{ Name string }
|
||||
if err := json.NewDecoder(resp.Body).Decode(&listed); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resp.Body.Close()
|
||||
if len(listed) == 0 || listed[0].Name != "note" {
|
||||
t.Errorf("GET /api/v1/modules = %+v, want note listed", listed)
|
||||
}
|
||||
|
||||
req, _ = http.NewRequest(http.MethodPost, base+"/api/v1/print/note",
|
||||
strings.NewReader(`{"title":"Notiz","text":"Milch kaufen","items":["Brot"],"done":[0]}`))
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
resp, err = http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusAccepted {
|
||||
t.Fatalf("POST /api/v1/print/note = %d", resp.StatusCode)
|
||||
}
|
||||
waitFor(t, func() bool {
|
||||
// "[√] Brot" in CP437: √ is 0xFB.
|
||||
return bytes.Contains(printer.received(), []byte("[\xFB] Brot"))
|
||||
})
|
||||
|
||||
cancel()
|
||||
select {
|
||||
case err := <-served:
|
||||
|
||||
@@ -25,15 +25,20 @@ type errorCode struct {
|
||||
var (
|
||||
codeBadRequest = errorCode{fiber.StatusBadRequest, "bad_request", "malformed request"}
|
||||
codeInvalidJob = errorCode{fiber.StatusBadRequest, "invalid_job", "invalid job"}
|
||||
codeInvalidPayload = errorCode{fiber.StatusBadRequest, "invalid_payload", "invalid payload"}
|
||||
codeInvalidQuery = errorCode{fiber.StatusBadRequest, "invalid_query", "invalid query parameter"}
|
||||
codeUnknownPrinter = errorCode{fiber.StatusBadRequest, "unknown_printer", "unknown printer"}
|
||||
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"}
|
||||
codeModuleNotFound = errorCode{fiber.StatusNotFound, "module_not_found", "module 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"}
|
||||
codeModuleFailed = errorCode{fiber.StatusUnprocessableEntity, "module_failed", "module built an invalid receipt"}
|
||||
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"}
|
||||
@@ -83,8 +88,11 @@ type errorResponse struct {
|
||||
Error string `json:"error"`
|
||||
// Code is stable and meant for clients to match on.
|
||||
Code string `json:"code"`
|
||||
// Details lists every problem when an invalid_job fails validation, each
|
||||
// naming the element by its path, e.g. elements[0].children[3] (qr).
|
||||
// Details lists every problem when a job fails validation (invalid_job),
|
||||
// a module payload is invalid (invalid_payload) or a module builds an
|
||||
// invalid receipt (module_failed). A job problem names the element by
|
||||
// its path, e.g. elements[0].children[3] (qr); a payload problem names
|
||||
// the field, e.g. done[0].
|
||||
Details []string `json:"details,omitempty"`
|
||||
}
|
||||
|
||||
|
||||
@@ -66,7 +66,12 @@ func (s *Server) handlePrint(c fiber.Ctx) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return s.submit(c, job)
|
||||
}
|
||||
|
||||
// submit queues a validated job and answers 202 with its status and a
|
||||
// Location header, or refuses it when the queue is full or closed.
|
||||
func (s *Server) submit(c fiber.Ctx, job receipt.Job) error {
|
||||
status, err := s.jobs.Submit(job)
|
||||
switch {
|
||||
case errors.Is(err, printqueue.ErrQueueFull):
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/gofiber/fiber/v3/middleware/requestid"
|
||||
|
||||
"uberbringer/internal/pkg/modules"
|
||||
"uberbringer/internal/pkg/receipt"
|
||||
)
|
||||
|
||||
// defaultPrinter is the only name ?printer= accepts while one printer is
|
||||
// configured.
|
||||
const defaultPrinter = "default"
|
||||
|
||||
// modulePayload is a module's payload: a JSON object whose fields the
|
||||
// module defines, such as a note's title, text and items.
|
||||
type modulePayload map[string]any
|
||||
|
||||
// moduleList is the body of GET /api/v1/modules: every module, sorted by
|
||||
// name.
|
||||
type moduleList []moduleInfo
|
||||
|
||||
// moduleInfo describes one module.
|
||||
type moduleInfo struct {
|
||||
// Name is the module's name in the module routes' paths, e.g. note.
|
||||
Name string `json:"name"`
|
||||
// Description says in one line what the module prints.
|
||||
Description string `json:"description"`
|
||||
}
|
||||
|
||||
// handleModules lists the modules, sorted by name.
|
||||
func (s *Server) handleModules(c fiber.Ctx) error {
|
||||
infos := s.modules.List()
|
||||
list := make(moduleList, len(infos))
|
||||
for i, info := range infos {
|
||||
list[i] = moduleInfo(info)
|
||||
}
|
||||
return c.JSON(list)
|
||||
}
|
||||
|
||||
// handlePrintModule builds a job from the body with the module the route
|
||||
// names and queues it. A module with nothing to print answers 204.
|
||||
func (s *Server) handlePrintModule(c fiber.Ctx) error {
|
||||
job, skip, err := s.moduleJob(c)
|
||||
switch {
|
||||
case err != nil:
|
||||
return err
|
||||
case skip:
|
||||
return c.SendStatus(fiber.StatusNoContent)
|
||||
}
|
||||
return s.submit(c, job)
|
||||
}
|
||||
|
||||
// handlePreviewModule builds a job as handlePrintModule does and answers
|
||||
// with its preview instead of queueing it.
|
||||
func (s *Server) handlePreviewModule(c fiber.Ctx) error {
|
||||
job, skip, err := s.moduleJob(c)
|
||||
switch {
|
||||
case err != nil:
|
||||
return err
|
||||
case skip:
|
||||
return c.SendStatus(fiber.StatusNoContent)
|
||||
}
|
||||
return s.preview(c, job)
|
||||
}
|
||||
|
||||
// moduleJob builds the job the route's module makes of the request body,
|
||||
// with the copies the query asks for, and validates it. skip is set when
|
||||
// the module has nothing to print. A job that fails validation is a bug in
|
||||
// the module: it is logged and reported, and answered 422 with the
|
||||
// problems.
|
||||
func (s *Server) moduleJob(c fiber.Ctx) (job receipt.Job, skip bool, err error) {
|
||||
// Clone: fasthttp reuses the buffer behind route params.
|
||||
name := strings.Clone(c.Params("module"))
|
||||
module, ok := s.modules.Get(name)
|
||||
if !ok {
|
||||
return job, false, newAPIError(codeModuleNotFound.withMessage(fmt.Sprintf("module %q not found", name)))
|
||||
}
|
||||
copies, err := moduleQuery(c)
|
||||
if err != nil {
|
||||
return job, false, err
|
||||
}
|
||||
|
||||
job, err = module.Build(c.Context(), c.Body(), s.moduleEnv())
|
||||
var payloadErr *modules.PayloadError
|
||||
switch {
|
||||
case errors.Is(err, modules.ErrSkip):
|
||||
return receipt.Job{}, true, nil
|
||||
case errors.As(err, &payloadErr):
|
||||
msg := fmt.Sprintf("invalid payload for module %q", name)
|
||||
return job, false, newAPIError(codeInvalidPayload.withMessage(msg), payloadErr.Problems...)
|
||||
case err != nil:
|
||||
return job, false, fmt.Errorf("module %s: %w", name, err)
|
||||
}
|
||||
|
||||
if copies > 0 {
|
||||
job.Copies = copies
|
||||
}
|
||||
if err := job.Validate(); err != nil {
|
||||
var ve *receipt.ValidationError
|
||||
if !errors.As(err, &ve) {
|
||||
return job, false, err
|
||||
}
|
||||
s.reportModuleBug(c, name, len(ve.Problems))
|
||||
msg := fmt.Sprintf("module %q built an invalid receipt", name)
|
||||
return job, false, newAPIError(codeModuleFailed.withMessage(msg), ve.Problems...)
|
||||
}
|
||||
return job, false, nil
|
||||
}
|
||||
|
||||
// moduleQuery reads the query parameters of a module route: copies, 1 to
|
||||
// receipt.MaxCopies, and printer, which only "default" may name while one
|
||||
// printer is configured. Each may be given once. Any other parameter is
|
||||
// refused, so that a misspelt one is not silently ignored. copies is 0 when
|
||||
// the query does not set it.
|
||||
func moduleQuery(c fiber.Ctx) (int, error) {
|
||||
copies := 0
|
||||
seen := make(map[string]bool)
|
||||
for key, value := range c.Request().URI().QueryArgs().All() {
|
||||
name := string(key)
|
||||
if seen[name] {
|
||||
return 0, newAPIError(codeInvalidQuery.withMessage(fmt.Sprintf("query parameter %q is given more than once", name)))
|
||||
}
|
||||
seen[name] = true
|
||||
switch name {
|
||||
case "copies":
|
||||
n, err := strconv.Atoi(string(value))
|
||||
if err != nil || n < 1 || n > receipt.MaxCopies {
|
||||
return 0, newAPIError(codeInvalidQuery.withMessage(fmt.Sprintf("copies must be 1-%d", receipt.MaxCopies)))
|
||||
}
|
||||
copies = n
|
||||
case "printer":
|
||||
if p := string(value); p != "" && p != defaultPrinter {
|
||||
msg := fmt.Sprintf("printer %q is not configured; the only printer is %q", p, defaultPrinter)
|
||||
return 0, newAPIError(codeUnknownPrinter.withMessage(msg))
|
||||
}
|
||||
default:
|
||||
return 0, newAPIError(codeInvalidQuery.withMessage(fmt.Sprintf("unknown query parameter %q; module routes take copies and printer", name)))
|
||||
}
|
||||
}
|
||||
return copies, nil
|
||||
}
|
||||
|
||||
// reportModuleBug logs and reports a module that built a job validation
|
||||
// refuses. The problems themselves are left out, since they can quote the
|
||||
// payload.
|
||||
func (s *Server) reportModuleBug(c fiber.Ctx, name string, problems int) {
|
||||
s.logger.LogAttrs(c.Context(), slog.LevelError, "module built an invalid receipt",
|
||||
slog.String("module", name),
|
||||
slog.Int("problems", problems),
|
||||
slog.String("path", c.Path()),
|
||||
slog.String("request_id", requestid.FromContext(c)),
|
||||
)
|
||||
hubFrom(c).CaptureException(fmt.Errorf("module %s built an invalid receipt (%d problems)", name, problems))
|
||||
}
|
||||
@@ -0,0 +1,286 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
|
||||
"uberbringer/internal/pkg/modules"
|
||||
"uberbringer/internal/pkg/printqueue"
|
||||
"uberbringer/internal/pkg/receipt"
|
||||
)
|
||||
|
||||
// fakeModule answers according to its body: "skip", "payload", "invalid"
|
||||
// and "fail" give those outcomes, and any other body prints as one line of
|
||||
// text with the build time.
|
||||
type fakeModule struct{}
|
||||
|
||||
func (fakeModule) Name() string { return "fake" }
|
||||
func (fakeModule) Description() string { return "Prints its body" }
|
||||
|
||||
func (fakeModule) Build(_ context.Context, body []byte, env modules.Env) (receipt.Job, error) {
|
||||
switch string(body) {
|
||||
case "skip":
|
||||
return receipt.Job{}, modules.ErrSkip
|
||||
case "payload":
|
||||
return receipt.Job{}, &modules.PayloadError{Problems: []string{"text: required", "done[0]: index 5 is out of range"}}
|
||||
case "invalid":
|
||||
return receipt.Job{Elements: []receipt.Element{{Type: "box"}, {Type: "kv"}}}, nil
|
||||
case "fail":
|
||||
return receipt.Job{}, errors.New("module broke")
|
||||
}
|
||||
return receipt.Job{Elements: []receipt.Element{{Type: "text", Text: string(body) + " at " + env.Stamp()}}}, nil
|
||||
}
|
||||
|
||||
func moduleRequest(t *testing.T, target, body string) *http.Request {
|
||||
t.Helper()
|
||||
req := httptest.NewRequest(http.MethodPost, target, strings.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", "Bearer "+validToken(t))
|
||||
return req
|
||||
}
|
||||
|
||||
const shoppingNote = `{"title":"Shopping","text":"Milk, eggs and the good bread from the bakery on Elm St.","items":["Milk","Eggs","Bread"],"done":[2]}`
|
||||
|
||||
func TestModulePrintAccepted(t *testing.T) {
|
||||
jobs := &fakeJobs{nextID: newJobID(t)}
|
||||
s := newTestServer(t, jobs, &fakePrinter{})
|
||||
resp, body := do(t, s, moduleRequest(t, "/api/v1/print/fake?copies=2&printer=default", "hello"))
|
||||
if resp.StatusCode != http.StatusAccepted {
|
||||
t.Fatalf("status = %d (%v)", resp.StatusCode, body)
|
||||
}
|
||||
if body["id"] != "job_01h455vb4pex5vsknk084sn02q" || body["status"] != "queued" {
|
||||
t.Errorf("body = %v", body)
|
||||
}
|
||||
if loc := resp.Header.Get("Location"); loc != "/api/v1/jobs/job_01h455vb4pex5vsknk084sn02q" {
|
||||
t.Errorf("Location = %q", loc)
|
||||
}
|
||||
if len(jobs.submitted) != 1 {
|
||||
t.Fatalf("submitted %d jobs", len(jobs.submitted))
|
||||
}
|
||||
job := jobs.submitted[0]
|
||||
if job.Copies != 2 || job.Elements[0].Text != "hello at 29 Nov 21:04" {
|
||||
t.Errorf("submitted %+v; want 2 copies of the text with the build time", job)
|
||||
}
|
||||
}
|
||||
|
||||
func TestModuleNotePrints(t *testing.T) {
|
||||
jobs := &fakeJobs{nextID: newJobID(t)}
|
||||
s := newTestServer(t, jobs, &fakePrinter{})
|
||||
for _, target := range []string{"/api/v1/print/note", "/api/v1/print/note?printer="} {
|
||||
resp, body := send(t, s, moduleRequest(t, target, shoppingNote))
|
||||
if resp.StatusCode != http.StatusAccepted {
|
||||
t.Fatalf("%s: status = %d (%s)", target, resp.StatusCode, body)
|
||||
}
|
||||
}
|
||||
if len(jobs.submitted) != 2 {
|
||||
t.Fatalf("submitted %d jobs, want 2", len(jobs.submitted))
|
||||
}
|
||||
box := jobs.submitted[0].Elements[0]
|
||||
if box.Type != "box" || box.Title != "Shopping" || box.Footer != "29 Nov 21:04" || jobs.submitted[0].Copies != 0 {
|
||||
t.Errorf("submitted %+v", jobs.submitted[0])
|
||||
}
|
||||
}
|
||||
|
||||
func TestModuleSkip(t *testing.T) {
|
||||
jobs := &fakeJobs{nextID: newJobID(t)}
|
||||
s := newTestServer(t, jobs, &fakePrinter{})
|
||||
for _, target := range []string{"/api/v1/print/fake", "/api/v1/preview/fake"} {
|
||||
resp, body := send(t, s, moduleRequest(t, target, "skip"))
|
||||
if resp.StatusCode != http.StatusNoContent || len(body) != 0 {
|
||||
t.Errorf("%s: status = %d, body %q; want 204 and no body", target, resp.StatusCode, body)
|
||||
}
|
||||
}
|
||||
if len(jobs.submitted) != 0 {
|
||||
t.Error("a skipped payload was queued")
|
||||
}
|
||||
}
|
||||
|
||||
func TestModuleRefusals(t *testing.T) {
|
||||
tests := []struct {
|
||||
name, target, body string
|
||||
status int
|
||||
code, message string
|
||||
details []string
|
||||
}{
|
||||
{"payload problems", "/api/v1/print/fake", "payload", 400, "invalid_payload", `invalid payload for module "fake"`,
|
||||
[]string{"text: required", "done[0]: index 5 is out of range"}},
|
||||
{"note payload problems", "/api/v1/print/note", `{"title":"x","colour":"red"}`, 400, "invalid_payload", `invalid payload for module "note"`,
|
||||
[]string{"colour: unknown field"}},
|
||||
{"note without text", "/api/v1/preview/note", `{"title":"x"}`, 400, "invalid_payload", `invalid payload for module "note"`,
|
||||
[]string{"text: required"}},
|
||||
{"unknown module", "/api/v1/print/notx", "hello", 404, "module_not_found", `module "notx" not found`, nil},
|
||||
{"unknown module on preview", "/api/v1/preview/notx?copies=9", "hello", 404, "module_not_found", `module "notx" not found`, nil},
|
||||
{"another printer", "/api/v1/print/fake?printer=office", "hello", 400, "unknown_printer",
|
||||
`printer "office" is not configured; the only printer is "default"`, nil},
|
||||
{"another printer on preview", "/api/v1/preview/fake?printer=Default", "hello", 400, "unknown_printer",
|
||||
`printer "Default" is not configured; the only printer is "default"`, nil},
|
||||
{"no copies", "/api/v1/print/fake?copies=0", "hello", 400, "invalid_query", "copies must be 1-5", nil},
|
||||
{"too many copies", "/api/v1/print/fake?copies=6", "hello", 400, "invalid_query", "copies must be 1-5", nil},
|
||||
{"copies not a number", "/api/v1/print/fake?copies=two", "hello", 400, "invalid_query", "copies must be 1-5", nil},
|
||||
{"copies twice", "/api/v1/print/fake?copies=1&copies=2", "hello", 400, "invalid_query", `query parameter "copies" is given more than once`, nil},
|
||||
{"unknown parameter", "/api/v1/print/fake?copy=2", "hello", 400, "invalid_query",
|
||||
`unknown query parameter "copy"; module routes take copies and printer`, nil},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
jobs := &fakeJobs{nextID: newJobID(t)}
|
||||
s, logs := newLoggedServer(t, jobs, &fakePrinter{})
|
||||
resp, raw := send(t, s, moduleRequest(t, tt.target, tt.body))
|
||||
e := expectError(t, resp, raw, tt.status, tt.code)
|
||||
if e.Error != tt.message {
|
||||
t.Errorf("error = %q, want %q", e.Error, tt.message)
|
||||
}
|
||||
if strings.Join(e.Details, "\n") != strings.Join(tt.details, "\n") {
|
||||
t.Errorf("details = %q, want %q", e.Details, tt.details)
|
||||
}
|
||||
if len(jobs.submitted) != 0 {
|
||||
t.Error("a refused request was queued")
|
||||
}
|
||||
if failures := errorLines(logs.lines(t)); len(failures) != 0 {
|
||||
t.Errorf("a refusal was logged as a failure: %v", failures)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A module that builds a job validation refuses has a bug: the client gets
|
||||
// 422 with the problems, and the bug is logged and reported once, without
|
||||
// the problems, which can quote the payload.
|
||||
func TestModuleBuiltAnInvalidJob(t *testing.T) {
|
||||
for _, target := range []string{"/api/v1/print/fake", "/api/v1/preview/fake"} {
|
||||
t.Run(target, func(t *testing.T) {
|
||||
events := captureSentryEvents(t)
|
||||
jobs := &fakeJobs{nextID: newJobID(t)}
|
||||
s, logs := newLoggedServer(t, jobs, &fakePrinter{})
|
||||
resp, raw := send(t, s, moduleRequest(t, target, "invalid"))
|
||||
e := expectError(t, resp, raw, http.StatusUnprocessableEntity, "module_failed")
|
||||
want := []string{
|
||||
"elements[0] (box): text or children is required",
|
||||
"elements[1] (kv): pairs: at least one pair is required",
|
||||
}
|
||||
if e.Error != `module "fake" built an invalid receipt` || strings.Join(e.Details, "\n") != strings.Join(want, "\n") {
|
||||
t.Errorf("error = %q, details = %q", e.Error, e.Details)
|
||||
}
|
||||
if len(jobs.submitted) != 0 {
|
||||
t.Error("an invalid job was queued")
|
||||
}
|
||||
failures := errorLines(logs.lines(t))
|
||||
if len(failures) != 1 || failures[0]["msg"] != "module built an invalid receipt" ||
|
||||
failures[0]["module"] != "fake" || failures[0]["problems"] != float64(2) {
|
||||
t.Errorf("error lines = %v, want one for the module", failures)
|
||||
}
|
||||
logs.mu.Lock()
|
||||
logged := logs.buf.String()
|
||||
logs.mu.Unlock()
|
||||
if strings.Contains(logged, "pairs: at least one") {
|
||||
t.Error("the problems were logged")
|
||||
}
|
||||
if n := events.count(); n != 1 {
|
||||
t.Errorf("%d Sentry events, want 1", n)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestModuleUnexpectedError(t *testing.T) {
|
||||
events := captureSentryEvents(t)
|
||||
s, logs := newLoggedServer(t, &fakeJobs{}, &fakePrinter{})
|
||||
resp, raw := send(t, s, moduleRequest(t, "/api/v1/print/fake", "fail"))
|
||||
expectError(t, resp, raw, http.StatusInternalServerError, "internal_error")
|
||||
failures := errorLines(logs.lines(t))
|
||||
if len(failures) != 1 || failures[0]["err"] != "module fake: module broke" {
|
||||
t.Errorf("error lines = %v", failures)
|
||||
}
|
||||
if n := events.count(); n != 1 {
|
||||
t.Errorf("%d Sentry events, want 1", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestModuleQueueRefusals(t *testing.T) {
|
||||
tests := []struct {
|
||||
err error
|
||||
code string
|
||||
wantRetryAfter bool
|
||||
}{
|
||||
{printqueue.ErrQueueFull, "queue_full", true},
|
||||
{printqueue.ErrClosed, "shutting_down", false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.code, func(t *testing.T) {
|
||||
s := newTestServer(t, &fakeJobs{submitErr: tt.err}, &fakePrinter{})
|
||||
resp, body := send(t, s, moduleRequest(t, "/api/v1/print/note", shoppingNote))
|
||||
expectError(t, resp, body, http.StatusServiceUnavailable, tt.code)
|
||||
if got := resp.Header.Get("Retry-After") == "10"; got != tt.wantRetryAfter {
|
||||
t.Errorf("Retry-After = %q", resp.Header.Get("Retry-After"))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestModuleList(t *testing.T) {
|
||||
s := newTestServer(t, &fakeJobs{}, &fakePrinter{})
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/modules", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+validToken(t))
|
||||
resp, body := send(t, s, req)
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("status = %d (%s)", resp.StatusCode, body)
|
||||
}
|
||||
want := `[{"name":"fake","description":"Prints its body"},{"name":"note","description":"Boxed note with an optional checklist"}]`
|
||||
if string(body) != want {
|
||||
t.Errorf("body = %s, want %s", body, want)
|
||||
}
|
||||
if cc := resp.Header.Get(fiber.HeaderCacheControl); cc != "no-store" {
|
||||
t.Errorf("Cache-Control = %q, want no-store", cc)
|
||||
}
|
||||
}
|
||||
|
||||
func TestModulePreview(t *testing.T) {
|
||||
jobs := &fakeJobs{}
|
||||
s := newTestServer(t, jobs, &fakePrinter{})
|
||||
resp, body := send(t, s, moduleRequest(t, "/api/v1/preview/note", shoppingNote))
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("status = %d (%s)", resp.StatusCode, body)
|
||||
}
|
||||
want := "" +
|
||||
"┌─ Shopping ─────────────────────────────┐\n" +
|
||||
"│ Milk, eggs and the good bread from the │\n" +
|
||||
"│ bakery on Elm St. │\n" +
|
||||
"│ │\n" +
|
||||
"│ [ ] Milk │\n" +
|
||||
"│ [ ] Eggs │\n" +
|
||||
"│ [√] Bread │\n" +
|
||||
"└──────────────────────── 29 Nov 21:04 ──┘\n" +
|
||||
" - - - - - - - partial cut - - - - - - - -\n"
|
||||
if string(body) != want {
|
||||
t.Errorf("body =\n%s\nwant\n%s", body, want)
|
||||
}
|
||||
if len(jobs.submitted) != 0 {
|
||||
t.Error("a preview was queued for printing")
|
||||
}
|
||||
|
||||
req := moduleRequest(t, "/api/v1/preview/fake?copies=3", "hi")
|
||||
req.Header.Set("Accept", "application/json")
|
||||
resp, raw := do(t, s, req)
|
||||
if resp.StatusCode != http.StatusOK || raw["line_count"] != float64(3) {
|
||||
t.Errorf("status %d, body %v; want three copies of one line", resp.StatusCode, raw)
|
||||
}
|
||||
}
|
||||
|
||||
func TestModulePreviewTooManyLines(t *testing.T) {
|
||||
s, logs := newLoggedServer(t, &fakeJobs{}, &fakePrinter{})
|
||||
s.previewer = testRenderer(5)
|
||||
resp, raw := send(t, s, moduleRequest(t, "/api/v1/preview/note", shoppingNote))
|
||||
e := expectError(t, resp, raw, http.StatusUnprocessableEntity, "too_many_lines")
|
||||
if e.Error != "receipt would print 8 lines, limit is 5" {
|
||||
t.Errorf("error = %q", e.Error)
|
||||
}
|
||||
if failures := errorLines(logs.lines(t)); len(failures) != 0 {
|
||||
t.Errorf("a refusal was logged as a failure: %v", failures)
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,12 @@ func (s *Server) handlePreview(c fiber.Ctx) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return s.preview(c, job)
|
||||
}
|
||||
|
||||
// preview answers with the lines a validated job would print, as
|
||||
// handlePreview describes.
|
||||
func (s *Server) preview(c fiber.Ctx, job receipt.Job) error {
|
||||
preview, err := s.previewer.Preview(c.Context(), job)
|
||||
var limit *receipt.LineLimitError
|
||||
switch {
|
||||
|
||||
@@ -229,9 +229,80 @@ func Routes() []Route {
|
||||
errors: []errorCode{codeJobNotFound},
|
||||
handle: (*Server).handleJob,
|
||||
},
|
||||
{
|
||||
Method: http.MethodPost,
|
||||
Path: BasePath + "/print/{module}",
|
||||
OperationID: "printModule",
|
||||
Summary: "Queue the receipt a module builds from its payload",
|
||||
Description: "The module named in the path builds a receipt from the body, its own payload, " +
|
||||
"which is decoded strictly: an unknown field or one of the wrong type is refused, with " +
|
||||
"every problem listed. The receipt is then validated and queued as on /api/v1/print. A " +
|
||||
"module with nothing to print answers 204.",
|
||||
Tag: "modules",
|
||||
Auth: true,
|
||||
Request: modulePayload{},
|
||||
Params: moduleParams,
|
||||
Responses: []Response{
|
||||
{Status: http.StatusAccepted, Description: "The receipt is queued",
|
||||
Content: []Content{{MediaType: mediaJSON, Body: printqueue.Status{}}},
|
||||
Headers: []Header{{Name: fiber.HeaderLocation, Description: "The job's URL, which answers " +
|
||||
"with its status."}}},
|
||||
{Status: http.StatusNoContent, Description: "The module had nothing to print"},
|
||||
},
|
||||
errors: []errorCode{codeInvalidPayload, codeInvalidQuery, codeUnknownPrinter, codeModuleNotFound,
|
||||
codeModuleFailed, codeQueueFull, codeShuttingDown},
|
||||
handle: (*Server).handlePrintModule,
|
||||
},
|
||||
{
|
||||
Method: http.MethodPost,
|
||||
Path: BasePath + "/preview/{module}",
|
||||
OperationID: "previewModule",
|
||||
Summary: "Show the lines a module's receipt prints, without printing it",
|
||||
Description: "Builds the receipt as /api/v1/print/{module} does and answers as /api/v1/preview " +
|
||||
"does: JSON with the lines' styles when the Accept header prefers application/json to " +
|
||||
"text/plain, and plain text otherwise. It prints nothing and fetches no images.",
|
||||
Tag: "modules",
|
||||
Auth: true,
|
||||
Request: modulePayload{},
|
||||
Params: moduleParams,
|
||||
Responses: []Response{
|
||||
{Status: http.StatusOK, Description: "The lines the printer would print",
|
||||
Content: []Content{
|
||||
{MediaType: mediaText, Body: ""},
|
||||
{MediaType: mediaJSON, Body: previewResponse{}},
|
||||
}},
|
||||
{Status: http.StatusNoContent, Description: "The module had nothing to print"},
|
||||
},
|
||||
errors: []errorCode{codeInvalidPayload, codeInvalidQuery, codeUnknownPrinter, codeModuleNotFound,
|
||||
codeModuleFailed, codeTooManyLines},
|
||||
handle: (*Server).handlePreviewModule,
|
||||
},
|
||||
{
|
||||
Method: http.MethodGet,
|
||||
Path: BasePath + "/modules",
|
||||
OperationID: "listModules",
|
||||
Summary: "List the modules",
|
||||
Description: "Every module the module routes take, sorted by name.",
|
||||
Tag: "modules",
|
||||
Auth: true,
|
||||
Responses: []Response{{Status: http.StatusOK, Description: "The modules",
|
||||
Content: []Content{{MediaType: mediaJSON, Body: moduleList{}}}}},
|
||||
handle: (*Server).handleModules,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// moduleParams are the parameters of the module routes.
|
||||
var moduleParams = []Param{
|
||||
{Name: "module", In: "path", Required: true,
|
||||
Description: "The module's name, e.g. note. GET /api/v1/modules lists them."},
|
||||
{Name: "copies", In: "query",
|
||||
Description: "How many copies to print, each cut separately: a whole number, 1-5. Default 1."},
|
||||
{Name: "printer", In: "query",
|
||||
Description: "Reserved for a second printer: only default is accepted. Any other query parameter " +
|
||||
"is refused."},
|
||||
}
|
||||
|
||||
// pathParam finds the {name} parameters in a route path.
|
||||
var pathParam = regexp.MustCompile(`\{([^/{}]+)\}`)
|
||||
|
||||
|
||||
@@ -17,6 +17,7 @@ import (
|
||||
"github.com/gofiber/fiber/v3/middleware/requestid"
|
||||
|
||||
"uberbringer/internal/pkg/escpos"
|
||||
"uberbringer/internal/pkg/modules"
|
||||
"uberbringer/internal/pkg/printqueue"
|
||||
"uberbringer/internal/pkg/receipt"
|
||||
)
|
||||
@@ -41,11 +42,22 @@ 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.
|
||||
@@ -100,6 +112,8 @@ type Server struct {
|
||||
jobs Jobs
|
||||
printer Printer
|
||||
previewer Previewer
|
||||
modules Modules
|
||||
moduleEnv func() modules.Env
|
||||
logger *slog.Logger
|
||||
}
|
||||
|
||||
@@ -108,6 +122,8 @@ 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:
|
||||
@@ -116,7 +132,15 @@ func New(config Config, deps Deps, logger *slog.Logger) *Server {
|
||||
if config.HealthRecheckDelay <= 0 {
|
||||
config.HealthRecheckDelay = defaultHealthRecheckDelay
|
||||
}
|
||||
s := &Server{config: config, jobs: deps.Jobs, printer: deps.Printer, previewer: deps.Previewer, logger: logger}
|
||||
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,
|
||||
|
||||
@@ -22,6 +22,7 @@ import (
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
|
||||
"uberbringer/internal/pkg/escpos"
|
||||
"uberbringer/internal/pkg/modules"
|
||||
"uberbringer/internal/pkg/printer"
|
||||
"uberbringer/internal/pkg/printqueue"
|
||||
"uberbringer/internal/pkg/receipt"
|
||||
@@ -135,7 +136,22 @@ func newServer(t *testing.T, jobs *fakeJobs, p Printer, logger *slog.Logger, opt
|
||||
for _, opt := range opts {
|
||||
opt(&cfg)
|
||||
}
|
||||
return New(cfg, Deps{Jobs: jobs, Printer: p, Previewer: testRenderer(2000)}, logger)
|
||||
registry, err := modules.NewRegistry(fakeModule{}, modules.Note())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return New(cfg, Deps{
|
||||
Jobs: jobs,
|
||||
Printer: p,
|
||||
Previewer: testRenderer(2000),
|
||||
Modules: registry,
|
||||
ModuleEnv: testModuleEnv,
|
||||
}, logger)
|
||||
}
|
||||
|
||||
// testModuleEnv is 29 Nov 2026 21:04 UTC.
|
||||
func testModuleEnv() modules.Env {
|
||||
return modules.Env{Now: time.Date(2026, 11, 29, 21, 4, 5, 0, time.UTC), Location: time.UTC, TimeLayout: "02 Jan 15:04"}
|
||||
}
|
||||
|
||||
// testRenderer is a TM-T88 renderer in CP437 that previews jobs of up to
|
||||
@@ -709,9 +725,12 @@ func TestRoutesConform(t *testing.T) {
|
||||
}
|
||||
// Each authenticated route maps to a path that reaches it.
|
||||
authenticated := map[string]string{
|
||||
"POST /api/v1/print": "/api/v1/print",
|
||||
"POST /api/v1/preview": "/api/v1/preview",
|
||||
"GET /api/v1/jobs/:id": "/api/v1/jobs/" + id.String(),
|
||||
"POST /api/v1/print": "/api/v1/print",
|
||||
"POST /api/v1/preview": "/api/v1/preview",
|
||||
"POST /api/v1/print/:module": "/api/v1/print/fake",
|
||||
"POST /api/v1/preview/:module": "/api/v1/preview/fake",
|
||||
"GET /api/v1/modules": "/api/v1/modules",
|
||||
"GET /api/v1/jobs/:id": "/api/v1/jobs/" + id.String(),
|
||||
}
|
||||
|
||||
s := newTestServer(t, &fakeJobs{}, &fakePrinter{})
|
||||
@@ -909,6 +928,22 @@ func TestRefusalsAreNotLoggedAsFailures(t *testing.T) {
|
||||
status: http.StatusUnauthorized,
|
||||
level: slog.LevelInfo,
|
||||
},
|
||||
{
|
||||
name: "invalid module payload",
|
||||
jobs: &fakeJobs{},
|
||||
printer: &fakePrinter{},
|
||||
request: func(t *testing.T) *http.Request { return moduleRequest(t, "/api/v1/print/note", `{"title":"x"}`) },
|
||||
status: http.StatusBadRequest,
|
||||
level: slog.LevelInfo,
|
||||
},
|
||||
{
|
||||
name: "unknown module",
|
||||
jobs: &fakeJobs{},
|
||||
printer: &fakePrinter{},
|
||||
request: func(t *testing.T) *http.Request { return moduleRequest(t, "/api/v1/print/notx", `{}`) },
|
||||
status: http.StatusNotFound,
|
||||
level: slog.LevelInfo,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
|
||||
Reference in new issue
Block a user