Generate the OpenAPI document from a route table
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:
1 parent
9f7c5db923
commit
bdd337e2dc
31 files changed
+3153
-128
No files matched your search
+5
-2
@@ -1,7 +1,10 @@
|
|||||||
# The image is built from the Go sources alone; everything else, the local
|
# The image is built from the Go sources and the embedded OpenAPI document
|
||||||
# config.toml with its API secret included, stays out of the build context.
|
# alone; everything else, the local config.toml with its API secret
|
||||||
|
# included, stays out of the build context.
|
||||||
*
|
*
|
||||||
!go.mod
|
!go.mod
|
||||||
!go.sum
|
!go.sum
|
||||||
!cmd
|
!cmd
|
||||||
!internal
|
!internal
|
||||||
|
!docs/embed.go
|
||||||
|
!docs/swagger.json
|
||||||
@@ -58,6 +58,13 @@ jobs:
|
|||||||
- name: staticcheck
|
- name: staticcheck
|
||||||
run: go tool staticcheck ./...
|
run: go tool staticcheck ./...
|
||||||
|
|
||||||
|
# docs/swagger.json is generated from the route table and its types; a
|
||||||
|
# change to either must come with the regenerated document.
|
||||||
|
- name: OpenAPI document up to date
|
||||||
|
run: |
|
||||||
|
go generate ./...
|
||||||
|
git diff --exit-code -- docs/swagger.json
|
||||||
|
|
||||||
# The limit is per package: a hung test fails with every goroutine's
|
# The limit is per package: a hung test fails with every goroutine's
|
||||||
# stack instead of being killed by the runner.
|
# stack instead of being killed by the runner.
|
||||||
- name: Test (race detector)
|
- name: Test (race detector)
|
||||||
|
|||||||
+5
-3
@@ -43,9 +43,9 @@ archives:
|
|||||||
- formats: [tar]
|
- formats: [tar]
|
||||||
name_template: "{{ .ProjectName }}_{{ .Os }}_{{ .Arch }}{{ if .Arm }}v{{ .Arm }}{{ end }}"
|
name_template: "{{ .ProjectName }}_{{ .Os }}_{{ .Arch }}{{ if .Arm }}v{{ .Arm }}{{ end }}"
|
||||||
# Listing files replaces goreleaser's defaults, so the license, README,
|
# Listing files replaces goreleaser's defaults, so the license, README,
|
||||||
# API reference and changelog are listed too. Each must exist; paths are
|
# API reference, OpenAPI document and changelog are listed too. Each
|
||||||
# kept, and install.sh takes packaging/uberbringer.service from the
|
# must exist; paths are kept, and install.sh takes
|
||||||
# unpacked archive.
|
# packaging/uberbringer.service from the unpacked archive.
|
||||||
files:
|
files:
|
||||||
- src: LICENSE.txt
|
- src: LICENSE.txt
|
||||||
info: &commit-mtime
|
info: &commit-mtime
|
||||||
@@ -54,6 +54,8 @@ archives:
|
|||||||
info: *commit-mtime
|
info: *commit-mtime
|
||||||
- src: docs/api.md
|
- src: docs/api.md
|
||||||
info: *commit-mtime
|
info: *commit-mtime
|
||||||
|
- src: docs/swagger.json
|
||||||
|
info: *commit-mtime
|
||||||
- src: CHANGELOG.md
|
- src: CHANGELOG.md
|
||||||
info: *commit-mtime
|
info: *commit-mtime
|
||||||
- src: configs/config.example.toml
|
- src: configs/config.example.toml
|
||||||
|
|||||||
@@ -7,6 +7,16 @@ version may break callers; such changes are listed under **Breaking**.
|
|||||||
|
|
||||||
## [Unreleased]
|
## [Unreleased]
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- `docs/swagger.json`, the OpenAPI 3.1 document of the HTTP API: every
|
||||||
|
route with its parameters, responses and the error codes it and its
|
||||||
|
middleware answer with, and the schemas of the job and of every response.
|
||||||
|
It is generated from the route table and the Go types
|
||||||
|
(`go generate ./...`), served at `GET /openapi.json` without a token, and
|
||||||
|
shipped in the release archives and the Docker build. CI fails when it is
|
||||||
|
out of date.
|
||||||
|
|
||||||
## [0.2.0] - 2026-11-30
|
## [0.2.0] - 2026-11-30
|
||||||
|
|
||||||
The daemon is rewritten, and so are its install script and release process,
|
The daemon is rewritten, and so are its install script and release process,
|
||||||
|
|||||||
@@ -12,11 +12,18 @@ root `Dockerfile`.
|
|||||||
- Coding rules: `R:\Current Storage\Projects\AI-Memory\Golang-Programming-Standards.md`.
|
- Coding rules: `R:\Current Storage\Projects\AI-Memory\Golang-Programming-Standards.md`.
|
||||||
Every change follows it. `.gitea/workflows/`, `packaging/`, the root
|
Every change follows it. `.gitea/workflows/`, `packaging/`, the root
|
||||||
`Dockerfile` and `install.sh` take the place of the standards' `build/` and
|
`Dockerfile` and `install.sh` take the place of the standards' `build/` and
|
||||||
`scripts/`.
|
`scripts/`, and the generated `docs/swagger.json` takes the place of
|
||||||
|
`api/`.
|
||||||
- `docs/api.md` is the reference for the API: routes, elements, blocks and
|
- `docs/api.md` is the reference for the API: routes, elements, blocks and
|
||||||
error codes. `README.md` covers installing,
|
error codes. `README.md` covers installing,
|
||||||
configuration, the command line and the package layout. There is no
|
configuration, the command line and the package layout.
|
||||||
OpenAPI document.
|
- `docs/swagger.json`, the OpenAPI 3.1 document, is generated
|
||||||
|
(`go generate ./...`, which runs `tools/genopenapi`) from the route table in
|
||||||
|
`internal/app/uberbringer/server/routes.go` and the Go types it names: their
|
||||||
|
`json` and `jsonschema` tags and their doc comments. The server registers
|
||||||
|
its routes from the same table. Never edit the file by hand; regenerate it
|
||||||
|
in the same commit as any change to a route or to a request or response
|
||||||
|
type.
|
||||||
- `docs/design.md` explains why the daemon is shaped as it is and lists what
|
- `docs/design.md` explains why the daemon is shaped as it is and lists what
|
||||||
is deferred. Change it in the same commit as any code that departs from it.
|
is deferred. Change it in the same commit as any code that departs from it.
|
||||||
- `docs/plans/<feature>.md` holds a feature until it ships. A decision made
|
- `docs/plans/<feature>.md` holds a feature until it ships. A decision made
|
||||||
@@ -27,13 +34,18 @@ root `Dockerfile`.
|
|||||||
|
|
||||||
`cmd/uberbringer` is a thin main. `internal/app/uberbringer` holds the CLI and
|
`cmd/uberbringer` is a thin main. `internal/app/uberbringer` holds the CLI and
|
||||||
the wiring, and `server/` holds the HTTP API. `internal/pkg/*` holds the
|
the wiring, and `server/` holds the HTTP API. `internal/pkg/*` holds the
|
||||||
libraries. README § Development lists them. The module path is the bare
|
libraries. README § Development lists them. `tools/genopenapi` writes
|
||||||
|
`docs/swagger.json`; the `docs` package embeds it, and `internal/app` hands
|
||||||
|
it to the server in its config, so the generator never builds the package
|
||||||
|
that embeds its own output. The module path is the bare
|
||||||
`uberbringer`, so imports read `uberbringer/internal/...`. Imports point down:
|
`uberbringer`, so imports read `uberbringer/internal/...`. Imports point down:
|
||||||
|
|
||||||
- server → printqueue, receipt, printer, escpos
|
- server → printqueue, receipt, printer, escpos
|
||||||
- printqueue → receipt
|
- printqueue → receipt
|
||||||
- receipt → escpos, raster
|
- receipt → escpos, raster
|
||||||
- printer → escpos
|
- printer → escpos
|
||||||
|
- internal/app → docs, server and the libraries
|
||||||
|
- tools/genopenapi → server, printqueue, receipt
|
||||||
|
|
||||||
Only `internal/app` reads config or wires in safehttp. Packages under
|
Only `internal/app` reads config or wires in safehttp. Packages under
|
||||||
`internal/pkg` take plain values, and escpos knows nothing of JSON or HTTP.
|
`internal/pkg` take plain values, and escpos knows nothing of JSON or HTTP.
|
||||||
@@ -49,6 +61,7 @@ works from PowerShell and fails from Git Bash.
|
|||||||
go mod tidy -diff
|
go mod tidy -diff
|
||||||
go vet ./...
|
go vet ./...
|
||||||
go tool staticcheck ./...
|
go tool staticcheck ./...
|
||||||
|
go generate ./... && git diff --exit-code -- docs/swagger.json # the OpenAPI document is up to date
|
||||||
go test -race -timeout 5m ./... *> "$env:TEMP\uberbringer-test.txt"; "exit $LASTEXITCODE"
|
go test -race -timeout 5m ./... *> "$env:TEMP\uberbringer-test.txt"; "exit $LASTEXITCODE"
|
||||||
go tool govulncheck ./... # after any dependency or toolchain change, and before a tag
|
go tool govulncheck ./... # after any dependency or toolchain change, and before a tag
|
||||||
goreleaser release --snapshot --clean # into dist/; after a change to .goreleaser.yaml or packaging/
|
goreleaser release --snapshot --clean # into dist/; after a change to .goreleaser.yaml or packaging/
|
||||||
@@ -101,9 +114,20 @@ docs (`README.md` or `docs/api.md`) and CHANGELOG.md say what changed.
|
|||||||
- These changes land in one commit with their docs:
|
- These changes land in one commit with their docs:
|
||||||
- A config key: `internal/pkg/config` (the default and the validation),
|
- A config key: `internal/pkg/config` (the default and the validation),
|
||||||
`configs/config.example.toml` and README § Configuration.
|
`configs/config.example.toml` and README § Configuration.
|
||||||
- A route, element field, status or error code: its code, its tests and
|
- A route, element field, status or error code: its code, its tests,
|
||||||
`docs/api.md`. A new route also needs its case in `TestRoutesConform`,
|
`docs/api.md` and the regenerated `docs/swagger.json`. A route is an
|
||||||
which fails for a route without one.
|
entry in the table in `server/routes.go`, never a direct
|
||||||
|
`app.Get`/`Post`; it also needs its case in `TestRoutesConform`, which
|
||||||
|
fails for a route without one, and `TestRegisteredRoutesAreTheTable`
|
||||||
|
fails for a route registered outside the table.
|
||||||
|
- An enum value or a limit goes into the field's `jsonschema` tag. The
|
||||||
|
tests in `receipt/schema_test.go`, `printqueue/schema_test.go` and
|
||||||
|
`server/schema_test.go` hold the tags to validation, to the Go constants
|
||||||
|
and to the values the handlers send. The enums list the canonical
|
||||||
|
spellings; validation also takes other letter case and a few aliases.
|
||||||
|
- A schema description is the first paragraph of the type's or field's
|
||||||
|
doc comment. Write it for API readers; notes for Go readers go after a
|
||||||
|
blank `//` line.
|
||||||
- Dependencies are at their latest stable release when added or bumped.
|
- Dependencies are at their latest stable release when added or bumped.
|
||||||
- Commit, push, tag or release only when the owner asks. Releases are
|
- Commit, push, tag or release only when the owner asks. Releases are
|
||||||
`vX.Y.Z` tags on `main`; `release.yml` refuses a tag whose commit is not on
|
`vX.Y.Z` tags on `main`; `release.yml` refuses a tag whose commit is not on
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
.PHONY: build test lint fmt fmt-check vet tidy tidy-check vuln release-check snapshot check run
|
.PHONY: build test lint fmt fmt-check vet tidy tidy-check vuln openapi openapi-check release-check snapshot check run
|
||||||
|
|
||||||
# Without the leading v, as goreleaser's {{ .Version }} reports it.
|
# Without the leading v, as goreleaser's {{ .Version }} reports it.
|
||||||
VERSION ?= $(patsubst v%,%,$(shell git describe --tags --always --dirty 2>/dev/null || echo dev))
|
VERSION ?= $(patsubst v%,%,$(shell git describe --tags --always --dirty 2>/dev/null || echo dev))
|
||||||
@@ -37,6 +37,14 @@ tidy-check:
|
|||||||
vuln:
|
vuln:
|
||||||
go tool govulncheck ./...
|
go tool govulncheck ./...
|
||||||
|
|
||||||
|
# Runs every go:generate directive, which writes docs/swagger.json.
|
||||||
|
openapi:
|
||||||
|
go generate ./...
|
||||||
|
|
||||||
|
# Fails when docs/swagger.json differs from what the route table produces.
|
||||||
|
openapi-check: openapi
|
||||||
|
git diff --exit-code -- docs/swagger.json
|
||||||
|
|
||||||
# Validates .goreleaser.yaml without building anything.
|
# Validates .goreleaser.yaml without building anything.
|
||||||
release-check:
|
release-check:
|
||||||
goreleaser check
|
goreleaser check
|
||||||
@@ -49,7 +57,7 @@ snapshot:
|
|||||||
|
|
||||||
# The gate .gitea/workflows/test.yml runs, in the same order.
|
# The gate .gitea/workflows/test.yml runs, in the same order.
|
||||||
# .gitea/workflows/security.yml runs vuln.
|
# .gitea/workflows/security.yml runs vuln.
|
||||||
check: fmt-check tidy-check vet lint test release-check
|
check: fmt-check tidy-check vet lint openapi-check test release-check
|
||||||
|
|
||||||
run:
|
run:
|
||||||
go run ./cmd/uberbringer --config config.toml
|
go run ./cmd/uberbringer --config config.toml
|
||||||
@@ -124,6 +124,8 @@ make run
|
|||||||
|
|
||||||
[docs/api.md](docs/api.md) is the API reference: the routes, the print
|
[docs/api.md](docs/api.md) is the API reference: the routes, the print
|
||||||
elements and blocks, and the error codes.
|
elements and blocks, and the error codes.
|
||||||
|
[docs/swagger.json](docs/swagger.json) is the OpenAPI 3.1 document,
|
||||||
|
generated from the route table; the daemon serves it at `GET /openapi.json`.
|
||||||
|
|
||||||
## Configuration
|
## Configuration
|
||||||
|
|
||||||
@@ -251,6 +253,7 @@ make check # the CI gate, below
|
|||||||
make build # bin/uberbringer
|
make build # bin/uberbringer
|
||||||
make fmt # gofmt + goimports
|
make fmt # gofmt + goimports
|
||||||
make vuln # govulncheck
|
make vuln # govulncheck
|
||||||
|
make openapi # regenerate docs/swagger.json (go generate ./...)
|
||||||
make snapshot # release archives in dist/; publishes nothing
|
make snapshot # release archives in dist/; publishes nothing
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -261,14 +264,24 @@ order:
|
|||||||
2. `tidy-check`: `go mod tidy -diff`.
|
2. `tidy-check`: `go mod tidy -diff`.
|
||||||
3. `go vet`.
|
3. `go vet`.
|
||||||
4. staticcheck.
|
4. staticcheck.
|
||||||
5. `go test -race -timeout 5m`.
|
5. `openapi-check`: `go generate ./...` must leave `docs/swagger.json`
|
||||||
6. `release-check`: `goreleaser check`, which validates the release config
|
unchanged.
|
||||||
|
6. `go test -race -timeout 5m`.
|
||||||
|
7. `release-check`: `goreleaser check`, which validates the release config
|
||||||
without building.
|
without building.
|
||||||
|
|
||||||
It needs goreleaser installed. govulncheck is not part of it; run
|
It needs goreleaser installed. govulncheck is not part of it; run
|
||||||
`make vuln`. `make snapshot` builds the release archives locally; run it after
|
`make vuln`. `make snapshot` builds the release archives locally; run it
|
||||||
changing `.goreleaser.yaml` or `packaging/`. `make` builds report the version without the leading `v`, e.g.
|
after changing `.goreleaser.yaml` or `packaging/`. `make` builds report the
|
||||||
`0.1.2-3-gabc1234`, as release binaries do.
|
version without the leading `v`, e.g. `0.1.2-3-gabc1234`, as release
|
||||||
|
binaries do.
|
||||||
|
|
||||||
|
`docs/swagger.json` is generated by `tools/genopenapi` from the route table
|
||||||
|
in `internal/app/uberbringer/server/routes.go`, which the server also
|
||||||
|
registers its routes from. The schemas come from the Go types the routes
|
||||||
|
name: their `json` and `jsonschema` tags and their doc comments. Never edit
|
||||||
|
the file by hand: change the route table or the types, run
|
||||||
|
`go generate ./...`, and commit the document with the change.
|
||||||
|
|
||||||
The linters are pinned as Go tools in `go.mod`, so `go tool staticcheck`,
|
The linters are pinned as Go tools in `go.mod`, so `go tool staticcheck`,
|
||||||
`go tool govulncheck` and `go tool goimports` need no separate install. The
|
`go tool govulncheck` and `go tool goimports` need no separate install. The
|
||||||
@@ -289,7 +302,8 @@ internal/pkg/printqueue/ Job queue, worker and status history
|
|||||||
configs/ Example configuration
|
configs/ Example configuration
|
||||||
examples/ Example jobs, such as the block calibration receipt
|
examples/ Example jobs, such as the block calibration receipt
|
||||||
packaging/ systemd unit
|
packaging/ systemd unit
|
||||||
docs/ Design notes and feature plans
|
tools/genopenapi/ Generates docs/swagger.json from the route table
|
||||||
|
docs/ API reference, OpenAPI document, design notes and feature plans
|
||||||
```
|
```
|
||||||
|
|
||||||
[docs/design.md](docs/design.md) explains why the daemon is shaped as it is.
|
[docs/design.md](docs/design.md) explains why the daemon is shaped as it is.
|
||||||
@@ -300,9 +314,10 @@ docs/ Design notes and feature plans
|
|||||||
CI runs on the Gitea runner from `.gitea/workflows/`. The repository has no
|
CI runs on the Gitea runner from `.gitea/workflows/`. The repository has no
|
||||||
`.github/` directory.
|
`.github/` directory.
|
||||||
|
|
||||||
- `test.yml` runs the `make check` gate on every branch push. It lints, tests
|
- `test.yml` runs the `make check` gate on every branch push. It lints,
|
||||||
and validates the release config, but builds no binaries, and it does not
|
checks that `docs/swagger.json` is up to date, tests and validates the
|
||||||
run on pull requests or tags. Binaries are built only by `release.yml`.
|
release config, but builds no binaries, and it does not run on pull
|
||||||
|
requests or tags. Binaries are built only by `release.yml`.
|
||||||
- `security.yml` runs govulncheck on pushes to main and every Monday at
|
- `security.yml` runs govulncheck on pushes to main and every Monday at
|
||||||
06:00 UTC. Scheduled runs use main's copy of the workflow.
|
06:00 UTC. Scheduled runs use main's copy of the workflow.
|
||||||
- `release.yml` builds and publishes a release with goreleaser 2.20.3 when a
|
- `release.yml` builds and publishes a release with goreleaser 2.20.3 when a
|
||||||
@@ -311,8 +326,8 @@ CI runs on the Gitea runner from `.gitea/workflows/`. The repository has no
|
|||||||
- `vX.Y.Z-rc.N` tags are published as prereleases, so they never become the
|
- `vX.Y.Z-rc.N` tags are published as prereleases, so they never become the
|
||||||
latest release that `install.sh` installs.
|
latest release that `install.sh` installs.
|
||||||
- Each archive holds the binary, `LICENSE.txt`, `README.md`,
|
- Each archive holds the binary, `LICENSE.txt`, `README.md`,
|
||||||
`docs/api.md`, `CHANGELOG.md`, `configs/config.example.toml` and
|
`docs/api.md`, `docs/swagger.json`, `CHANGELOG.md`,
|
||||||
`packaging/uberbringer.service`.
|
`configs/config.example.toml` and `packaging/uberbringer.service`.
|
||||||
- The release notes link to `CHANGELOG.md` at the tag.
|
- The release notes link to `CHANGELOG.md` at the tag.
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|||||||
+10
@@ -32,8 +32,18 @@ included, carry `Cache-Control: no-store`.
|
|||||||
| POST | `/api/v1/preview` | Show the lines a job prints, without printing it |
|
| POST | `/api/v1/preview` | Show the lines a job prints, without printing it |
|
||||||
| GET | `/api/v1/jobs/:id` | Job status |
|
| GET | `/api/v1/jobs/:id` | Job status |
|
||||||
| GET | `/healthz` | Printer and queue health (no auth) |
|
| GET | `/healthz` | Printer and queue health (no auth) |
|
||||||
|
| GET | `/openapi.json` | This API's OpenAPI 3.1 document (no auth) |
|
||||||
| GET | `/` | Version information (no auth) |
|
| GET | `/` | Version information (no auth) |
|
||||||
|
|
||||||
|
[docs/swagger.json](swagger.json) is the API's OpenAPI 3.1 document:
|
||||||
|
every route, its parameters, its responses and the codes it and its
|
||||||
|
middleware answer with, and the schemas of the job and of every response.
|
||||||
|
The codes the HTTP server itself can send for any request are listed once,
|
||||||
|
in its description. It is generated from the server's route table and the
|
||||||
|
Go types behind it, and the daemon serves the copy built into it at
|
||||||
|
`GET /openapi.json`. Its enums list the canonical spellings; the server
|
||||||
|
also accepts other letter case and a few aliases, such as `centre`.
|
||||||
|
|
||||||
### Print a receipt
|
### Print a receipt
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
|
|||||||
@@ -113,6 +113,17 @@ client ─HTTPS─▶ Caddy ─▶ server ── validate ──▶ printqueue (
|
|||||||
`error` is for people. A refusal is answered and never logged as a failure.
|
`error` is for people. A refusal is answered and never logged as a failure.
|
||||||
An unexpected error or panic is logged once and reported to Sentry once,
|
An unexpected error or panic is logged once and reported to Sentry once,
|
||||||
without the body or the `Authorization` header.
|
without the body or the `Authorization` header.
|
||||||
|
- **The OpenAPI document is generated (owner, 2026-11-30).** One route
|
||||||
|
table drives both the server's routes and `docs/swagger.json`, so the
|
||||||
|
document cannot describe a route the server lacks. Schemas come from the
|
||||||
|
Go types by reflection, descriptions from the first paragraph of their doc
|
||||||
|
comments, and enums and limits from `jsonschema` tags. Tests hold the tags
|
||||||
|
to validation and to the values the handlers send; the enums list the
|
||||||
|
canonical spellings, while validation also takes other letter case and a
|
||||||
|
few aliases. Request schemas are strict, as the decoder is; response
|
||||||
|
schemas allow fields added later. Nothing in the document is written by
|
||||||
|
hand. The server gets the document in its config, so the generator does
|
||||||
|
not build the package that embeds its own output.
|
||||||
- **What stays compatible with 0.1.** The endpoint, the HS256 tokens and the
|
- **What stays compatible with 0.1.** The endpoint, the HS256 tokens and the
|
||||||
config keys stay as they were. The 0.1 body and its plain-text answer do
|
config keys stay as they were. The 0.1 body and its plain-text answer do
|
||||||
not. A 0.1 body gets a `400` that points to the element format in
|
not. A 0.1 body gets a `400` that points to the element format in
|
||||||
|
|||||||
@@ -0,0 +1,13 @@
|
|||||||
|
// Package docs embeds swagger.json, the OpenAPI document of Überbringer's
|
||||||
|
// HTTP API, which tools/genopenapi writes into this directory from the route
|
||||||
|
// table, so the daemon serves the document of the build it runs.
|
||||||
|
package docs
|
||||||
|
|
||||||
|
import _ "embed"
|
||||||
|
|
||||||
|
//go:embed swagger.json
|
||||||
|
var openAPI []byte
|
||||||
|
|
||||||
|
// OpenAPI returns the HTTP API's OpenAPI 3.1 document. The caller must not
|
||||||
|
// modify it.
|
||||||
|
func OpenAPI() []byte { return openAPI }
|
||||||
+1207
File diff suppressed because it is too large.
Load diff
@@ -7,6 +7,7 @@ require (
|
|||||||
github.com/go-viper/mapstructure/v2 v2.5.0
|
github.com/go-viper/mapstructure/v2 v2.5.0
|
||||||
github.com/gofiber/fiber/v3 v3.7.0
|
github.com/gofiber/fiber/v3 v3.7.0
|
||||||
github.com/golang-jwt/jwt/v5 v5.3.1
|
github.com/golang-jwt/jwt/v5 v5.3.1
|
||||||
|
github.com/invopop/jsonschema v0.14.0
|
||||||
github.com/liamg/tml v0.7.1
|
github.com/liamg/tml v0.7.1
|
||||||
github.com/pelletier/go-toml/v2 v2.4.3
|
github.com/pelletier/go-toml/v2 v2.4.3
|
||||||
github.com/spf13/cobra v1.10.2
|
github.com/spf13/cobra v1.10.2
|
||||||
@@ -19,6 +20,8 @@ require (
|
|||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/BurntSushi/toml v1.6.0 // indirect
|
github.com/BurntSushi/toml v1.6.0 // indirect
|
||||||
|
github.com/bahlo/generic-list-go v0.2.0 // indirect
|
||||||
|
github.com/buger/jsonparser v1.6.1 // indirect
|
||||||
github.com/fsnotify/fsnotify v1.9.0 // indirect
|
github.com/fsnotify/fsnotify v1.9.0 // indirect
|
||||||
github.com/gofiber/schema v1.10.2 // indirect
|
github.com/gofiber/schema v1.10.2 // indirect
|
||||||
github.com/gofiber/utils/v2 v2.6.5 // indirect
|
github.com/gofiber/utils/v2 v2.6.5 // indirect
|
||||||
@@ -29,6 +32,8 @@ require (
|
|||||||
github.com/mattn/go-colorable v0.1.16 // indirect
|
github.com/mattn/go-colorable v0.1.16 // indirect
|
||||||
github.com/mattn/go-isatty v0.0.24 // indirect
|
github.com/mattn/go-isatty v0.0.24 // indirect
|
||||||
github.com/molecule-man/go-brrr v1.3.1 // indirect
|
github.com/molecule-man/go-brrr v1.3.1 // indirect
|
||||||
|
github.com/pb33f/go-yaml v0.2.0 // indirect
|
||||||
|
github.com/pb33f/ordered-map/v2 v2.3.2 // indirect
|
||||||
github.com/philhofer/fwd v1.2.1 // indirect
|
github.com/philhofer/fwd v1.2.1 // indirect
|
||||||
github.com/sagikazarmark/locafero v0.11.0 // indirect
|
github.com/sagikazarmark/locafero v0.11.0 // indirect
|
||||||
github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 // indirect
|
github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 // indirect
|
||||||
|
|||||||
@@ -1,5 +1,9 @@
|
|||||||
github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk=
|
github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk=
|
||||||
github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
|
github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
|
||||||
|
github.com/bahlo/generic-list-go v0.2.0 h1:5sz/EEAK+ls5wF+NeqDpk5+iNdMDXrh3z3nPnH1Wvgk=
|
||||||
|
github.com/bahlo/generic-list-go v0.2.0/go.mod h1:2KvAjgMlE5NNynlg/5iLrrCCZ2+5xWbdbCW3pNTGyYg=
|
||||||
|
github.com/buger/jsonparser v1.6.1 h1:I0phFv0PlbLHnM7TZAVjZ2MJ2/eWRTDyuO7GLR98IEs=
|
||||||
|
github.com/buger/jsonparser v1.6.1/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0=
|
||||||
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
|
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
|
||||||
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
|
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
|
||||||
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
|
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
|
||||||
@@ -33,6 +37,8 @@ github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
|||||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||||
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
|
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
|
||||||
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
|
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
|
||||||
|
github.com/invopop/jsonschema v0.14.0 h1:MHQqLhvpNUZfw+hM3AZDYK7jxO8FZoQeQM77g8iyZjg=
|
||||||
|
github.com/invopop/jsonschema v0.14.0/go.mod h1:ygm6C2EaVNMBDPpaPlnOA2pFAxBnxGjFlMZABxm9n2I=
|
||||||
github.com/klauspost/compress v1.20.5 h1:rJj5VjH4xQxbnLphg6eqUcDxRFCw1jpMdDY9qXlrwSs=
|
github.com/klauspost/compress v1.20.5 h1:rJj5VjH4xQxbnLphg6eqUcDxRFCw1jpMdDY9qXlrwSs=
|
||||||
github.com/klauspost/compress v1.20.5/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
|
github.com/klauspost/compress v1.20.5/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
|
||||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||||
@@ -47,6 +53,10 @@ github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsRe
|
|||||||
github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=
|
github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=
|
||||||
github.com/molecule-man/go-brrr v1.3.1 h1:EwaJUzRIlp/dFmIpzq4J17CA5Zi5OHo2vOGmu09hF1w=
|
github.com/molecule-man/go-brrr v1.3.1 h1:EwaJUzRIlp/dFmIpzq4J17CA5Zi5OHo2vOGmu09hF1w=
|
||||||
github.com/molecule-man/go-brrr v1.3.1/go.mod h1:7ybW6/7gA3oKY45jOfVNjSJDtrr6ea4tzbsTkjmQDC4=
|
github.com/molecule-man/go-brrr v1.3.1/go.mod h1:7ybW6/7gA3oKY45jOfVNjSJDtrr6ea4tzbsTkjmQDC4=
|
||||||
|
github.com/pb33f/go-yaml v0.2.0 h1:t9fYMVk2BGlBIu6L07gryB+gOWt8rjEJO7e/jdBSqCo=
|
||||||
|
github.com/pb33f/go-yaml v0.2.0/go.mod h1:QvWdkHP5VjFYAeHMQUkaPQqREaQnBNOXmWzAjNrnSdo=
|
||||||
|
github.com/pb33f/ordered-map/v2 v2.3.2 h1:wDyaZ2Pv9QLh64X4utCeD5Zoi9nIv2aW3lwv172O5PQ=
|
||||||
|
github.com/pb33f/ordered-map/v2 v2.3.2/go.mod h1:1OhFrXu3OYw3kM+FXF+Ug3ugmmZ9LE8z0JfQMLvtV0w=
|
||||||
github.com/pelletier/go-toml/v2 v2.4.3 h1:GTRvJQutkOSftxIFD5xw9aepkYNuPWmVJpffdDPYVpY=
|
github.com/pelletier/go-toml/v2 v2.4.3 h1:GTRvJQutkOSftxIFD5xw9aepkYNuPWmVJpffdDPYVpY=
|
||||||
github.com/pelletier/go-toml/v2 v2.4.3/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
|
github.com/pelletier/go-toml/v2 v2.4.3/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
|
||||||
github.com/philhofer/fwd v1.2.1 h1:UtpS73q8bFgy/yH3gCq8LSNvj5gv/FowNOiWZa7uKwQ=
|
github.com/philhofer/fwd v1.2.1 h1:UtpS73q8bFgy/yH3gCq8LSNvj5gv/FowNOiWZa7uKwQ=
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ import (
|
|||||||
"go.jetify.com/typeid"
|
"go.jetify.com/typeid"
|
||||||
"golang.org/x/sync/errgroup"
|
"golang.org/x/sync/errgroup"
|
||||||
|
|
||||||
|
"uberbringer/docs"
|
||||||
"uberbringer/internal/app/uberbringer/server"
|
"uberbringer/internal/app/uberbringer/server"
|
||||||
"uberbringer/internal/pkg/config"
|
"uberbringer/internal/pkg/config"
|
||||||
"uberbringer/internal/pkg/escpos"
|
"uberbringer/internal/pkg/escpos"
|
||||||
@@ -97,6 +98,7 @@ func run(ctx context.Context, cfg *config.Config, build BuildInfo, out io.Writer
|
|||||||
WriteTimeout: cfg.WebServer.WriteTimeout,
|
WriteTimeout: cfg.WebServer.WriteTimeout,
|
||||||
IdleTimeout: cfg.WebServer.IdleTimeout,
|
IdleTimeout: cfg.WebServer.IdleTimeout,
|
||||||
RequestID: newRequestID,
|
RequestID: newRequestID,
|
||||||
|
OpenAPI: docs.OpenAPI(),
|
||||||
}, server.Deps{Jobs: queue, Printer: printerClient, Previewer: renderer}, logger)
|
}, server.Deps{Jobs: queue, Printer: printerClient, Previewer: renderer}, logger)
|
||||||
|
|
||||||
addr := net.JoinHostPort(cfg.WebServer.BindIP, strconv.Itoa(cfg.WebServer.Port))
|
addr := net.JoinHostPort(cfg.WebServer.BindIP, strconv.Itoa(cfg.WebServer.Port))
|
||||||
|
|||||||
@@ -79,8 +79,12 @@ func (e *apiError) Error() string { return e.message }
|
|||||||
|
|
||||||
// errorResponse is the JSON body of every error.
|
// errorResponse is the JSON body of every error.
|
||||||
type errorResponse struct {
|
type errorResponse struct {
|
||||||
Error string `json:"error"`
|
// Error says what went wrong, for people. It may change.
|
||||||
Code string `json:"code"`
|
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 []string `json:"details,omitempty"`
|
Details []string `json:"details,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -19,21 +19,47 @@ import (
|
|||||||
// healthTimeout bounds the printer status check behind /healthz.
|
// healthTimeout bounds the printer status check behind /healthz.
|
||||||
const healthTimeout = 3 * time.Second
|
const healthTimeout = 3 * time.Second
|
||||||
|
|
||||||
|
// indexResponse describes the running build.
|
||||||
|
type indexResponse struct {
|
||||||
|
// Project is the project's name.
|
||||||
|
Project string `json:"Project"`
|
||||||
|
// Description says what the daemon does.
|
||||||
|
Description string `json:"Description"`
|
||||||
|
// Authors is where the project lives.
|
||||||
|
Authors string `json:"Authors"`
|
||||||
|
// Version is the release, e.g. 0.2.0, or dev for a local build.
|
||||||
|
Version string `json:"Version"`
|
||||||
|
// Build is the commit the binary was built from.
|
||||||
|
Build string `json:"Build"`
|
||||||
|
}
|
||||||
|
|
||||||
func (s *Server) handleIndex(c fiber.Ctx) error {
|
func (s *Server) handleIndex(c fiber.Ctx) error {
|
||||||
info := s.config.Info
|
return c.JSON(indexResponse(s.config.Info))
|
||||||
return c.JSON(fiber.Map{
|
|
||||||
"Project": info.Project,
|
|
||||||
"Description": info.Description,
|
|
||||||
"Authors": info.Authors,
|
|
||||||
"Version": info.Version,
|
|
||||||
"Build": info.Build,
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func handleRobots(c fiber.Ctx) error {
|
func handleRobots(c fiber.Ctx) error {
|
||||||
return c.SendString("User-agent: *\nDisallow:\n")
|
return c.SendString("User-agent: *\nDisallow:\n")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// openAPIDocument is the body of GET /openapi.json: this API's OpenAPI 3.1
|
||||||
|
// document, generated from the route table.
|
||||||
|
type openAPIDocument struct {
|
||||||
|
// OpenAPI is the OpenAPI version the document follows.
|
||||||
|
OpenAPI string `json:"openapi"`
|
||||||
|
// Info names the API and its version.
|
||||||
|
Info map[string]any `json:"info"`
|
||||||
|
// Paths are the routes.
|
||||||
|
Paths map[string]any `json:"paths"`
|
||||||
|
// Components holds the schemas of the request and response bodies.
|
||||||
|
Components map[string]any `json:"components"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// handleOpenAPI answers with the configured OpenAPI document.
|
||||||
|
func (s *Server) handleOpenAPI(c fiber.Ctx) error {
|
||||||
|
c.Set(fiber.HeaderContentType, mediaJSON)
|
||||||
|
return c.Send(s.config.OpenAPI)
|
||||||
|
}
|
||||||
|
|
||||||
// handlePrint validates and queues a job.
|
// handlePrint validates and queues a job.
|
||||||
func (s *Server) handlePrint(c fiber.Ctx) error {
|
func (s *Server) handlePrint(c fiber.Ctx) error {
|
||||||
job, err := decodeValidJob(c.Body())
|
job, err := decodeValidJob(c.Body())
|
||||||
@@ -121,21 +147,40 @@ func (s *Server) handleJob(c fiber.Ctx) error {
|
|||||||
|
|
||||||
// printerHealth is the printer part of the /healthz response.
|
// printerHealth is the printer part of the /healthz response.
|
||||||
type printerHealth struct {
|
type printerHealth struct {
|
||||||
// Reachable is omitted when it is unknown, e.g. after a timeout.
|
// Reachable is whether the printer accepted a connection; it is omitted
|
||||||
Reachable *bool `json:"reachable,omitempty"`
|
// when that is unknown, e.g. after a timeout.
|
||||||
Status string `json:"status"`
|
Reachable *bool `json:"reachable,omitempty"`
|
||||||
Online *bool `json:"online,omitempty"`
|
// Status is ready, not_ready, unknown for a printer that does not
|
||||||
CoverOpen *bool `json:"cover_open,omitempty"`
|
// answer status requests, unreachable, or timeout when the status read
|
||||||
Paper string `json:"paper,omitempty"`
|
// ran out of time.
|
||||||
Error string `json:"error,omitempty"`
|
Status string `json:"status" jsonschema:"enum=ready,enum=not_ready,enum=unknown,enum=unreachable,enum=timeout"`
|
||||||
|
// Online is whether the printer reports itself online.
|
||||||
|
Online *bool `json:"online,omitempty"`
|
||||||
|
// CoverOpen is reported only while the printer is offline: Epson
|
||||||
|
// printers go offline when the cover opens.
|
||||||
|
CoverOpen *bool `json:"cover_open,omitempty"`
|
||||||
|
// Paper is ok, near_end or out.
|
||||||
|
Paper string `json:"paper,omitempty" jsonschema:"enum=ok,enum=near_end,enum=out"`
|
||||||
|
// Error is set when the printer reports an error, such as a cutter
|
||||||
|
// error.
|
||||||
|
Error string `json:"error,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// healthResponse is the body of GET /healthz.
|
||||||
type healthResponse struct {
|
type healthResponse struct {
|
||||||
Status string `json:"status"`
|
// Status is ok, degraded when the printer is not ready, or unavailable
|
||||||
|
// when it is unreachable or did not answer in time.
|
||||||
|
Status string `json:"status" jsonschema:"enum=ok,enum=degraded,enum=unavailable"`
|
||||||
|
// Printer is the printer's state.
|
||||||
Printer printerHealth `json:"printer"`
|
Printer printerHealth `json:"printer"`
|
||||||
Queue struct {
|
// Queue is the print queue's state.
|
||||||
Pending int `json:"pending"`
|
Queue queueHealth `json:"queue"`
|
||||||
} `json:"queue"`
|
}
|
||||||
|
|
||||||
|
// queueHealth is the queue part of the /healthz response.
|
||||||
|
type queueHealth struct {
|
||||||
|
// Pending is how many jobs wait to be printed.
|
||||||
|
Pending int `json:"pending"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// handleHealth reports whether the printer is reachable and ready. It
|
// handleHealth reports whether the printer is reachable and ready. It
|
||||||
|
|||||||
@@ -41,31 +41,54 @@ func (s *Server) handlePreview(c fiber.Ctx) error {
|
|||||||
|
|
||||||
// previewResponse is the JSON form of a preview.
|
// previewResponse is the JSON form of a preview.
|
||||||
type previewResponse struct {
|
type previewResponse struct {
|
||||||
Columns int `json:"columns"`
|
// Columns is the number of Font A characters per line.
|
||||||
CodePage string `json:"codepage"`
|
Columns int `json:"columns"`
|
||||||
LineCount int `json:"line_count"`
|
// CodePage is the code page text is printed in.
|
||||||
Lines []previewLine `json:"lines"`
|
CodePage string `json:"codepage"`
|
||||||
Warnings []string `json:"warnings"`
|
// LineCount is the lines the receipt prints, all copies counted: text
|
||||||
|
// lines, fed lines, and one for each QR code, barcode and image.
|
||||||
|
LineCount int `json:"line_count"`
|
||||||
|
// Lines are the lines as they print, in order.
|
||||||
|
Lines []previewLine `json:"lines"`
|
||||||
|
// Warnings name the elements with characters the code page lacks, and
|
||||||
|
// images wider than the paper.
|
||||||
|
Warnings []string `json:"warnings"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// previewLine is one line of a preview.
|
||||||
type previewLine struct {
|
type previewLine struct {
|
||||||
Kind string `json:"kind"`
|
// Kind is what printed the line.
|
||||||
Text string `json:"text"`
|
Kind string `json:"kind" jsonschema:"enum=text,enum=qr,enum=barcode,enum=image,enum=raw,enum=cut"`
|
||||||
|
// Text is the line as it prints, or a placeholder such as
|
||||||
|
// [qr: https://example.com].
|
||||||
|
Text string `json:"text"`
|
||||||
|
// Runs are the styled parts of text. Plain Font A text at size 1 has
|
||||||
|
// none.
|
||||||
Runs []previewRun `json:"runs,omitempty"`
|
Runs []previewRun `json:"runs,omitempty"`
|
||||||
Data string `json:"data,omitempty"`
|
// Data is the QR code or barcode data, the image URL (or base64), the
|
||||||
|
// number of raw bytes, or the cut mode.
|
||||||
|
Data string `json:"data,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// previewRun is a styled range of a line's text, in characters [from, to).
|
// previewRun is a styled range of a line's text, in characters [from, to).
|
||||||
// Width and height are omitted at scale 1, font when it is a.
|
// Width and height are omitted at scale 1, font when it is a.
|
||||||
type previewRun struct {
|
type previewRun struct {
|
||||||
From int `json:"from"`
|
// From is the first character of the run.
|
||||||
To int `json:"to"`
|
From int `json:"from"`
|
||||||
Bold bool `json:"bold,omitempty"`
|
// To is the character after the run.
|
||||||
Underline int `json:"underline,omitempty"`
|
To int `json:"to"`
|
||||||
Invert bool `json:"invert,omitempty"`
|
// Bold is set for bold text.
|
||||||
Font string `json:"font,omitempty"`
|
Bold bool `json:"bold,omitempty"`
|
||||||
Width int `json:"width,omitempty"`
|
// Underline is 1 for a thin and 2 for a thick underline.
|
||||||
Height int `json:"height,omitempty"`
|
Underline int `json:"underline,omitempty" jsonschema:"enum=1,enum=2"`
|
||||||
|
// Invert is set for white on black.
|
||||||
|
Invert bool `json:"invert,omitempty"`
|
||||||
|
// Font is b for the smaller font.
|
||||||
|
Font string `json:"font,omitempty" jsonschema:"enum=b"`
|
||||||
|
// Width is the character width multiplier, when it is not 1.
|
||||||
|
Width int `json:"width,omitempty"`
|
||||||
|
// Height is the character height multiplier, when it is not 1.
|
||||||
|
Height int `json:"height,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func newPreviewResponse(p receipt.Preview) previewResponse {
|
func newPreviewResponse(p receipt.Preview) previewResponse {
|
||||||
|
|||||||
@@ -0,0 +1,259 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"regexp"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/gofiber/fiber/v3"
|
||||||
|
|
||||||
|
"uberbringer/internal/pkg/printqueue"
|
||||||
|
"uberbringer/internal/pkg/receipt"
|
||||||
|
)
|
||||||
|
|
||||||
|
// BasePath prefixes the routes that need a bearer token.
|
||||||
|
const BasePath = "/api/v1"
|
||||||
|
|
||||||
|
// Media types the routes answer with.
|
||||||
|
const (
|
||||||
|
mediaJSON = fiber.MIMEApplicationJSON
|
||||||
|
mediaText = fiber.MIMETextPlainCharsetUTF8
|
||||||
|
)
|
||||||
|
|
||||||
|
// Route is one route of the HTTP API. The server registers it from this
|
||||||
|
// table and tools/genopenapi documents it in docs/swagger.json, so the two
|
||||||
|
// cannot differ.
|
||||||
|
type Route struct {
|
||||||
|
Method string
|
||||||
|
// Path is in OpenAPI form, e.g. /api/v1/jobs/{id}.
|
||||||
|
Path string
|
||||||
|
OperationID string
|
||||||
|
Summary string
|
||||||
|
Description string
|
||||||
|
Tag string
|
||||||
|
// Auth routes are under BasePath: they need a bearer token, are rate
|
||||||
|
// limited per client and answer with Cache-Control: no-store.
|
||||||
|
Auth bool
|
||||||
|
// NoStore adds Cache-Control: no-store to a route without Auth.
|
||||||
|
NoStore bool
|
||||||
|
// Request is the zero value of the JSON request body's type, or nil.
|
||||||
|
Request any
|
||||||
|
// Params are the route's path, query and header parameters.
|
||||||
|
Params []Param
|
||||||
|
Responses []Response
|
||||||
|
|
||||||
|
// errors are the codes the handler answers with itself;
|
||||||
|
// DocumentedErrors adds those of the middleware.
|
||||||
|
errors []errorCode
|
||||||
|
handle func(*Server, fiber.Ctx) error
|
||||||
|
}
|
||||||
|
|
||||||
|
// Response is one documented answer of a route that is not an error.
|
||||||
|
type Response struct {
|
||||||
|
Status int
|
||||||
|
Description string
|
||||||
|
// Content lists the bodies by media type; none for an empty answer.
|
||||||
|
Content []Content
|
||||||
|
// Headers are the headers it carries besides Content-Type.
|
||||||
|
Headers []Header
|
||||||
|
}
|
||||||
|
|
||||||
|
// Content is a response body in one media type.
|
||||||
|
type Content struct {
|
||||||
|
MediaType string
|
||||||
|
// Body is the zero value of the body's type; a string is a text body.
|
||||||
|
Body any
|
||||||
|
}
|
||||||
|
|
||||||
|
// Header is a response header a route documents.
|
||||||
|
type Header struct {
|
||||||
|
Name string
|
||||||
|
Description string
|
||||||
|
// Integer headers carry a whole number, the rest a string.
|
||||||
|
Integer bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// Param is a path, query or header parameter of a route.
|
||||||
|
type Param struct {
|
||||||
|
Name string
|
||||||
|
// In is "path", "query" or "header".
|
||||||
|
In string
|
||||||
|
Description string
|
||||||
|
Required bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// ErrorDoc is an error code a route can answer with.
|
||||||
|
type ErrorDoc struct {
|
||||||
|
Status int
|
||||||
|
Code string
|
||||||
|
Message string
|
||||||
|
}
|
||||||
|
|
||||||
|
// ErrorBody returns the zero value of the body every error answers with.
|
||||||
|
func ErrorBody() any { return errorResponse{} }
|
||||||
|
|
||||||
|
// DocumentedErrors returns the codes the route can answer with: its own and
|
||||||
|
// those of the middleware it runs behind.
|
||||||
|
func (r Route) DocumentedErrors() []ErrorDoc {
|
||||||
|
codes := append([]errorCode(nil), r.errors...)
|
||||||
|
if r.Request != nil {
|
||||||
|
codes = append(codes, codeBodyTooLarge)
|
||||||
|
}
|
||||||
|
if r.Auth {
|
||||||
|
codes = append(codes, codeUnauthorized, codeRateLimited)
|
||||||
|
}
|
||||||
|
codes = append(codes, codeInternal)
|
||||||
|
return errorDocs(codes)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ServerErrors returns the codes the HTTP server itself can answer any
|
||||||
|
// request with: for a malformed or slow request, for an unknown route or
|
||||||
|
// method, and for an unsupported transfer coding.
|
||||||
|
func ServerErrors() []ErrorDoc {
|
||||||
|
return errorDocs([]errorCode{codeBadRequest, codeNotFound, codeMethodNotAllowed, codeRequestTimeout,
|
||||||
|
codeHeadersTooLarge, codeNotImplemented})
|
||||||
|
}
|
||||||
|
|
||||||
|
func errorDocs(codes []errorCode) []ErrorDoc {
|
||||||
|
docs := make([]ErrorDoc, len(codes))
|
||||||
|
for i, c := range codes {
|
||||||
|
docs[i] = ErrorDoc{Status: c.status, Code: c.code, Message: c.message}
|
||||||
|
}
|
||||||
|
return docs
|
||||||
|
}
|
||||||
|
|
||||||
|
// Routes returns the route table.
|
||||||
|
func Routes() []Route {
|
||||||
|
return []Route{
|
||||||
|
{
|
||||||
|
Method: http.MethodGet,
|
||||||
|
Path: "/",
|
||||||
|
OperationID: "getInfo",
|
||||||
|
Summary: "Version information",
|
||||||
|
Description: "The project's name, description and authors, and the version and build of the running daemon.",
|
||||||
|
Tag: "meta",
|
||||||
|
Responses: []Response{{Status: http.StatusOK, Description: "The running build",
|
||||||
|
Content: []Content{{MediaType: mediaJSON, Body: indexResponse{}}}}},
|
||||||
|
handle: (*Server).handleIndex,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Method: http.MethodGet,
|
||||||
|
Path: "/robots.txt",
|
||||||
|
OperationID: "getRobots",
|
||||||
|
Summary: "Robots exclusion file",
|
||||||
|
Tag: "meta",
|
||||||
|
Responses: []Response{{Status: http.StatusOK, Description: "A robots.txt that allows everything",
|
||||||
|
Content: []Content{{MediaType: mediaText, Body: ""}}}},
|
||||||
|
handle: func(_ *Server, c fiber.Ctx) error { return handleRobots(c) },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Method: http.MethodGet,
|
||||||
|
Path: "/openapi.json",
|
||||||
|
OperationID: "getOpenAPI",
|
||||||
|
Summary: "This API's OpenAPI document",
|
||||||
|
Description: "The OpenAPI 3.1 document of this API, generated from its route table, as the running " +
|
||||||
|
"build serves it.",
|
||||||
|
Tag: "meta",
|
||||||
|
Responses: []Response{{Status: http.StatusOK, Description: "The document",
|
||||||
|
Content: []Content{{MediaType: mediaJSON, Body: openAPIDocument{}}}}},
|
||||||
|
handle: (*Server).handleOpenAPI,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Method: http.MethodGet,
|
||||||
|
Path: "/healthz",
|
||||||
|
OperationID: "getHealth",
|
||||||
|
Summary: "Printer and queue health",
|
||||||
|
Description: "Reads the printer's real-time status. A printer that looks not ready is read again " +
|
||||||
|
"750 ms later, and only a problem that is still there gives 503. A printer that does not " +
|
||||||
|
"answer status requests is reported as status unknown with 200.",
|
||||||
|
Tag: "health",
|
||||||
|
NoStore: true,
|
||||||
|
Responses: []Response{
|
||||||
|
{Status: http.StatusOK, Description: "The printer is reachable and ready, or does not report status",
|
||||||
|
Content: []Content{{MediaType: mediaJSON, Body: healthResponse{}}}},
|
||||||
|
{Status: http.StatusServiceUnavailable, Description: "The printer is unreachable, not ready, " +
|
||||||
|
"or did not answer in time", Content: []Content{{MediaType: mediaJSON, Body: healthResponse{}}}},
|
||||||
|
},
|
||||||
|
handle: (*Server).handleHealth,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Method: http.MethodPost,
|
||||||
|
Path: BasePath + "/print",
|
||||||
|
OperationID: "printJob",
|
||||||
|
Summary: "Queue a print job",
|
||||||
|
Description: "Validates the whole job and queues it. The worker renders it in full before anything " +
|
||||||
|
"is sent to the printer, and fetches its images then, so a broken image URL shows up as a " +
|
||||||
|
"failed job.",
|
||||||
|
Tag: "print",
|
||||||
|
Auth: true,
|
||||||
|
Request: receipt.Job{},
|
||||||
|
Responses: []Response{{Status: http.StatusAccepted, Description: "The job is queued",
|
||||||
|
Content: []Content{{MediaType: mediaJSON, Body: printqueue.Status{}}},
|
||||||
|
Headers: []Header{{Name: fiber.HeaderLocation, Description: "The job's URL, which answers with " +
|
||||||
|
"its status."}}}},
|
||||||
|
errors: []errorCode{codeInvalidJob, codeQueueFull, codeShuttingDown},
|
||||||
|
handle: (*Server).handlePrint,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Method: http.MethodPost,
|
||||||
|
Path: BasePath + "/preview",
|
||||||
|
OperationID: "previewJob",
|
||||||
|
Summary: "Show the lines a job prints, without printing it",
|
||||||
|
Description: "Validates the job as /api/v1/print does, renders it and reads the lines back from " +
|
||||||
|
"the rendered bytes. It prints nothing and fetches no images. The answer is JSON with the " +
|
||||||
|
"lines' styles when the Accept header prefers application/json to text/plain (for example " +
|
||||||
|
"application/json or application/*), and plain text otherwise.",
|
||||||
|
Tag: "print",
|
||||||
|
Auth: true,
|
||||||
|
Request: receipt.Job{},
|
||||||
|
Responses: []Response{{Status: http.StatusOK, Description: "The lines the printer would print",
|
||||||
|
Content: []Content{
|
||||||
|
{MediaType: mediaText, Body: ""},
|
||||||
|
{MediaType: mediaJSON, Body: previewResponse{}},
|
||||||
|
}}},
|
||||||
|
errors: []errorCode{codeInvalidJob, codeTooManyLines},
|
||||||
|
handle: (*Server).handlePreview,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Method: http.MethodGet,
|
||||||
|
Path: BasePath + "/jobs/{id}",
|
||||||
|
OperationID: "getJob",
|
||||||
|
Summary: "Job status",
|
||||||
|
Description: "The status of a queued, printing or finished job. The last queue.history finished " +
|
||||||
|
"jobs are kept.",
|
||||||
|
Tag: "print",
|
||||||
|
Auth: true,
|
||||||
|
Params: []Param{{Name: "id", In: "path", Required: true, Description: "The job's ID, a job_ TypeID."}},
|
||||||
|
Responses: []Response{{Status: http.StatusOK, Description: "The job's status",
|
||||||
|
Content: []Content{{MediaType: mediaJSON, Body: printqueue.Status{}}}}},
|
||||||
|
errors: []errorCode{codeJobNotFound},
|
||||||
|
handle: (*Server).handleJob,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// pathParam finds the {name} parameters in a route path.
|
||||||
|
var pathParam = regexp.MustCompile(`\{([^/{}]+)\}`)
|
||||||
|
|
||||||
|
// fiberPath turns an OpenAPI path into Fiber's form: {id} becomes :id.
|
||||||
|
func fiberPath(path string) string {
|
||||||
|
return pathParam.ReplaceAllString(path, ":$1")
|
||||||
|
}
|
||||||
|
|
||||||
|
// registerRoutes adds every route of the table to the app. api is the group
|
||||||
|
// at BasePath that holds the bearer token, rate limit and no-store
|
||||||
|
// middleware.
|
||||||
|
func (s *Server) registerRoutes(api fiber.Router) {
|
||||||
|
for _, r := range Routes() {
|
||||||
|
handler := func(c fiber.Ctx) error { return r.handle(s, c) }
|
||||||
|
path := fiberPath(r.Path)
|
||||||
|
switch {
|
||||||
|
case r.Auth:
|
||||||
|
api.Add([]string{r.Method}, strings.TrimPrefix(path, BasePath), handler)
|
||||||
|
case r.NoStore:
|
||||||
|
s.app.Add([]string{r.Method}, path, noStore, handler)
|
||||||
|
default:
|
||||||
|
s.app.Add([]string{r.Method}, path, handler)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"uberbringer/docs"
|
||||||
|
)
|
||||||
|
|
||||||
|
// The route table is consistent: every route has a handler, a response and
|
||||||
|
// a unique operation ID, the routes that need a token are exactly those
|
||||||
|
// under BasePath, and every path parameter is declared.
|
||||||
|
func TestRouteTable(t *testing.T) {
|
||||||
|
ops := map[string]bool{}
|
||||||
|
routes := map[string]bool{}
|
||||||
|
for _, r := range Routes() {
|
||||||
|
key := r.Method + " " + r.Path
|
||||||
|
if routes[key] {
|
||||||
|
t.Errorf("%s is in the table twice", key)
|
||||||
|
}
|
||||||
|
routes[key] = true
|
||||||
|
if ops[r.OperationID] || r.OperationID == "" {
|
||||||
|
t.Errorf("%s: operation ID %q is empty or taken", key, r.OperationID)
|
||||||
|
}
|
||||||
|
ops[r.OperationID] = true
|
||||||
|
if r.handle == nil || len(r.Responses) == 0 || r.Summary == "" || r.Tag == "" {
|
||||||
|
t.Errorf("%s: needs a handler, a response, a summary and a tag", key)
|
||||||
|
}
|
||||||
|
if r.Auth != strings.HasPrefix(r.Path, BasePath+"/") {
|
||||||
|
t.Errorf("%s: Auth is %v, but the token is needed exactly under %s", key, r.Auth, BasePath)
|
||||||
|
}
|
||||||
|
if p := fiberPath(r.Path); strings.ContainsAny(p, "{}") {
|
||||||
|
t.Errorf("%s: Fiber path %s still has braces", key, p)
|
||||||
|
}
|
||||||
|
for _, m := range pathParam.FindAllStringSubmatch(r.Path, -1) {
|
||||||
|
declared := false
|
||||||
|
for _, p := range r.Params {
|
||||||
|
declared = declared || p.In == "path" && p.Name == m[1]
|
||||||
|
}
|
||||||
|
if !declared {
|
||||||
|
t.Errorf("%s: path parameter %s is not in Params", key, m[1])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The server registers exactly the routes of the table, so none can be
|
||||||
|
// added without being documented.
|
||||||
|
func TestRegisteredRoutesAreTheTable(t *testing.T) {
|
||||||
|
want := map[string]bool{}
|
||||||
|
for _, r := range Routes() {
|
||||||
|
want[r.Method+" "+fiberPath(r.Path)] = true
|
||||||
|
}
|
||||||
|
s := newTestServer(t, &fakeJobs{}, &fakePrinter{})
|
||||||
|
got := map[string]bool{}
|
||||||
|
for _, route := range s.app.GetRoutes(true) {
|
||||||
|
if route.Method != http.MethodHead {
|
||||||
|
got[route.Method+" "+route.Path] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for key := range got {
|
||||||
|
if !want[key] {
|
||||||
|
t.Errorf("%s is registered but not in Routes(): add it to the table in routes.go", key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for key := range want {
|
||||||
|
if !got[key] {
|
||||||
|
t.Errorf("%s is in Routes() but not registered", key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// GET /openapi.json answers, without a token, with the document embedded in
|
||||||
|
// the build.
|
||||||
|
func TestOpenAPIServesEmbeddedDocument(t *testing.T) {
|
||||||
|
s := newTestServer(t, &fakeJobs{}, &fakePrinter{}, func(c *Config) { c.OpenAPI = docs.OpenAPI() })
|
||||||
|
resp, body := send(t, s, httptest.NewRequest(http.MethodGet, "/openapi.json", nil))
|
||||||
|
if resp.StatusCode != http.StatusOK {
|
||||||
|
t.Fatalf("status %d: %s", resp.StatusCode, body)
|
||||||
|
}
|
||||||
|
if ct := resp.Header.Get("Content-Type"); !strings.HasPrefix(ct, "application/json") {
|
||||||
|
t.Errorf("Content-Type = %q", ct)
|
||||||
|
}
|
||||||
|
if !bytes.Equal(body, docs.OpenAPI()) {
|
||||||
|
t.Error("the body is not the embedded document")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFiberPath(t *testing.T) {
|
||||||
|
for in, want := range map[string]string{
|
||||||
|
BasePath + "/jobs/{id}": BasePath + "/jobs/:id",
|
||||||
|
BasePath + "/jobs/{job_id}/x/{n}": BasePath + "/jobs/:job_id/x/:n",
|
||||||
|
"/healthz": "/healthz",
|
||||||
|
} {
|
||||||
|
if got := fiberPath(in); got != want {
|
||||||
|
t.Errorf("fiberPath(%q) = %q, want %q", in, got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"go/ast"
|
||||||
|
"go/parser"
|
||||||
|
gotoken "go/token"
|
||||||
|
"maps"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"reflect"
|
||||||
|
"slices"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"uberbringer/internal/pkg/escpos"
|
||||||
|
"uberbringer/internal/pkg/printer"
|
||||||
|
)
|
||||||
|
|
||||||
|
// enumOf returns the enum values in the jsonschema tag of typ's field,
|
||||||
|
// sorted.
|
||||||
|
func enumOf(t *testing.T, typ reflect.Type, field string) []string {
|
||||||
|
t.Helper()
|
||||||
|
f, ok := typ.FieldByName(field)
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("%s has no field %s", typ.Name(), 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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
slices.Sort(values)
|
||||||
|
return values
|
||||||
|
}
|
||||||
|
|
||||||
|
// The kind enum of a preview line lists every line kind the interpreter
|
||||||
|
// produces.
|
||||||
|
func TestPreviewKindEnumListsEveryLineKind(t *testing.T) {
|
||||||
|
file, err := parser.ParseFile(gotoken.NewFileSet(), "../../../pkg/escpos/interpret.go", nil, 0)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var kinds []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, "Line") || i >= len(spec.Values) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if lit, ok := spec.Values[i].(*ast.BasicLit); ok && lit.Kind == gotoken.STRING {
|
||||||
|
v, _ := strconv.Unquote(lit.Value)
|
||||||
|
kinds = append(kinds, v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
slices.Sort(kinds)
|
||||||
|
if enum := enumOf(t, reflect.TypeFor[previewLine](), "Kind"); len(kinds) == 0 || !slices.Equal(kinds, enum) {
|
||||||
|
t.Errorf("previewLine.Kind enum %v, escpos Line constants %v", enum, kinds)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The enums of the /healthz body are exactly the values the handler sends
|
||||||
|
// over every printer state.
|
||||||
|
func TestHealthEnumsMatchHandler(t *testing.T) {
|
||||||
|
printers := []*fakePrinter{
|
||||||
|
{statuses: []escpos.Status{{Online: true}}},
|
||||||
|
{statuses: []escpos.Status{{Online: true, PaperNearEnd: true}}},
|
||||||
|
{statuses: []escpos.Status{{PaperOut: true}}},
|
||||||
|
{statuses: []escpos.Status{{CoverOpen: true}}},
|
||||||
|
{statuses: []escpos.Status{{CutterError: true}}},
|
||||||
|
{err: printer.ErrStatusUnsupported},
|
||||||
|
{err: errors.New("connection refused")},
|
||||||
|
{err: fmt.Errorf("reading printer status: %w", context.DeadlineExceeded)},
|
||||||
|
}
|
||||||
|
status, printerStatus, paper := map[string]bool{}, map[string]bool{}, map[string]bool{}
|
||||||
|
for _, p := range printers {
|
||||||
|
s := newTestServer(t, &fakeJobs{}, p)
|
||||||
|
_, body := send(t, s, httptest.NewRequest(http.MethodGet, "/healthz", nil))
|
||||||
|
var resp healthResponse
|
||||||
|
if err := json.Unmarshal(body, &resp); err != nil {
|
||||||
|
t.Fatalf("decoding %s: %v", body, err)
|
||||||
|
}
|
||||||
|
status[resp.Status] = true
|
||||||
|
printerStatus[resp.Printer.Status] = true
|
||||||
|
if resp.Printer.Paper != "" {
|
||||||
|
paper[resp.Printer.Paper] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, tt := range []struct {
|
||||||
|
typ reflect.Type
|
||||||
|
field string
|
||||||
|
seen map[string]bool
|
||||||
|
}{
|
||||||
|
{reflect.TypeFor[healthResponse](), "Status", status},
|
||||||
|
{reflect.TypeFor[printerHealth](), "Status", printerStatus},
|
||||||
|
{reflect.TypeFor[printerHealth](), "Paper", paper},
|
||||||
|
} {
|
||||||
|
seen := slices.Sorted(maps.Keys(tt.seen))
|
||||||
|
if enum := enumOf(t, tt.typ, tt.field); !slices.Equal(seen, enum) {
|
||||||
|
t.Errorf("%s.%s enum %v, the handler sends %v", tt.typ.Name(), tt.field, enum, seen)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -80,6 +80,10 @@ type Config struct {
|
|||||||
// RequestID generates request IDs.
|
// RequestID generates request IDs.
|
||||||
RequestID func() string
|
RequestID func() string
|
||||||
|
|
||||||
|
// OpenAPI is the API's OpenAPI document, which GET /openapi.json
|
||||||
|
// answers with.
|
||||||
|
OpenAPI []byte
|
||||||
|
|
||||||
// HealthRecheckDelay is how long /healthz waits before re-reading a
|
// HealthRecheckDelay is how long /healthz waits before re-reading a
|
||||||
// printer that looked not ready. Zero means defaultHealthRecheckDelay.
|
// printer that looked not ready. Zero means defaultHealthRecheckDelay.
|
||||||
HealthRecheckDelay time.Duration
|
HealthRecheckDelay time.Duration
|
||||||
@@ -140,11 +144,7 @@ func New(config Config, deps Deps, logger *slog.Logger) *Server {
|
|||||||
s.app.Use(requestid.New(requestid.Config{Generator: config.RequestID}))
|
s.app.Use(requestid.New(requestid.Config{Generator: config.RequestID}))
|
||||||
s.app.Use(compress.New(compress.Config{Level: compress.LevelBestSpeed}))
|
s.app.Use(compress.New(compress.Config{Level: compress.LevelBestSpeed}))
|
||||||
|
|
||||||
s.app.Get("/", s.handleIndex)
|
api := s.app.Group(BasePath,
|
||||||
s.app.Get("/robots.txt", handleRobots)
|
|
||||||
s.app.Get("/healthz", noStore, s.handleHealth)
|
|
||||||
|
|
||||||
api := s.app.Group("/api/v1",
|
|
||||||
noStore,
|
noStore,
|
||||||
limiter.New(limiter.Config{
|
limiter.New(limiter.Config{
|
||||||
Max: config.RateLimit,
|
Max: config.RateLimit,
|
||||||
@@ -154,9 +154,7 @@ func New(config Config, deps Deps, logger *slog.Logger) *Server {
|
|||||||
}),
|
}),
|
||||||
requireBearerToken(config.Secret),
|
requireBearerToken(config.Secret),
|
||||||
)
|
)
|
||||||
api.Post("/print", s.handlePrint)
|
s.registerRoutes(api)
|
||||||
api.Post("/preview", s.handlePreview)
|
|
||||||
api.Get("/jobs/:id", s.handleJob)
|
|
||||||
|
|
||||||
return s
|
return s
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -702,9 +702,10 @@ func TestRateLimitPerClientBehindProxy(t *testing.T) {
|
|||||||
func TestRoutesConform(t *testing.T) {
|
func TestRoutesConform(t *testing.T) {
|
||||||
id := newJobID(t)
|
id := newJobID(t)
|
||||||
public := map[string]bool{
|
public := map[string]bool{
|
||||||
"GET /": true,
|
"GET /": true,
|
||||||
"GET /robots.txt": true,
|
"GET /robots.txt": true,
|
||||||
"GET /healthz": true,
|
"GET /healthz": true,
|
||||||
|
"GET /openapi.json": true,
|
||||||
}
|
}
|
||||||
// Each authenticated route maps to a path that reaches it.
|
// Each authenticated route maps to a path that reaches it.
|
||||||
authenticated := map[string]string{
|
authenticated := map[string]string{
|
||||||
@@ -732,7 +733,7 @@ func TestRoutesConform(t *testing.T) {
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
default:
|
default:
|
||||||
t.Errorf("%s has no conformance case: add one here and a row to the API table in docs/api.md", key)
|
t.Errorf("%s has no conformance case: add it to the table in routes.go, a case here and a row to the API table in docs/api.md", key)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for key := range authenticated {
|
for key := range authenticated {
|
||||||
|
|||||||
@@ -61,12 +61,19 @@ const (
|
|||||||
|
|
||||||
// Status describes a job.
|
// Status describes a job.
|
||||||
type Status struct {
|
type Status struct {
|
||||||
ID JobID `json:"id"`
|
// ID identifies the job.
|
||||||
State State `json:"status"`
|
ID JobID `json:"id"`
|
||||||
Error string `json:"error,omitempty"`
|
// State is where the job is in its lifecycle.
|
||||||
Attempts int `json:"attempts,omitempty"`
|
State State `json:"status" jsonschema:"enum=queued,enum=printing,enum=done,enum=failed"`
|
||||||
CreatedAt time.Time `json:"created_at"`
|
// Error says why a failed job failed.
|
||||||
StartedAt *time.Time `json:"started_at,omitempty"`
|
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"`
|
FinishedAt *time.Time `json:"finished_at,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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
@@ -50,75 +50,133 @@ const (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// Job is a receipt to print.
|
// 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 {
|
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
|
// Copies is how many times the receipt is printed, each with its own
|
||||||
// cut. Zero means one.
|
// 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
|
// Element is one item on a receipt. Its type selects which fields apply. On
|
||||||
// blocks (box, rule and kv) and inside a box, a field that does not apply is
|
// the blocks (box, rule and kv) and inside a box, a field that does not
|
||||||
// an error; on the other types it is ignored, except for the block fields.
|
// apply is an error; on the other types it is ignored, except for the block
|
||||||
// Width and Height mean character multipliers for text, module width and
|
// fields. width and height mean character multipliers for text, module width
|
||||||
// bar height for barcodes, and target width in dots for images. A block's
|
// and bar height for barcodes, and target width in dots for images. A
|
||||||
// width is set by Columns, in characters of its own size and font, never by
|
// block's width is set by columns, in characters of its own size and font,
|
||||||
// Width; without Columns a block spans the line.
|
// 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 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 is a text element's UTF-8 text, a box's body or a rule's label.
|
||||||
Text string `json:"text,omitempty"`
|
// \n starts a new line.
|
||||||
Bold bool `json:"bold,omitempty"`
|
Text string `json:"text,omitempty"`
|
||||||
Size int `json:"size,omitempty"`
|
// Bold prints the text in bold: a box's text, a rule's label.
|
||||||
Width int `json:"width,omitempty"`
|
Bold bool `json:"bold,omitempty"`
|
||||||
Height int `json:"height,omitempty"`
|
// Size sets width and height together: 1-8 for text, 1-3 for a block,
|
||||||
Font string `json:"font,omitempty"`
|
// whose borders scale with its text. For a QR code it is the module size
|
||||||
Align string `json:"align,omitempty"`
|
// in dots, 1-16, default 6. 0 means the default.
|
||||||
Underline int `json:"underline,omitempty"`
|
Size int `json:"size,omitempty" jsonschema:"minimum=0,maximum=16"`
|
||||||
Invert bool `json:"invert,omitempty"`
|
// Width is the character width for text (1-8), the module width of a
|
||||||
Newline *bool `json:"newline,omitempty"`
|
// barcode (2-6, default 3), or the target width of an image in dots. 0
|
||||||
Wrap *bool `json:"wrap,omitempty"`
|
// 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 is a feed's number of lines, 1-255. 0 means the default, 1.
|
||||||
Lines int `json:"lines,omitempty"`
|
Lines int `json:"lines,omitempty" jsonschema:"minimum=0,maximum=255"`
|
||||||
|
|
||||||
// QR code and barcode.
|
// Data is a QR code's data, up to 7089 bytes of UTF-8, or a barcode's:
|
||||||
Data string `json:"data,omitempty"`
|
// digits for EAN and UPC, A-Z 0-9 -.$/+% and space for CODE39, printable
|
||||||
Correction string `json:"correction,omitempty"`
|
// ASCII for CODE128.
|
||||||
Symbology string `json:"symbology,omitempty"`
|
Data string `json:"data,omitempty"`
|
||||||
HRI string `json:"hri,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 is an image's http or https URL. Set url or base64.
|
||||||
URL string `json:"url,omitempty"`
|
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"`
|
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"`
|
Hex string `json:"hex,omitempty"`
|
||||||
|
|
||||||
// Cut.
|
// Mode is a cut's mode. Default partial.
|
||||||
Mode string `json:"mode,omitempty"`
|
Mode string `json:"mode,omitempty" jsonschema:"enum=partial,enum=full"`
|
||||||
|
|
||||||
// Blocks. Style is the border or line style of a box or rule. Children
|
// Children are a box's body as elements, one level deep: text, feed,
|
||||||
// are the body of a box, one level deep.
|
// rule and kv. Set text or children, not both.
|
||||||
Children []Element `json:"children,omitempty"`
|
Children []Element `json:"children,omitempty"`
|
||||||
Title string `json:"title,omitempty"`
|
// Title is text set into a box's top border.
|
||||||
TitleStyle string `json:"title_style,omitempty"`
|
Title string `json:"title,omitempty"`
|
||||||
Footer string `json:"footer,omitempty"`
|
// TitleStyle is inline, the default, or capped.
|
||||||
Style string `json:"style,omitempty"`
|
TitleStyle string `json:"title_style,omitempty" jsonschema:"enum=inline,enum=capped"`
|
||||||
Padding *int `json:"padding,omitempty"`
|
// Footer is text set into a box's bottom border, on the right.
|
||||||
Fit bool `json:"fit,omitempty"`
|
Footer string `json:"footer,omitempty"`
|
||||||
Columns int `json:"columns,omitempty"`
|
// Style is a box's border style (single, double, double-h, double-v or
|
||||||
Pairs []Pair `json:"pairs,omitempty"`
|
// ascii) or a rule's line style (single, double, light, medium, dark,
|
||||||
Leader string `json:"leader,omitempty"`
|
// 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.
|
// Pair is one row of a kv block: a key, a leader and a value.
|
||||||
type Pair struct {
|
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"`
|
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
|
// DecodeJob strictly decodes one JSON job. An unknown field is an error, so
|
||||||
|
|||||||
@@ -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)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,120 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"go/ast"
|
||||||
|
"go/parser"
|
||||||
|
"go/token"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"reflect"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// modulePath is the module's import path, which every package path starts
|
||||||
|
// with.
|
||||||
|
const modulePath = "uberbringer"
|
||||||
|
|
||||||
|
// comments maps "pkgpath.Type" and "pkgpath.Type.Field" to the first
|
||||||
|
// paragraph of their doc comments, for the packages whose types the document
|
||||||
|
// describes. Later paragraphs are for Go readers only.
|
||||||
|
// jsonschema's own extractor builds its keys from file paths, which come out
|
||||||
|
// with backslashes on Windows, so the generator reads the comments itself to
|
||||||
|
// give the same document on every platform.
|
||||||
|
type comments map[string]string
|
||||||
|
|
||||||
|
// extractComments reads the doc comments of every type in the packages of
|
||||||
|
// the given values.
|
||||||
|
func extractComments(root string, of ...any) (comments, error) {
|
||||||
|
out := make(comments)
|
||||||
|
for _, v := range of {
|
||||||
|
pkg := reflect.TypeOf(v).PkgPath()
|
||||||
|
rel, ok := strings.CutPrefix(pkg, modulePath+"/")
|
||||||
|
if !ok {
|
||||||
|
return nil, fmt.Errorf("package %s is outside the module", pkg)
|
||||||
|
}
|
||||||
|
dir := filepath.Join(root, filepath.FromSlash(rel))
|
||||||
|
entries, err := os.ReadDir(dir)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("reading %s: %w", rel, err)
|
||||||
|
}
|
||||||
|
fset := token.NewFileSet()
|
||||||
|
for _, e := range entries {
|
||||||
|
name := e.Name()
|
||||||
|
if e.IsDir() || !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
f, err := parser.ParseFile(fset, filepath.Join(dir, name), nil, parser.ParseComments)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
out.collect(pkg, f)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c comments) collect(pkg string, f *ast.File) {
|
||||||
|
for _, decl := range f.Decls {
|
||||||
|
gen, ok := decl.(*ast.GenDecl)
|
||||||
|
if !ok || gen.Tok != token.TYPE {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for _, spec := range gen.Specs {
|
||||||
|
ts := spec.(*ast.TypeSpec)
|
||||||
|
doc := ts.Doc
|
||||||
|
if doc == nil && len(gen.Specs) == 1 {
|
||||||
|
doc = gen.Doc
|
||||||
|
}
|
||||||
|
key := pkg + "." + ts.Name.Name
|
||||||
|
if text := firstParagraph(doc.Text()); text != "" {
|
||||||
|
c[key] = text
|
||||||
|
}
|
||||||
|
st, ok := ts.Type.(*ast.StructType)
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for _, field := range st.Fields.List {
|
||||||
|
text := field.Doc.Text()
|
||||||
|
if text == "" {
|
||||||
|
text = field.Comment.Text()
|
||||||
|
}
|
||||||
|
for _, n := range field.Names {
|
||||||
|
if text != "" {
|
||||||
|
c[key+"."+n.Name] = firstParagraph(text)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// lookup is the jsonschema LookupComment hook: field is the Go field name,
|
||||||
|
// or empty for the type itself. A comment starts, as Go doc comments do,
|
||||||
|
// with the Go name; the document shows the schema's or the property's name
|
||||||
|
// there instead.
|
||||||
|
func (c comments) lookup(t reflect.Type, field string) string {
|
||||||
|
key := t.PkgPath() + "." + t.Name()
|
||||||
|
if field == "" {
|
||||||
|
text := c[key]
|
||||||
|
if rest, ok := strings.CutPrefix(text, t.Name()+" "); ok {
|
||||||
|
text = schemaName(t) + " " + rest
|
||||||
|
}
|
||||||
|
return text
|
||||||
|
}
|
||||||
|
text := c[key+"."+field]
|
||||||
|
if f, ok := t.FieldByName(field); ok {
|
||||||
|
name, _, _ := strings.Cut(f.Tag.Get("json"), ",")
|
||||||
|
if rest, ok := strings.CutPrefix(text, field+" "); ok && name != "" {
|
||||||
|
text = name + " " + rest
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return text
|
||||||
|
}
|
||||||
|
|
||||||
|
// firstParagraph returns a doc comment's text up to its first blank line, on
|
||||||
|
// one line.
|
||||||
|
func firstParagraph(text string) string {
|
||||||
|
para, _, _ := strings.Cut(strings.TrimSpace(text), "\n\n")
|
||||||
|
return strings.Join(strings.Fields(para), " ")
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
// `go generate ./...` regenerates docs/swagger.json. go generate runs each
|
||||||
|
// directive in its own package's directory, so the directive builds this
|
||||||
|
// package as ".".
|
||||||
|
//
|
||||||
|
//go:generate go run .
|
||||||
@@ -0,0 +1,355 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"reflect"
|
||||||
|
"sort"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"unicode"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
|
"github.com/invopop/jsonschema"
|
||||||
|
|
||||||
|
"uberbringer/internal/app/uberbringer/server"
|
||||||
|
"uberbringer/internal/pkg/printqueue"
|
||||||
|
"uberbringer/internal/pkg/receipt"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
componentsPrefix = "#/components/schemas/"
|
||||||
|
defsPrefix = "#/$defs/"
|
||||||
|
securityScheme = "bearerAuth"
|
||||||
|
mediaJSON = "application/json"
|
||||||
|
// codesExtension lists the error codes a status stands for.
|
||||||
|
codesExtension = "x-uberbringer-codes"
|
||||||
|
)
|
||||||
|
|
||||||
|
// jobIDPattern matches a job_ TypeID: a UUIDv7 in Crockford base32 after the
|
||||||
|
// prefix.
|
||||||
|
const jobIDPattern = "^job_[0-7][0-9a-hjkmnp-tv-z]{25}$"
|
||||||
|
|
||||||
|
// Generate returns docs/swagger.json for the route table. root is the
|
||||||
|
// repository root, whose sources hold the doc comments.
|
||||||
|
func Generate(root string) ([]byte, error) {
|
||||||
|
c, err := extractComments(root, server.Route{}, receipt.Job{}, printqueue.Status{})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
g := &generator{
|
||||||
|
requests: newSchemaReflector(c, true),
|
||||||
|
responses: newSchemaReflector(c, false),
|
||||||
|
schemas: make(map[string]any),
|
||||||
|
}
|
||||||
|
if _, err := g.schemaRef(g.responses, server.ErrorBody()); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
paths := make(map[string]any)
|
||||||
|
tags := make(map[string]bool)
|
||||||
|
for _, r := range server.Routes() {
|
||||||
|
op, err := g.operation(r)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s %s: %w", r.Method, r.Path, err)
|
||||||
|
}
|
||||||
|
item, _ := paths[r.Path].(map[string]any)
|
||||||
|
if item == nil {
|
||||||
|
item = make(map[string]any)
|
||||||
|
paths[r.Path] = item
|
||||||
|
}
|
||||||
|
item[strings.ToLower(r.Method)] = op
|
||||||
|
tags[r.Tag] = true
|
||||||
|
}
|
||||||
|
|
||||||
|
var serverErrors []string
|
||||||
|
for _, e := range server.ServerErrors() {
|
||||||
|
serverErrors = append(serverErrors, strconv.Itoa(e.Status)+" "+e.Code)
|
||||||
|
}
|
||||||
|
doc := map[string]any{
|
||||||
|
"openapi": "3.1.0",
|
||||||
|
"info": map[string]any{
|
||||||
|
"title": "Überbringer HTTP API",
|
||||||
|
"version": "v1",
|
||||||
|
"description": "Takes print jobs as JSON and prints them on an Epson ESC/POS receipt printer. " +
|
||||||
|
"Every error is JSON with a stable code. Each operation lists the codes it and its " +
|
||||||
|
"middleware answer with; the HTTP server itself can also refuse any request with " +
|
||||||
|
strings.Join(serverErrors, ", ") + ". Responses from /healthz and every /api/v1 route " +
|
||||||
|
"carry Cache-Control: no-store. Generated from the route table; do not edit.",
|
||||||
|
"license": map[string]any{"name": "EUPL-1.2", "identifier": "EUPL-1.2"},
|
||||||
|
},
|
||||||
|
"tags": sortedTags(tags),
|
||||||
|
"paths": paths,
|
||||||
|
"components": map[string]any{
|
||||||
|
"schemas": g.schemas,
|
||||||
|
"securitySchemes": map[string]any{
|
||||||
|
securityScheme: map[string]any{
|
||||||
|
"type": "http",
|
||||||
|
"scheme": "bearer",
|
||||||
|
"bearerFormat": "JWT",
|
||||||
|
"description": "An HS256 token signed with api.secret, as `uberbringer token` issues them.",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
var buf bytes.Buffer
|
||||||
|
enc := json.NewEncoder(&buf)
|
||||||
|
enc.SetEscapeHTML(false)
|
||||||
|
enc.SetIndent("", " ")
|
||||||
|
if err := enc.Encode(doc); err != nil {
|
||||||
|
return nil, fmt.Errorf("encoding the document: %w", err)
|
||||||
|
}
|
||||||
|
return buf.Bytes(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// newSchemaReflector reflects types into JSON Schema 2020-12, the dialect of
|
||||||
|
// OpenAPI 3.1. A request schema is strict, as the server decodes requests:
|
||||||
|
// an unknown field is an error, and a field is required only when its
|
||||||
|
// jsonschema tag says so. A response schema allows additional properties,
|
||||||
|
// so a field added later does not break a client validating against an
|
||||||
|
// older document, and requires the fields that are always sent.
|
||||||
|
func newSchemaReflector(c comments, request bool) *jsonschema.Reflector {
|
||||||
|
return &jsonschema.Reflector{
|
||||||
|
Anonymous: true,
|
||||||
|
AllowAdditionalProperties: !request,
|
||||||
|
RequiredFromJSONSchemaTags: request,
|
||||||
|
Namer: schemaName,
|
||||||
|
Mapper: mapType(c),
|
||||||
|
LookupComment: c.lookup,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type generator struct {
|
||||||
|
requests, responses *jsonschema.Reflector
|
||||||
|
schemas map[string]any
|
||||||
|
}
|
||||||
|
|
||||||
|
func (g *generator) operation(r server.Route) (map[string]any, error) {
|
||||||
|
op := map[string]any{
|
||||||
|
"operationId": r.OperationID,
|
||||||
|
"summary": r.Summary,
|
||||||
|
"tags": []string{r.Tag},
|
||||||
|
}
|
||||||
|
if r.Description != "" {
|
||||||
|
op["description"] = r.Description
|
||||||
|
}
|
||||||
|
if r.Auth {
|
||||||
|
op["security"] = []any{map[string]any{securityScheme: []string{}}}
|
||||||
|
} else {
|
||||||
|
op["security"] = []any{}
|
||||||
|
}
|
||||||
|
if len(r.Params) > 0 {
|
||||||
|
params := make([]any, len(r.Params))
|
||||||
|
for i, p := range r.Params {
|
||||||
|
params[i] = map[string]any{
|
||||||
|
"name": p.Name,
|
||||||
|
"in": p.In,
|
||||||
|
"required": p.Required || p.In == "path",
|
||||||
|
"description": p.Description,
|
||||||
|
"schema": map[string]any{"type": "string"},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
op["parameters"] = params
|
||||||
|
}
|
||||||
|
if r.Request != nil {
|
||||||
|
ref, err := g.schemaRef(g.requests, r.Request)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
op["requestBody"] = map[string]any{
|
||||||
|
"required": true,
|
||||||
|
"content": map[string]any{mediaJSON: map[string]any{"schema": ref}},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
responses, err := g.routeResponses(r)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
op["responses"] = responses
|
||||||
|
return op, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (g *generator) routeResponses(r server.Route) (map[string]any, error) {
|
||||||
|
responses := make(map[string]any)
|
||||||
|
for _, resp := range r.Responses {
|
||||||
|
doc := map[string]any{"description": resp.Description}
|
||||||
|
if len(resp.Content) > 0 {
|
||||||
|
content := make(map[string]any, len(resp.Content))
|
||||||
|
for _, c := range resp.Content {
|
||||||
|
schema, err := g.bodySchema(c.Body)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
content[c.MediaType] = map[string]any{"schema": schema}
|
||||||
|
}
|
||||||
|
doc["content"] = content
|
||||||
|
}
|
||||||
|
if len(resp.Headers) > 0 {
|
||||||
|
headers := make(map[string]any, len(resp.Headers))
|
||||||
|
for _, h := range resp.Headers {
|
||||||
|
schema := map[string]any{"type": "string"}
|
||||||
|
if h.Integer {
|
||||||
|
schema = map[string]any{"type": "integer", "minimum": 1}
|
||||||
|
}
|
||||||
|
headers[h.Name] = map[string]any{"description": h.Description, "schema": schema}
|
||||||
|
}
|
||||||
|
doc["headers"] = headers
|
||||||
|
}
|
||||||
|
responses[strconv.Itoa(resp.Status)] = doc
|
||||||
|
}
|
||||||
|
|
||||||
|
byStatus := make(map[int][]server.ErrorDoc)
|
||||||
|
for _, e := range r.DocumentedErrors() {
|
||||||
|
byStatus[e.Status] = append(byStatus[e.Status], e)
|
||||||
|
}
|
||||||
|
for status, codes := range byStatus {
|
||||||
|
key := strconv.Itoa(status)
|
||||||
|
if _, taken := responses[key]; taken {
|
||||||
|
return nil, fmt.Errorf("status %d is both a response and an error", status)
|
||||||
|
}
|
||||||
|
names := make([]string, len(codes))
|
||||||
|
titles := make([]string, len(codes))
|
||||||
|
for i, c := range codes {
|
||||||
|
names[i] = c.Code
|
||||||
|
titles[i] = c.Code + ": " + c.Message
|
||||||
|
}
|
||||||
|
resp := map[string]any{
|
||||||
|
"description": http.StatusText(status) + ". " + strings.Join(titles, "; ") + ".",
|
||||||
|
codesExtension: names,
|
||||||
|
"content": map[string]any{mediaJSON: map[string]any{
|
||||||
|
"schema": map[string]any{"$ref": componentsPrefix + "ErrorResponse"},
|
||||||
|
}},
|
||||||
|
}
|
||||||
|
if headers := errorHeaders(status); headers != nil {
|
||||||
|
resp["headers"] = headers
|
||||||
|
}
|
||||||
|
responses[key] = resp
|
||||||
|
}
|
||||||
|
return responses, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// bodySchema is the schema of a response body: a string for a text body,
|
||||||
|
// otherwise a reference to the reflected type.
|
||||||
|
func (g *generator) bodySchema(body any) (map[string]any, error) {
|
||||||
|
if _, ok := body.(string); ok {
|
||||||
|
return map[string]any{"type": "string"}, nil
|
||||||
|
}
|
||||||
|
return g.schemaRef(g.responses, body)
|
||||||
|
}
|
||||||
|
|
||||||
|
// errorHeaders documents the headers an error status carries besides its
|
||||||
|
// body, or nil for none.
|
||||||
|
func errorHeaders(status int) map[string]any {
|
||||||
|
switch status {
|
||||||
|
case http.StatusUnauthorized:
|
||||||
|
return map[string]any{"WWW-Authenticate": map[string]any{
|
||||||
|
"description": `The challenge: Bearer realm="uberbringer", with error="invalid_token" when a ` +
|
||||||
|
"token was sent but is not valid.",
|
||||||
|
"schema": map[string]any{"type": "string"},
|
||||||
|
}}
|
||||||
|
case http.StatusTooManyRequests:
|
||||||
|
return map[string]any{"Retry-After": map[string]any{
|
||||||
|
"description": "How many seconds to wait before the client's next request is let through.",
|
||||||
|
"schema": map[string]any{"type": "integer", "minimum": 1},
|
||||||
|
}}
|
||||||
|
case http.StatusServiceUnavailable:
|
||||||
|
return map[string]any{"Retry-After": map[string]any{
|
||||||
|
"description": "Sent with queue_full: how many seconds to wait before trying again.",
|
||||||
|
"schema": map[string]any{"type": "integer", "minimum": 1},
|
||||||
|
}}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// schemaRef reflects v's type into the components and returns a reference
|
||||||
|
// to it.
|
||||||
|
func (g *generator) schemaRef(r *jsonschema.Reflector, v any) (map[string]any, error) {
|
||||||
|
s := r.Reflect(v)
|
||||||
|
raw, err := json.Marshal(s)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("reflecting %T: %w", v, err)
|
||||||
|
}
|
||||||
|
var root map[string]any
|
||||||
|
if err := json.Unmarshal(raw, &root); err != nil {
|
||||||
|
return nil, fmt.Errorf("reflecting %T: %w", v, err)
|
||||||
|
}
|
||||||
|
defs, _ := root["$defs"].(map[string]any)
|
||||||
|
for name, def := range defs {
|
||||||
|
def = rewriteRefs(def)
|
||||||
|
if existing, ok := g.schemas[name]; ok && !reflect.DeepEqual(existing, def) {
|
||||||
|
return nil, fmt.Errorf("two different schemas are both named %q", name)
|
||||||
|
}
|
||||||
|
g.schemas[name] = def
|
||||||
|
}
|
||||||
|
ref, ok := root["$ref"].(string)
|
||||||
|
if !ok {
|
||||||
|
return nil, fmt.Errorf("%T did not reflect to a named schema", v)
|
||||||
|
}
|
||||||
|
return map[string]any{"$ref": strings.Replace(ref, defsPrefix, componentsPrefix, 1)}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// rewriteRefs points every $ref at the components instead of $defs.
|
||||||
|
func rewriteRefs(node any) any {
|
||||||
|
switch n := node.(type) {
|
||||||
|
case map[string]any:
|
||||||
|
for k, v := range n {
|
||||||
|
if s, ok := v.(string); ok && k == "$ref" {
|
||||||
|
n[k] = strings.Replace(s, defsPrefix, componentsPrefix, 1)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
n[k] = rewriteRefs(v)
|
||||||
|
}
|
||||||
|
case []any:
|
||||||
|
for i, v := range n {
|
||||||
|
n[i] = rewriteRefs(v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return node
|
||||||
|
}
|
||||||
|
|
||||||
|
// schemaName names a component after its Go type, with a capital letter
|
||||||
|
// since several of the server's types are unexported. A job's status is
|
||||||
|
// JobStatus, as Status alone says too little.
|
||||||
|
func schemaName(t reflect.Type) string {
|
||||||
|
if t == reflect.TypeFor[printqueue.Status]() {
|
||||||
|
return "JobStatus"
|
||||||
|
}
|
||||||
|
name := t.Name()
|
||||||
|
if name == "" {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
r, size := utf8.DecodeRuneInString(name)
|
||||||
|
return string(unicode.ToUpper(r)) + name[size:]
|
||||||
|
}
|
||||||
|
|
||||||
|
// mapType gives a job ID its JSON form, a string, in place of the Go struct
|
||||||
|
// behind it.
|
||||||
|
func mapType(c comments) func(reflect.Type) *jsonschema.Schema {
|
||||||
|
return func(t reflect.Type) *jsonschema.Schema {
|
||||||
|
if t != reflect.TypeFor[printqueue.JobID]() {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return &jsonschema.Schema{
|
||||||
|
Type: "string",
|
||||||
|
Pattern: jobIDPattern,
|
||||||
|
Description: c.lookup(t, ""),
|
||||||
|
Examples: []any{"job_01kbx4n6m3ex8tq0wq3r5vrzq1"},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func sortedTags(tags map[string]bool) []any {
|
||||||
|
names := make([]string, 0, len(tags))
|
||||||
|
for name := range tags {
|
||||||
|
names = append(names, name)
|
||||||
|
}
|
||||||
|
sort.Strings(names)
|
||||||
|
out := make([]any, len(names))
|
||||||
|
for i, name := range names {
|
||||||
|
out[i] = map[string]any{"name": name}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
@@ -0,0 +1,260 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"slices"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"uberbringer/internal/app/uberbringer/server"
|
||||||
|
)
|
||||||
|
|
||||||
|
// repoRoot finds the repository root above the package directory, which go
|
||||||
|
// test runs in.
|
||||||
|
func repoRoot(t *testing.T) string {
|
||||||
|
t.Helper()
|
||||||
|
cwd, err := os.Getwd()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
root, err := findRepoRoot(cwd)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return root
|
||||||
|
}
|
||||||
|
|
||||||
|
func generated(t *testing.T) map[string]any {
|
||||||
|
t.Helper()
|
||||||
|
out, err := Generate(repoRoot(t))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Generate: %v", err)
|
||||||
|
}
|
||||||
|
var doc map[string]any
|
||||||
|
if err := json.Unmarshal(out, &doc); err != nil {
|
||||||
|
t.Fatalf("generated document is not JSON: %v", err)
|
||||||
|
}
|
||||||
|
return doc
|
||||||
|
}
|
||||||
|
|
||||||
|
func schema(t *testing.T, doc map[string]any, name string) map[string]any {
|
||||||
|
t.Helper()
|
||||||
|
s, ok := doc["components"].(map[string]any)["schemas"].(map[string]any)[name].(map[string]any)
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("no schema %s", name)
|
||||||
|
}
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
func property(t *testing.T, doc map[string]any, schemaName, prop string) map[string]any {
|
||||||
|
t.Helper()
|
||||||
|
p, ok := schema(t, doc, schemaName)["properties"].(map[string]any)[prop].(map[string]any)
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("%s has no property %s", schemaName, prop)
|
||||||
|
}
|
||||||
|
return p
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestSwaggerJSONUpToDate fails when docs/swagger.json differs from what the
|
||||||
|
// route table and its types produce: regenerate with `go generate ./...`.
|
||||||
|
func TestSwaggerJSONUpToDate(t *testing.T) {
|
||||||
|
root := repoRoot(t)
|
||||||
|
committed, err := os.ReadFile(filepath.Join(root, filepath.FromSlash(swaggerPath)))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
out, err := Generate(root)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !bytes.Equal(committed, out) {
|
||||||
|
t.Fatal("docs/swagger.json is out of date; run: go generate ./...")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGenerateIsStable(t *testing.T) {
|
||||||
|
a, err := Generate(repoRoot(t))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
b, err := Generate(repoRoot(t))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !bytes.Equal(a, b) {
|
||||||
|
t.Fatal("two runs produced different documents")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEveryRouteIsDocumented(t *testing.T) {
|
||||||
|
doc := generated(t)
|
||||||
|
if doc["openapi"] != "3.1.0" {
|
||||||
|
t.Fatalf("openapi = %v", doc["openapi"])
|
||||||
|
}
|
||||||
|
paths := doc["paths"].(map[string]any)
|
||||||
|
for _, r := range server.Routes() {
|
||||||
|
op, ok := paths[r.Path].(map[string]any)[strings.ToLower(r.Method)].(map[string]any)
|
||||||
|
if !ok {
|
||||||
|
t.Errorf("%s %s is not documented", r.Method, r.Path)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if op["operationId"] != r.OperationID {
|
||||||
|
t.Errorf("%s %s: operationId %v", r.Method, r.Path, op["operationId"])
|
||||||
|
}
|
||||||
|
responses := op["responses"].(map[string]any)
|
||||||
|
if _, ok := responses["500"]; !ok {
|
||||||
|
t.Errorf("%s %s: no 500 response", r.Method, r.Path)
|
||||||
|
}
|
||||||
|
security, _ := op["security"].([]any)
|
||||||
|
if r.Auth != (len(security) == 1) {
|
||||||
|
t.Errorf("%s %s: Auth %v, security %v", r.Method, r.Path, r.Auth, op["security"])
|
||||||
|
}
|
||||||
|
if !r.Auth {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for status, header := range map[string]string{"401": "WWW-Authenticate", "429": "Retry-After"} {
|
||||||
|
resp, ok := responses[status].(map[string]any)
|
||||||
|
if !ok {
|
||||||
|
t.Errorf("%s %s: no %s response", r.Method, r.Path, status)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if headers, _ := resp["headers"].(map[string]any); headers[header] == nil {
|
||||||
|
t.Errorf("%s %s: %s without %s", r.Method, r.Path, status, header)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Every {name} in a path has its path parameter.
|
||||||
|
func TestPathParametersDocumented(t *testing.T) {
|
||||||
|
doc := generated(t)
|
||||||
|
paths := doc["paths"].(map[string]any)
|
||||||
|
for _, r := range server.Routes() {
|
||||||
|
op := paths[r.Path].(map[string]any)[strings.ToLower(r.Method)].(map[string]any)
|
||||||
|
params, _ := op["parameters"].([]any)
|
||||||
|
for _, name := range pathParams(r.Path) {
|
||||||
|
found := slices.ContainsFunc(params, func(p any) bool {
|
||||||
|
m := p.(map[string]any)
|
||||||
|
return m["name"] == name && m["in"] == "path" && m["required"] == true
|
||||||
|
})
|
||||||
|
if !found {
|
||||||
|
t.Errorf("%s %s: path parameter %s is not documented", r.Method, r.Path, name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func pathParams(path string) []string {
|
||||||
|
var names []string
|
||||||
|
for part := range strings.SplitSeq(path, "/") {
|
||||||
|
if name, ok := strings.CutPrefix(part, "{"); ok {
|
||||||
|
names = append(names, strings.TrimSuffix(name, "}"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return names
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestReferencesResolve(t *testing.T) {
|
||||||
|
doc := generated(t)
|
||||||
|
schemas := doc["components"].(map[string]any)["schemas"].(map[string]any)
|
||||||
|
var walk func(node any)
|
||||||
|
walk = func(node any) {
|
||||||
|
switch n := node.(type) {
|
||||||
|
case map[string]any:
|
||||||
|
for k, v := range n {
|
||||||
|
if s, ok := v.(string); ok && k == "$ref" {
|
||||||
|
name, found := strings.CutPrefix(s, componentsPrefix)
|
||||||
|
if !found {
|
||||||
|
t.Errorf("$ref %q does not point at the components", s)
|
||||||
|
} else if _, ok := schemas[name]; !ok {
|
||||||
|
t.Errorf("$ref %q names no schema", s)
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
walk(v)
|
||||||
|
}
|
||||||
|
case []any:
|
||||||
|
for _, v := range n {
|
||||||
|
walk(v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
walk(doc)
|
||||||
|
}
|
||||||
|
|
||||||
|
// A request schema refuses unknown fields and requires only what its
|
||||||
|
// jsonschema tags mark, as the server's strict decoder does. A response
|
||||||
|
// schema allows fields a later version adds.
|
||||||
|
func TestRequestSchemasAreStrict(t *testing.T) {
|
||||||
|
doc := generated(t)
|
||||||
|
for name, required := range map[string][]any{"Job": {"elements"}, "Element": {"type"}, "Pair": {"key"}} {
|
||||||
|
s := schema(t, doc, name)
|
||||||
|
if s["additionalProperties"] != false {
|
||||||
|
t.Errorf("%s allows additional properties", name)
|
||||||
|
}
|
||||||
|
if got, _ := s["required"].([]any); !slices.Equal(got, required) {
|
||||||
|
t.Errorf("%s requires %v, want %v", name, got, required)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, name := range []string{"JobStatus", "HealthResponse", "PreviewResponse", "ErrorResponse"} {
|
||||||
|
if _, ok := schema(t, doc, name)["additionalProperties"]; ok {
|
||||||
|
t.Errorf("%s restricts additional properties", name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Descriptions come from the doc comments, with the JSON name in place of
|
||||||
|
// the Go name; enums and the job ID's pattern from the tags and the mapper.
|
||||||
|
func TestSchemasCarryComments(t *testing.T) {
|
||||||
|
doc := generated(t)
|
||||||
|
if d, _ := schema(t, doc, "Element")["description"].(string); !strings.HasPrefix(d, "Element is one item on a receipt") {
|
||||||
|
t.Errorf("Element description = %q", d)
|
||||||
|
}
|
||||||
|
// A type's description starts with the schema's name and stops at the
|
||||||
|
// first blank line of its doc comment.
|
||||||
|
if d, _ := schema(t, doc, "ErrorResponse")["description"].(string); !strings.HasPrefix(d, "ErrorResponse is ") {
|
||||||
|
t.Errorf("ErrorResponse description = %q", d)
|
||||||
|
}
|
||||||
|
if d, _ := schema(t, doc, "Job")["description"].(string); d != "Job is a receipt to print." {
|
||||||
|
t.Errorf("Job description = %q", d)
|
||||||
|
}
|
||||||
|
status := property(t, doc, "JobStatus", "status")
|
||||||
|
if d, _ := status["description"].(string); !strings.HasPrefix(d, "status is ") {
|
||||||
|
t.Errorf("JobStatus.status description = %q", d)
|
||||||
|
}
|
||||||
|
if enum, _ := status["enum"].([]any); len(enum) != 4 {
|
||||||
|
t.Errorf("JobStatus.status enum = %v", status["enum"])
|
||||||
|
}
|
||||||
|
id := property(t, doc, "JobStatus", "id")
|
||||||
|
if id["type"] != "string" || id["pattern"] != jobIDPattern {
|
||||||
|
t.Errorf("JobStatus.id = %v", id)
|
||||||
|
}
|
||||||
|
for _, prop := range []string{"text", "size", "pairs", "leader"} {
|
||||||
|
if d, _ := property(t, doc, "Element", prop)["description"].(string); d == "" {
|
||||||
|
t.Errorf("Element.%s has no description", prop)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Preview answers plain text or JSON, and the print route's 202 carries
|
||||||
|
// the job's URL.
|
||||||
|
func TestResponseContent(t *testing.T) {
|
||||||
|
doc := generated(t)
|
||||||
|
paths := doc["paths"].(map[string]any)
|
||||||
|
preview := paths["/api/v1/preview"].(map[string]any)["post"].(map[string]any)["responses"].(map[string]any)["200"].(map[string]any)
|
||||||
|
content := preview["content"].(map[string]any)
|
||||||
|
if len(content) != 2 || content["application/json"] == nil {
|
||||||
|
t.Errorf("preview 200 content = %v", content)
|
||||||
|
}
|
||||||
|
accepted := paths["/api/v1/print"].(map[string]any)["post"].(map[string]any)["responses"].(map[string]any)["202"].(map[string]any)
|
||||||
|
if headers, _ := accepted["headers"].(map[string]any); headers["Location"] == nil {
|
||||||
|
t.Errorf("print 202 headers = %v", accepted["headers"])
|
||||||
|
}
|
||||||
|
queueFull := paths["/api/v1/print"].(map[string]any)["post"].(map[string]any)["responses"].(map[string]any)["503"].(map[string]any)
|
||||||
|
if codes, _ := queueFull[codesExtension].([]any); !slices.Contains(codes, any("queue_full")) {
|
||||||
|
t.Errorf("print 503 codes = %v", queueFull[codesExtension])
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
// Command genopenapi writes docs/swagger.json, the OpenAPI 3.1 document of
|
||||||
|
// Überbringer's HTTP API, from the route table in
|
||||||
|
// internal/app/uberbringer/server and the Go types it names: paths from the
|
||||||
|
// routes, schemas by reflecting the request and response types (their json
|
||||||
|
// and jsonschema tags and their doc comments). Nothing in the document is
|
||||||
|
// written by hand, and a golden test fails when the committed file differs
|
||||||
|
// from what this produces.
|
||||||
|
//
|
||||||
|
// go run ./tools/genopenapi (or: go generate ./...)
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
)
|
||||||
|
|
||||||
|
// swaggerPath is the generated document, relative to the repository root.
|
||||||
|
const swaggerPath = "docs/swagger.json"
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
if err := run(); err != nil {
|
||||||
|
fmt.Fprintln(os.Stderr, "genopenapi:", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func run() error {
|
||||||
|
cwd, err := os.Getwd()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
root, err := findRepoRoot(cwd)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
out, err := Generate(root)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
path := filepath.Join(root, filepath.FromSlash(swaggerPath))
|
||||||
|
current, err := os.ReadFile(path)
|
||||||
|
if err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if bytes.Equal(current, out) {
|
||||||
|
fmt.Printf("genopenapi: %s is up to date\n", swaggerPath)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(path, out, 0o644); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
fmt.Printf("genopenapi: wrote %s\n", swaggerPath)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// findRepoRoot walks up from start to the directory holding go.mod.
|
||||||
|
func findRepoRoot(start string) (string, error) {
|
||||||
|
dir := start
|
||||||
|
for {
|
||||||
|
if _, err := os.Stat(filepath.Join(dir, "go.mod")); err == nil {
|
||||||
|
return dir, nil
|
||||||
|
}
|
||||||
|
parent := filepath.Dir(dir)
|
||||||
|
if parent == dir {
|
||||||
|
return "", fmt.Errorf("go.mod not found above %s", start)
|
||||||
|
}
|
||||||
|
dir = parent
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user