API inputs go in the JSON body, never in query parameters (owner,
2026-12-01; design.md, "Inputs go in the JSON body"). The module routes
took copies and printer in the query, beside a body that was the
module's payload alone.
The body of POST /api/v1/print/{module} and /api/v1/preview/{module}
now holds the payload under payload, with copies and printer beside it:
{"payload": {...}, "copies": 2, "printer": "default"}. A module may name
its payload's fields as it likes, since none can collide with copies or
printer; that matters for ntfy's messages and for any module that takes
another system's JSON. The body is decoded strictly, and its problems
are answered at once as invalid_payload, each named by its path in the
body: copies, or, once the body is right, payload.done[0] for one the
module finds. A field named body is quoted, "body", so it is never
taken for a problem with the whole body. copies takes 0-5, as a job's
does, 0 meaning one. A query string on these routes gets 400
invalid_query, now worded "query parameters are not accepted".
The ntfy client recipes in docs/api.md wrap $NTFY_RAW in the body. The
Windows command was run here through cmd.exe and PowerShell, and the
printf of the Linux one in sh, each with a message holding quotes, & and
%; neither ran under an ntfy client. No tag carries the module query, so
the 0.2.0 entries in the CHANGELOG change in place (owner, 2026-12-01).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
212 lines
7.3 KiB
Go
212 lines
7.3 KiB
Go
package server
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"log/slog"
|
|
"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 a module request's printer may give
|
|
// while one printer is configured.
|
|
const defaultPrinter = "default"
|
|
|
|
// moduleRequest is the body of the module routes: the module's payload,
|
|
// and the copies to print and the printer to print them on.
|
|
type moduleRequest struct {
|
|
// Payload is the module's payload: a JSON object whose fields the
|
|
// module defines, such as a note's title, text and items.
|
|
//
|
|
// It is kept as sent, since the module decodes it itself.
|
|
Payload json.RawMessage `json:"payload" jsonschema:"required,type=object"`
|
|
|
|
// Copies is how many times the receipt is printed, each with its own
|
|
// cut. Zero means one.
|
|
Copies int `json:"copies,omitempty" jsonschema:"minimum=0,maximum=5"`
|
|
|
|
// Printer is reserved for a second printer: only default is accepted,
|
|
// and an empty name means it.
|
|
Printer string `json:"printer,omitempty"`
|
|
}
|
|
|
|
// 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, "module:"+c.Params("module"))
|
|
}
|
|
|
|
// 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's
|
|
// payload, with the copies the request 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)))
|
|
}
|
|
if len(c.Request().URI().QueryString()) > 0 {
|
|
return job, false, newAPIError(codeInvalidQuery)
|
|
}
|
|
req, err := decodeModuleRequest(c.Body(), name)
|
|
if err != nil {
|
|
return job, false, err
|
|
}
|
|
|
|
job, err = module.Build(c.Context(), req.Payload, s.moduleEnv())
|
|
var (
|
|
payloadErr *modules.PayloadError
|
|
fallbackErr *modules.FallbackError
|
|
)
|
|
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.Within("payload")...)
|
|
case errors.As(err, &fallbackErr):
|
|
// The plain receipt still prints; the fault is reported once.
|
|
s.reportModuleFallback(c, name, fallbackErr)
|
|
case err != nil:
|
|
return job, false, fmt.Errorf("module %s: %w", name, err)
|
|
}
|
|
|
|
if req.Copies > 0 {
|
|
job.Copies = req.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
|
|
}
|
|
|
|
// decodeModuleRequest decodes the body of a module route strictly, so that
|
|
// a misspelt field is not silently ignored, and checks its copies and
|
|
// printer. Every problem with the body is answered at once, as
|
|
// invalid_payload; a printer other than the default is unknown_printer.
|
|
// The payload itself is the module's to check.
|
|
func decodeModuleRequest(body []byte, module string) (moduleRequest, error) {
|
|
var req moduleRequest
|
|
invalid := func(problems []string) error {
|
|
msg := fmt.Sprintf("invalid body for module %q", module)
|
|
return newAPIError(codeInvalidPayload.withMessage(msg), problems...)
|
|
}
|
|
var problems []string
|
|
if err := modules.DecodeStrict(body, &req); err != nil {
|
|
var pe *modules.PayloadError
|
|
if !errors.As(err, &pe) {
|
|
return req, err
|
|
}
|
|
// A body that is not one JSON object has no fields to check.
|
|
if len(pe.Problems) == 1 && strings.HasPrefix(pe.Problems[0], "body: ") {
|
|
return req, invalid(pe.Problems)
|
|
}
|
|
problems = pe.Problems
|
|
}
|
|
switch payload := bytes.TrimSpace(req.Payload); {
|
|
case len(payload) == 0 || bytes.Equal(payload, []byte("null")):
|
|
problems = append(problems, "payload: required")
|
|
case payload[0] != '{':
|
|
problems = append(problems, "payload: expected a JSON object")
|
|
}
|
|
if req.Copies < 0 || req.Copies > receipt.MaxCopies {
|
|
problems = append(problems, fmt.Sprintf("copies: must be 1-%d", receipt.MaxCopies))
|
|
}
|
|
if len(problems) > 0 {
|
|
return req, invalid(problems)
|
|
}
|
|
if req.Printer != "" && req.Printer != defaultPrinter {
|
|
msg := fmt.Sprintf("printer %q is not configured; the only printer is %q", req.Printer, defaultPrinter)
|
|
return req, newAPIError(codeUnknownPrinter.withMessage(msg))
|
|
}
|
|
return req, 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))
|
|
}
|
|
|
|
// reportModuleFallback logs and reports a module that could not lay out
|
|
// its receipt and built the plain fallback instead, which still prints.
|
|
// The error never quotes the payload.
|
|
func (s *Server) reportModuleFallback(c fiber.Ctx, name string, fallbackErr *modules.FallbackError) {
|
|
attrs := []slog.Attr{
|
|
slog.String("module", name),
|
|
slog.String("err", fallbackErr.Error()),
|
|
slog.String("path", c.Path()),
|
|
slog.String("request_id", requestid.FromContext(c)),
|
|
}
|
|
if fallbackErr.Stack != "" {
|
|
attrs = append(attrs, slog.String("stack", fallbackErr.Stack))
|
|
}
|
|
s.logger.LogAttrs(c.Context(), slog.LevelError, "module printed its fallback receipt", attrs...)
|
|
hubFrom(c).CaptureException(fmt.Errorf("module %s: %w", name, fallbackErr))
|
|
}
|