Generate the OpenAPI document from a route table
Security / Vulnerability check (push) Successful in 38s
Test / Lint and test (push) Successful in 1m53s

The server registers its routes from one table in server/routes.go, and
tools/genopenapi (run by go generate) writes docs/swagger.json, an
OpenAPI 3.1 document, from the same table and the Go types it names.
Schemas are reflected with invopop/jsonschema: descriptions from the
first paragraph of the doc comments, enums and limits from jsonschema
tags. Request schemas are strict, as the decoder is; response schemas
allow fields added later. The daemon serves the embedded document at
GET /openapi.json without a token, internal/app passes it to the server
in its config, and release archives and the Docker build include it.

Tests keep it honest: a golden test and a CI step fail when the
document is stale, every registered route must be in the table, and the
tags are held to validation, to the Go constants and to the values the
handlers send. receipt.Element and printqueue.Status gain field doc
comments for the descriptions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
57_WolveandClaude Opus 5.5 committed 2026-11-30 09:30:42 -06:00
1 parent 9f7c5db923
commit bdd337e2dc
31 files changed
+3153 -128

No files matched your search

+13 -6
View File
@@ -61,12 +61,19 @@ const (
// Status describes a job.
type Status struct {
ID JobID `json:"id"`
State State `json:"status"`
Error string `json:"error,omitempty"`
Attempts int `json:"attempts,omitempty"`
CreatedAt time.Time `json:"created_at"`
StartedAt *time.Time `json:"started_at,omitempty"`
// ID identifies the job.
ID JobID `json:"id"`
// State is where the job is in its lifecycle.
State State `json:"status" jsonschema:"enum=queued,enum=printing,enum=done,enum=failed"`
// Error says why a failed job failed.
Error string `json:"error,omitempty"`
// Attempts is how many times the job was sent to the printer.
Attempts int `json:"attempts,omitempty"`
// CreatedAt is when the job was queued.
CreatedAt time.Time `json:"created_at"`
// StartedAt is when the worker took the job.
StartedAt *time.Time `json:"started_at,omitempty"`
// FinishedAt is when the job was done or failed.
FinishedAt *time.Time `json:"finished_at,omitempty"`
}
+50
View File
@@ -0,0 +1,50 @@
package printqueue
import (
"go/ast"
"go/parser"
"go/token"
"reflect"
"slices"
"strconv"
"strings"
"testing"
)
// The status enum in Status's jsonschema tag lists every State constant.
func TestStateEnumListsEveryState(t *testing.T) {
file, err := parser.ParseFile(token.NewFileSet(), "queue.go", nil, 0)
if err != nil {
t.Fatal(err)
}
var states []string
ast.Inspect(file, func(n ast.Node) bool {
spec, ok := n.(*ast.ValueSpec)
if !ok {
return true
}
if ident, ok := spec.Type.(*ast.Ident); !ok || ident.Name != "State" {
return true
}
for _, v := range spec.Values {
if lit, ok := v.(*ast.BasicLit); ok && lit.Kind == token.STRING {
s, _ := strconv.Unquote(lit.Value)
states = append(states, s)
}
}
return true
})
f, _ := reflect.TypeFor[Status]().FieldByName("State")
var enum []string
for part := range strings.SplitSeq(f.Tag.Get("jsonschema"), ",") {
if v, ok := strings.CutPrefix(part, "enum="); ok {
enum = append(enum, v)
}
}
slices.Sort(states)
slices.Sort(enum)
if len(states) == 0 || !slices.Equal(states, enum) {
t.Errorf("Status.State enum %v, State constants %v", enum, states)
}
}
+106 -48
View File
@@ -50,75 +50,133 @@ const (
)
// Job is a receipt to print.
//
// The jsonschema tags on Job, Element and Pair give the JSON Schema of a
// job; Validate enforces the rules.
type Job struct {
Elements []Element `json:"elements"`
// Elements are the items on the receipt, in order: 1-500, box children
// counted.
Elements []Element `json:"elements" jsonschema:"required,minItems=1,maxItems=500"`
// Copies is how many times the receipt is printed, each with its own
// cut. Zero means one.
Copies int `json:"copies,omitempty"`
Copies int `json:"copies,omitempty" jsonschema:"minimum=0,maximum=5"`
}
// Element is one item on a receipt. Type selects which fields apply. On the
// blocks (box, rule and kv) and inside a box, a field that does not apply is
// an error; on the other types it is ignored, except for the block fields.
// Width and Height mean character multipliers for text, module width and
// bar height for barcodes, and target width in dots for images. A block's
// width is set by Columns, in characters of its own size and font, never by
// Width; without Columns a block spans the line.
// Element is one item on a receipt. Its type selects which fields apply. On
// the blocks (box, rule and kv) and inside a box, a field that does not
// apply is an error; on the other types it is ignored, except for the block
// fields. width and height mean character multipliers for text, module width
// and bar height for barcodes, and target width in dots for images. A
// block's width is set by columns, in characters of its own size and font,
// never by width; without columns a block spans the line. The enums list
// the canonical spellings: apart from type and leader, other letter case is
// accepted too, and so are a few aliases such as centre and ean-13.
type Element struct {
Type string `json:"type"`
// Type is the kind of element. box, rule and kv are blocks, laid out to
// the printer model's width when the job prints.
Type string `json:"type" jsonschema:"required,enum=text,enum=feed,enum=qr,enum=barcode,enum=image,enum=raw,enum=cut,enum=box,enum=rule,enum=kv"`
// Text.
Text string `json:"text,omitempty"`
Bold bool `json:"bold,omitempty"`
Size int `json:"size,omitempty"`
Width int `json:"width,omitempty"`
Height int `json:"height,omitempty"`
Font string `json:"font,omitempty"`
Align string `json:"align,omitempty"`
Underline int `json:"underline,omitempty"`
Invert bool `json:"invert,omitempty"`
Newline *bool `json:"newline,omitempty"`
Wrap *bool `json:"wrap,omitempty"`
// Text is a text element's UTF-8 text, a box's body or a rule's label.
// \n starts a new line.
Text string `json:"text,omitempty"`
// Bold prints the text in bold: a box's text, a rule's label.
Bold bool `json:"bold,omitempty"`
// Size sets width and height together: 1-8 for text, 1-3 for a block,
// whose borders scale with its text. For a QR code it is the module size
// in dots, 1-16, default 6. 0 means the default.
Size int `json:"size,omitempty" jsonschema:"minimum=0,maximum=16"`
// Width is the character width for text (1-8), the module width of a
// barcode (2-6, default 3), or the target width of an image in dots. 0
// means the default.
Width int `json:"width,omitempty" jsonschema:"minimum=0"`
// Height is the character height for text (1-8), or the bar height of a
// barcode in dots (1-255, default 80). 0 means the default.
Height int `json:"height,omitempty" jsonschema:"minimum=0,maximum=255"`
// Font is a, the default, or b, the smaller font; on a block it sets
// the font of its borders and text.
Font string `json:"font,omitempty" jsonschema:"enum=a,enum=b"`
// Align places text, a QR code, a barcode or an image, a box's text, or
// a rule's label. Default left, center for a rule's label.
Align string `json:"align,omitempty" jsonschema:"enum=left,enum=center,enum=right"`
// Underline is 0, 1 for thin or 2 for thick.
Underline int `json:"underline,omitempty" jsonschema:"minimum=0,maximum=2"`
// Invert prints white on black.
Invert bool `json:"invert,omitempty"`
// Newline false keeps the next element on the same line. Default true.
Newline *bool `json:"newline,omitempty"`
// Wrap false sends the text as it is and lets the printer wrap it,
// or inside a box splits lines at the box edge. Default true: wrap at
// spaces.
Wrap *bool `json:"wrap,omitempty"`
// Feed.
Lines int `json:"lines,omitempty"`
// Lines is a feed's number of lines, 1-255. 0 means the default, 1.
Lines int `json:"lines,omitempty" jsonschema:"minimum=0,maximum=255"`
// QR code and barcode.
Data string `json:"data,omitempty"`
Correction string `json:"correction,omitempty"`
Symbology string `json:"symbology,omitempty"`
HRI string `json:"hri,omitempty"`
// Data is a QR code's data, up to 7089 bytes of UTF-8, or a barcode's:
// digits for EAN and UPC, A-Z 0-9 -.$/+% and space for CODE39, printable
// ASCII for CODE128.
Data string `json:"data,omitempty"`
// Correction is a QR code's error correction level. Default M.
Correction string `json:"correction,omitempty" jsonschema:"enum=L,enum=M,enum=Q,enum=H"`
// Symbology is a barcode's type; required for a barcode.
Symbology string `json:"symbology,omitempty" jsonschema:"enum=ean13,enum=ean8,enum=upca,enum=upce,enum=code39,enum=code128"`
// HRI places a barcode's human-readable text. Default below.
HRI string `json:"hri,omitempty" jsonschema:"enum=none,enum=above,enum=below,enum=both"`
// Image.
URL string `json:"url,omitempty"`
// URL is an image's http or https URL. Set url or base64.
URL string `json:"url,omitempty"`
// Base64 is an image's data in base64, or a data:image/...;base64, URI:
// PNG, JPEG, GIF or WebP.
Base64 string `json:"base64,omitempty"`
// Raw.
// Hex is a raw element's ESC/POS bytes in hex, spaces allowed, e.g.
// "1B 61 01". It is sent as given.
Hex string `json:"hex,omitempty"`
// Cut.
Mode string `json:"mode,omitempty"`
// Mode is a cut's mode. Default partial.
Mode string `json:"mode,omitempty" jsonschema:"enum=partial,enum=full"`
// Blocks. Style is the border or line style of a box or rule. Children
// are the body of a box, one level deep.
Children []Element `json:"children,omitempty"`
Title string `json:"title,omitempty"`
TitleStyle string `json:"title_style,omitempty"`
Footer string `json:"footer,omitempty"`
Style string `json:"style,omitempty"`
Padding *int `json:"padding,omitempty"`
Fit bool `json:"fit,omitempty"`
Columns int `json:"columns,omitempty"`
Pairs []Pair `json:"pairs,omitempty"`
Leader string `json:"leader,omitempty"`
// Children are a box's body as elements, one level deep: text, feed,
// rule and kv. Set text or children, not both.
Children []Element `json:"children,omitempty"`
// Title is text set into a box's top border.
Title string `json:"title,omitempty"`
// TitleStyle is inline, the default, or capped.
TitleStyle string `json:"title_style,omitempty" jsonschema:"enum=inline,enum=capped"`
// Footer is text set into a box's bottom border, on the right.
Footer string `json:"footer,omitempty"`
// Style is a box's border style (single, double, double-h, double-v or
// ascii) or a rule's line style (single, double, light, medium, dark,
// solid, dashed, dotted or ascii). Default single.
Style string `json:"style,omitempty" jsonschema:"enum=single,enum=double,enum=double-h,enum=double-v,enum=ascii,enum=light,enum=medium,enum=dark,enum=solid,enum=dashed,enum=dotted"`
// Padding is the spaces between a box's side borders and its body, 0-3.
// Default 1.
Padding *int `json:"padding,omitempty" jsonschema:"minimum=0,maximum=3"`
// Fit shrinks a box to its widest line, title and footer included, and
// centres it. columns is then the most it may take.
Fit bool `json:"fit,omitempty"`
// Columns is a block's width in characters of its own size and font,
// 1-255, cut to the line. A narrower block is centred. 0 means the
// default, the whole line.
Columns int `json:"columns,omitempty" jsonschema:"minimum=0,maximum=255"`
// Pairs are a kv block's rows, 1-100; required for kv.
Pairs []Pair `json:"pairs,omitempty" jsonschema:"minItems=1,maxItems=100"`
// Leader is the fill between a kv row's key and value: ".", the
// default, "·", " " (or "space"), "_", "-" or "─".
Leader string `json:"leader,omitempty" jsonschema:"enum=.,enum=·,enum= ,enum=space,enum=_,enum=-,enum=─"`
}
// Pair is one row of a kv block: a key, a leader and a value.
type Pair struct {
Key string `json:"key"`
// Key is the row's key, on the left. A key too long for the line is cut
// with "...".
Key string `json:"key" jsonschema:"required,minLength=1"`
// Value is the row's value, on the right. A long value wraps into the
// room after the key.
Value string `json:"value"`
Bold bool `json:"bold,omitempty"`
// Bold prints the key and the value bold.
Bold bool `json:"bold,omitempty"`
}
// DecodeJob strictly decodes one JSON job. An unknown field is an error, so
+224
View File
@@ -0,0 +1,224 @@
package receipt
import (
"errors"
"go/ast"
"go/parser"
"go/token"
"reflect"
"slices"
"strconv"
"strings"
"testing"
)
// enumTag returns the enum values in the jsonschema tag of Element's field.
func enumTag(t *testing.T, field string) []string {
t.Helper()
f, ok := reflect.TypeFor[Element]().FieldByName(field)
if !ok {
t.Fatalf("Element has no field %s", field)
}
var values []string
for part := range strings.SplitSeq(f.Tag.Get("jsonschema"), ",") {
if v, ok := strings.CutPrefix(part, "enum="); ok {
values = append(values, v)
}
}
return values
}
// problemsWith validates a job of el alone and returns the problems that
// name field, as "font must be a or b" or "unknown symbology" do.
func problemsWith(t *testing.T, el Element, field string) []string {
t.Helper()
var ve *ValidationError
err := Job{Elements: []Element{el}}.Validate()
if err != nil && !errors.As(err, &ve) {
t.Fatalf("Validate: %v", err)
}
var out []string
if ve != nil {
for _, p := range ve.Problems {
if strings.Contains(p, "): "+field+" ") || strings.Contains(p, " "+field+" ") {
out = append(out, p)
}
}
}
return out
}
// The type enum lists every Type constant, so the schema offers every
// element type validation accepts.
func TestTypeEnumListsEveryType(t *testing.T) {
file, err := parser.ParseFile(token.NewFileSet(), "job.go", nil, 0)
if err != nil {
t.Fatal(err)
}
var types []string
ast.Inspect(file, func(n ast.Node) bool {
spec, ok := n.(*ast.ValueSpec)
if !ok {
return true
}
for i, name := range spec.Names {
if !strings.HasPrefix(name.Name, "Type") || i >= len(spec.Values) {
continue
}
if lit, ok := spec.Values[i].(*ast.BasicLit); ok && lit.Kind == token.STRING {
v, _ := strconv.Unquote(lit.Value)
types = append(types, v)
}
}
return true
})
enum := enumTag(t, "Type")
slices.Sort(types)
slices.Sort(enum)
if !slices.Equal(types, enum) {
t.Errorf("Element.Type enum %v, Type constants %v", enum, types)
}
}
// Each enum value in Element's jsonschema tags passes validation on an
// element it applies to, and a made-up value does not. Validation also takes
// other letter case and a few aliases, which the enums leave out.
func TestEnumTagsMatchValidation(t *testing.T) {
tests := []struct {
field, json string
// elements set the field to v on the elements it applies to; a
// value is valid when one of them accepts it.
elements func(v string) []Element
}{
{"Font", "font", func(v string) []Element { return []Element{{Type: TypeText, Text: "x", Font: v}} }},
{"Align", "align", func(v string) []Element { return []Element{{Type: TypeText, Text: "x", Align: v}} }},
{"Correction", "correction", func(v string) []Element {
return []Element{{Type: TypeQR, Data: "x", Correction: v}}
}},
{"Symbology", "symbology", func(v string) []Element {
return []Element{{Type: TypeBarcode, Data: "0", Symbology: v}}
}},
{"HRI", "hri", func(v string) []Element {
return []Element{{Type: TypeBarcode, Data: "x", Symbology: "code128", HRI: v}}
}},
{"Mode", "mode", func(v string) []Element { return []Element{{Type: TypeCut, Mode: v}} }},
{"TitleStyle", "title_style", func(v string) []Element {
return []Element{{Type: TypeBox, Text: "x", Title: "t", TitleStyle: v}}
}},
{"Style", "style", func(v string) []Element {
return []Element{{Type: TypeBox, Text: "x", Style: v}, {Type: TypeRule, Style: v}}
}},
{"Leader", "leader", func(v string) []Element {
return []Element{{Type: TypeKV, Pairs: []Pair{{Key: "k", Value: "v"}}, Leader: v}}
}},
}
for _, tt := range tests {
t.Run(tt.field, func(t *testing.T) {
accepted := func(v string) bool {
for _, el := range tt.elements(v) {
if len(problemsWith(t, el, tt.json)) == 0 {
return true
}
}
return false
}
for _, v := range enumTag(t, tt.field) {
if !accepted(v) {
t.Errorf("%s %q is in the enum but validation refuses it", tt.json, v)
}
}
if accepted("not-a-value") {
t.Errorf("%s accepts a value outside its enum", tt.json)
}
})
}
}
// tagBound returns the number after key= in the jsonschema tag of field on
// typ, e.g. maximum=5.
func tagBound(t *testing.T, typ reflect.Type, field, key string) (int, bool) {
t.Helper()
f, ok := typ.FieldByName(field)
if !ok {
t.Fatalf("%s has no field %s", typ.Name(), field)
}
for part := range strings.SplitSeq(f.Tag.Get("jsonschema"), ",") {
if v, ok := strings.CutPrefix(part, key+"="); ok {
n, err := strconv.Atoi(v)
if err != nil {
t.Fatalf("%s.%s: %s=%q is not a number", typ.Name(), field, key, v)
}
return n, true
}
}
return 0, false
}
// Each numeric bound in the jsonschema tags is a limit validation enforces:
// a job at the bound passes, and one just beyond it fails with a problem
// naming the field.
func TestBoundTagsMatchValidation(t *testing.T) {
text := Element{Type: TypeText, Text: "x"}
kv := func(pairs int, key string) Element {
el := Element{Type: TypeKV}
for range pairs {
el.Pairs = append(el.Pairs, Pair{Key: key, Value: "v"})
}
return el
}
one := func(el Element) Job { return Job{Elements: []Element{el}} }
tests := []struct {
typ reflect.Type
field, json string
lower, upper string // the tag keys of the bounds
job func(n int) Job
}{
{reflect.TypeFor[Job](), "Copies", "copies", "minimum", "maximum",
func(n int) Job { return Job{Elements: []Element{text}, Copies: n} }},
{reflect.TypeFor[Job](), "Elements", "elements", "minItems", "maxItems",
func(n int) Job { return Job{Elements: slices.Repeat([]Element{text}, n)} }},
{reflect.TypeFor[Element](), "Size", "size", "minimum", "maximum",
func(n int) Job { return one(Element{Type: TypeQR, Data: "x", Size: n}) }},
{reflect.TypeFor[Element](), "Height", "height", "minimum", "maximum",
func(n int) Job { return one(Element{Type: TypeBarcode, Symbology: "code128", Data: "x", Height: n}) }},
{reflect.TypeFor[Element](), "Underline", "underline", "minimum", "maximum",
func(n int) Job { return one(Element{Type: TypeText, Text: "x", Underline: n}) }},
{reflect.TypeFor[Element](), "Lines", "lines", "minimum", "maximum",
func(n int) Job { return one(Element{Type: TypeFeed, Lines: n}) }},
{reflect.TypeFor[Element](), "Padding", "padding", "minimum", "maximum",
func(n int) Job { return one(Element{Type: TypeBox, Text: "x", Padding: &n}) }},
{reflect.TypeFor[Element](), "Columns", "columns", "minimum", "maximum",
func(n int) Job { return one(Element{Type: TypeBox, Text: "x", Columns: n}) }},
{reflect.TypeFor[Element](), "Pairs", "pairs", "minItems", "maxItems",
func(n int) Job { return one(kv(n, "k")) }},
{reflect.TypeFor[Pair](), "Key", "key", "minLength", "",
func(n int) Job { return one(kv(1, strings.Repeat("k", n))) }},
}
for _, tt := range tests {
t.Run(tt.json, func(t *testing.T) {
check := func(key string, at, beyond int) {
if err := tt.job(at).Validate(); err != nil {
t.Errorf("%s=%d at the %s bound fails validation: %v", tt.json, at, key, err)
}
err := tt.job(beyond).Validate()
if err == nil || !strings.Contains(err.Error(), tt.json) {
t.Errorf("%s=%d beyond the %s bound: Validate = %v, want a problem naming %s",
tt.json, beyond, key, err, tt.json)
}
}
if n, ok := tagBound(t, tt.typ, tt.field, tt.lower); ok {
check(tt.lower, n, n-1)
} else {
t.Errorf("%s has no %s tag", tt.json, tt.lower)
}
if tt.upper == "" {
return
}
if n, ok := tagBound(t, tt.typ, tt.field, tt.upper); ok {
check(tt.upper, n, n+1)
} else {
t.Errorf("%s has no %s tag", tt.json, tt.upper)
}
})
}
}