Refactor to Go standards; add print queue and own ESC/POS library
CI / Lint, test and scan (push) Successful in 1m41s

Restructure the daemon to follow the project's Go coding standards and
expand its features.

Layout and tooling
- cmd/uberbringer/main.go is now thin; all logic lives under internal/.
- Module path is git.anomalous.dev/57_Wolve/uberbringer, go 1.26, every
  dependency upgraded, vendor/ removed.
- staticcheck, govulncheck and goimports pinned as go tools; add a
  Makefile, CI workflow, goreleaser v2 config and Alpine Dockerfile.

Features
- Background print queue with job status (GET /api/v1/jobs/:id), send
  retries with backoff, and graceful shutdown.
- New {"elements": [...]} job format on POST /api/v1/print. Breaking:
  replaces {"data": [...]}, and the response is now JSON 202.
- In-house ESC/POS library replacing justinmichaelvieira/escpos: sizes
  1-8, Font B, CODE39/CODE128, QR, banded raster images, DLE EOT status.
- UTF-8 text transcoded to CP437 (configurable) with word-aware wrapping.
- Images from URL or base64, scaled and dithered; URL fetches refuse
  internal addresses (SSRF guard).
- Fiber v3 HTTP server, TypeID (UUIDv7) job and request IDs, /healthz
  with live printer status, `secret` and `token` subcommands.

Fixes
- Jobs are validated before anything is sent; a failed printer dial no
  longer panics.
- Request logs never contain tokens; Sentry no longer receives the
  Authorization header or print contents.
- Rate limiting is per client behind nginx (X-Real-IP).
- install.sh writes the [printer] section, runs the service as a
  dedicated user and uses a current nginx TLS config.

config.toml is no longer tracked; start from configs/config.example.toml.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
57_WolveandClaude Opus 5.5 committed 2026-11-29 21:17:16 -06:00
1 parent bb73348433
commit 6502d9551d
807 files changed
+6659 -500291

No files matched your search

+165
View File
@@ -0,0 +1,165 @@
// Package uberbringer wires the Überbringer daemon together and provides its
// command-line interface.
package uberbringer
import (
"context"
"crypto/rand"
"encoding/base64"
"fmt"
"io"
"time"
"github.com/golang-jwt/jwt/v5"
"github.com/liamg/tml"
"github.com/spf13/cobra"
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/config"
)
// Project information shown by the banner, the version command and the API
// index route.
const (
Project = "Überbringer"
Description = "EPSON Receipt Printer Server"
Authors = "https://git.anomalous.dev/57_Wolve/uberbringer"
copyright = "William Gill"
)
// secretBytes is the size of generated API secrets: 256 bits, the HS256 hash
// size.
const secretBytes = 32
// BuildInfo is injected at build time through -ldflags.
type BuildInfo struct {
Version string
Commit string
// SentryDSN is the default DSN for release builds; sentry.dsn in the
// config and the SENTRY_DSN environment variable take precedence.
SentryDSN string
}
// Execute runs the command line given by args.
func Execute(ctx context.Context, build BuildInfo, args []string) error {
root := newRootCommand(build)
root.SetArgs(args)
return root.ExecuteContext(ctx)
}
func newRootCommand(build BuildInfo) *cobra.Command {
var configPath string
root := &cobra.Command{
Use: "uberbringer",
Short: "Runs the Überbringer receipt printer daemon.",
SilenceUsage: true,
SilenceErrors: true,
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, _ []string) error {
return serve(cmd.Context(), configPath, build, cmd.OutOrStdout())
},
}
root.PersistentFlags().StringVarP(&configPath, "config", "c", "config.toml", "path to the daemon config file")
root.AddCommand(
newVersionCommand(build),
newSecretCommand(),
newTokenCommand(&configPath),
)
return root
}
func newVersionCommand(build BuildInfo) *cobra.Command {
return &cobra.Command{
Use: "version",
Short: "Prints the version and exits.",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, _ []string) error {
_, err := fmt.Fprintln(cmd.OutOrStdout(), versionLine(build))
return err
},
}
}
func newSecretCommand() *cobra.Command {
return &cobra.Command{
Use: "secret",
Short: "Prints a new random API secret for api.secret in the config.",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, _ []string) error {
_, err := fmt.Fprintln(cmd.OutOrStdout(), newSecret())
return err
},
}
}
func newTokenCommand(configPath *string) *cobra.Command {
var (
subject string
ttl time.Duration
)
cmd := &cobra.Command{
Use: "token",
Short: "Prints a bearer token signed with the config's api.secret.",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, _ []string) error {
cfg, err := config.Load(*configPath)
if err != nil {
return err
}
token, err := signToken([]byte(cfg.API.Secret), subject, ttl, time.Now())
if err != nil {
return err
}
_, err = fmt.Fprintln(cmd.OutOrStdout(), token)
return err
},
}
cmd.Flags().StringVar(&subject, "subject", "uberbringer", "token subject, e.g. the client's name")
cmd.Flags().DurationVar(&ttl, "ttl", 0, "token lifetime, e.g. 720h (0 means it never expires)")
return cmd
}
// newSecret returns a random base64 API secret. crypto/rand.Read never fails
// on supported platforms; it crashes the program rather than return weak bytes.
func newSecret() string {
b := make([]byte, secretBytes)
_, _ = rand.Read(b) // documented to never return an error
return base64.StdEncoding.EncodeToString(b)
}
// signToken returns an HS256 JWT for subject. A zero ttl means no expiry.
func signToken(secret []byte, subject string, ttl time.Duration, now time.Time) (string, error) {
if ttl < 0 {
return "", fmt.Errorf("ttl must not be negative")
}
claims := jwt.RegisteredClaims{
Subject: subject,
IssuedAt: jwt.NewNumericDate(now),
}
if ttl > 0 {
claims.ExpiresAt = jwt.NewNumericDate(now.Add(ttl))
}
signed, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString(secret)
if err != nil {
return "", fmt.Errorf("signing token: %w", err)
}
return signed, nil
}
func versionLine(build BuildInfo) string {
return fmt.Sprintf("%s | Version: %s Build: %s | Copyright © %d %s",
Project, build.Version, build.Commit, time.Now().Year(), copyright)
}
// printBanner writes the startup banner.
func printBanner(w io.Writer, build BuildInfo) {
const rule = "-----------------------------------------------------------------------------------------------"
// The banner is cosmetic; a failed write to the terminal is not worth
// stopping the daemon for.
_ = tml.Fprintf(w, "%s\n\n", rule)
_ = tml.Fprintf(w, "<bold> <lightblue>%s</lightblue></bold>\n\n", versionLine(build))
_ = tml.Fprintf(w, "<bold> <lightblue>Project:</lightblue> %s</bold>\n", Project)
_ = tml.Fprintf(w, "<bold> <lightblue>Description:</lightblue> %s</bold>\n", Description)
_ = tml.Fprintf(w, "<bold> <lightblue>Authors:</lightblue> %s</bold>\n\n", Authors)
_ = tml.Fprintf(w, "%s\n", rule)
}
+104
View File
@@ -0,0 +1,104 @@
package uberbringer
import (
"bytes"
"encoding/base64"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/golang-jwt/jwt/v5"
)
func runCommand(t *testing.T, args ...string) (string, error) {
t.Helper()
cmd := newRootCommand(BuildInfo{Version: "1.2.3", Commit: "abc123"})
var out bytes.Buffer
cmd.SetOut(&out)
cmd.SetArgs(args)
err := cmd.Execute()
return out.String(), err
}
func TestVersionCommand(t *testing.T) {
out, err := runCommand(t, "version")
if err != nil {
t.Fatal(err)
}
if !strings.Contains(out, "Überbringer | Version: 1.2.3 Build: abc123") {
t.Errorf("version output = %q", out)
}
}
func TestSecretCommand(t *testing.T) {
out, err := runCommand(t, "secret")
if err != nil {
t.Fatal(err)
}
raw, err := base64.StdEncoding.DecodeString(strings.TrimSpace(out))
if err != nil || len(raw) != secretBytes {
t.Errorf("secret %q decodes to %d bytes, %v", out, len(raw), err)
}
again, _ := runCommand(t, "secret")
if again == out {
t.Error("two secrets were identical")
}
}
func TestTokenCommand(t *testing.T) {
secret, _ := runCommand(t, "secret")
secret = strings.TrimSpace(secret)
path := filepath.Join(t.TempDir(), "config.toml")
body := "[api]\nsecret = \"" + secret + "\"\n[printer]\naddress = \"192.168.1.245\"\n"
if err := os.WriteFile(path, []byte(body), 0o600); err != nil {
t.Fatal(err)
}
out, err := runCommand(t, "token", "-c", path, "--subject", "kitchen", "--ttl", "1h")
if err != nil {
t.Fatal(err)
}
claims := &jwt.RegisteredClaims{}
_, err = jwt.ParseWithClaims(strings.TrimSpace(out), claims, func(*jwt.Token) (any, error) {
return []byte(secret), nil
}, jwt.WithValidMethods([]string{"HS256"}))
if err != nil {
t.Fatalf("token does not verify: %v", err)
}
if claims.Subject != "kitchen" || claims.ExpiresAt == nil {
t.Errorf("claims = %+v", claims)
}
if left := time.Until(claims.ExpiresAt.Time); left < 59*time.Minute || left > time.Hour {
t.Errorf("expires in %v, want about 1h", left)
}
}
func TestTokenCommandNoExpiryByDefault(t *testing.T) {
token, err := signToken([]byte("0123456789abcdef0123456789abcdef"), "x", 0, time.Now())
if err != nil {
t.Fatal(err)
}
claims := &jwt.RegisteredClaims{}
if _, _, err := jwt.NewParser().ParseUnverified(token, claims); err != nil {
t.Fatal(err)
}
if claims.ExpiresAt != nil {
t.Errorf("ExpiresAt = %v, want none", claims.ExpiresAt)
}
}
func TestServeRejectsBadConfig(t *testing.T) {
_, err := runCommand(t, "-c", filepath.Join(t.TempDir(), "missing.toml"))
if err == nil {
t.Fatal("serve with a missing config must fail")
}
}
func TestNewRequestID(t *testing.T) {
id := newRequestID()
if !strings.HasPrefix(id, "req_") || len(id) != len("req_")+26 {
t.Errorf("request ID %q is not a req_ TypeID", id)
}
}
+177
View File
@@ -0,0 +1,177 @@
package uberbringer
import (
"context"
"fmt"
"io"
"log/slog"
"net"
"os"
"strconv"
"time"
"github.com/getsentry/sentry-go"
"go.jetify.com/typeid"
"golang.org/x/sync/errgroup"
"git.anomalous.dev/57_Wolve/uberbringer/internal/app/uberbringer/server"
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/config"
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/escpos"
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/printer"
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/printqueue"
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/receipt"
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/safehttp"
)
// sentryFlushTimeout bounds how long shutdown waits for queued error reports.
const sentryFlushTimeout = 2 * time.Second
// serve loads the config, wires every component and runs until ctx is
// cancelled.
func serve(ctx context.Context, configPath string, build BuildInfo, out io.Writer) error {
cfg, err := config.Load(configPath)
if err != nil {
return err
}
logger := newLogger(cfg.Log, os.Stderr)
printBanner(out, build)
profile, err := escpos.LookupProfile(cfg.Printer.Model)
if err != nil {
return fmt.Errorf("config printer.model: %w", err)
}
if cfg.Printer.PaperWidth > 0 {
profile.DotsPerLine = cfg.Printer.PaperWidth
}
codePage, err := escpos.ParseCodePage(cfg.Printer.CodePage)
if err != nil {
return fmt.Errorf("config printer.codepage: %w", err)
}
flushSentry, err := initSentry(cfg.Sentry, build, logger)
if err != nil {
return err
}
defer flushSentry()
fetcher := safehttp.New(safehttp.Options{
Timeout: cfg.Images.Timeout,
MaxBytes: cfg.Images.MaxBytes,
AllowPrivate: cfg.Images.AllowPrivateNetworks,
AllowedHosts: cfg.Images.AllowedHosts,
})
renderer := receipt.NewRenderer(receipt.Options{
Profile: profile,
CodePage: codePage,
Columns: cfg.Printer.Columns,
MaxPixels: cfg.Images.MaxPixels,
MaxHeight: cfg.Images.MaxHeight,
}, fetcher)
printerClient := printer.NewClient(
net.JoinHostPort(cfg.Printer.Address, strconv.Itoa(cfg.Printer.Port)),
cfg.Printer.DialTimeout, cfg.Printer.WriteTimeout)
queue := printqueue.New(renderer, printerClient, logger, printqueue.Options{
Size: cfg.Queue.Size,
History: cfg.Queue.History,
Retries: cfg.Printer.Retries,
RetryDelay: cfg.Printer.RetryDelay,
OnFailure: reportJobFailure,
})
srv := server.New(server.Config{
Info: server.Info{
Project: Project,
Description: Description,
Authors: Authors,
Version: build.Version,
Build: build.Commit,
},
Secret: []byte(cfg.API.Secret),
RateLimit: cfg.WebServer.RateLimit,
RateWindow: cfg.WebServer.RateWindow,
TrustedProxies: cfg.WebServer.TrustedProxies,
ProxyHeader: cfg.WebServer.ProxyHeader,
BodyLimit: cfg.WebServer.BodyLimit,
ReadTimeout: cfg.WebServer.ReadTimeout,
WriteTimeout: cfg.WebServer.WriteTimeout,
IdleTimeout: cfg.WebServer.IdleTimeout,
RequestID: newRequestID,
}, queue, printerClient, logger)
addr := net.JoinHostPort(cfg.WebServer.BindIP, strconv.Itoa(cfg.WebServer.Port))
var lc net.ListenConfig
ln, err := lc.Listen(ctx, "tcp", addr)
if err != nil {
return fmt.Errorf("listening on %s: %w", addr, err)
}
logger.Info("listening",
"addr", ln.Addr().String(),
"printer", printerClient.Addr(),
"model", profile.Name,
"codepage", codePage.String(),
"paper_dots", profile.DotsPerLine)
group, groupCtx := errgroup.WithContext(ctx)
group.Go(func() error { return queue.Run(groupCtx) })
group.Go(func() error { return srv.Serve(groupCtx, ln) })
err = group.Wait()
logger.Info("shutdown complete")
return err
}
// newLogger builds the structured logger described by cfg.
func newLogger(cfg config.LogConfig, w io.Writer) *slog.Logger {
var level slog.Level
// config.Validate has already checked the level name.
_ = level.UnmarshalText([]byte(cfg.Level))
options := &slog.HandlerOptions{Level: level}
if cfg.Format == config.LogFormatJSON {
return slog.New(slog.NewJSONHandler(w, options))
}
return slog.New(slog.NewTextHandler(w, options))
}
// initSentry enables error reporting when a DSN is configured and returns a
// func that flushes pending events.
func initSentry(cfg config.SentryConfig, build BuildInfo, logger *slog.Logger) (func(), error) {
dsn := cfg.DSN
if dsn == "" {
dsn = build.SentryDSN
}
if dsn == "" {
logger.Info("error reporting disabled: no Sentry DSN configured")
return func() {}, nil
}
// Leaving DataCollection unset keeps the SDK's no-PII defaults: no user
// data, cookies or sensitive headers. The HTTP middleware also never
// attaches request bodies, which hold the text being printed.
err := sentry.Init(sentry.ClientOptions{
Dsn: dsn,
Environment: cfg.Environment,
Release: "uberbringer@" + build.Version,
Debug: cfg.Debug,
AttachStacktrace: true,
})
if err != nil {
return nil, fmt.Errorf("initializing Sentry: %w", err)
}
logger.Info("error reporting enabled", "environment", cfg.Environment)
return func() { sentry.Flush(sentryFlushTimeout) }, nil
}
// reportJobFailure sends a failed print job to Sentry.
func reportJobFailure(id printqueue.JobID, err error) {
hub := sentry.CurrentHub().Clone()
hub.Scope().SetTag("job_id", id.String())
hub.CaptureException(err)
}
// newRequestID returns a "req_" TypeID.
func newRequestID() string {
id, err := typeid.WithPrefix("req")
if err != nil {
// Only possible if the system random source fails; a timestamp still
// lets log lines for one request be correlated.
return "req_" + strconv.FormatInt(time.Now().UnixNano(), 36)
}
return id.String()
}
+167
View File
@@ -0,0 +1,167 @@
package uberbringer
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
)
// fakePrinter records everything sent to it.
type fakePrinter struct {
mu sync.Mutex
data bytes.Buffer
addr *net.TCPAddr
}
func startFakePrinter(t *testing.T) *fakePrinter {
t.Helper()
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = ln.Close() })
p := &fakePrinter{addr: ln.Addr().(*net.TCPAddr)}
go func() {
for {
conn, err := ln.Accept()
if err != nil {
return
}
go func() {
defer conn.Close()
data, _ := io.ReadAll(conn)
p.mu.Lock()
defer p.mu.Unlock()
p.data.Write(data)
}()
}
}()
return p
}
func (p *fakePrinter) received() []byte {
p.mu.Lock()
defer p.mu.Unlock()
return bytes.Clone(p.data.Bytes())
}
func freePort(t *testing.T) int {
t.Helper()
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer ln.Close()
return ln.Addr().(*net.TCPAddr).Port
}
// TestServeEndToEnd runs the real wiring: config, queue, renderer, printer
// client and HTTP server, then checks a graceful shutdown.
func TestServeEndToEnd(t *testing.T) {
printer := startFakePrinter(t)
port := freePort(t)
const secret = "end-to-end-secret-end-to-end-secret!"
path := filepath.Join(t.TempDir(), "config.toml")
cfg := fmt.Sprintf(`
[webserver]
port = %d
[api]
secret = %q
[printer]
address = "127.0.0.1"
port = %d
[log]
level = "error"
`, port, secret, printer.addr.Port)
if err := os.WriteFile(path, []byte(cfg), 0o600); err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
served := make(chan error, 1)
go func() { served <- serve(ctx, path, BuildInfo{Version: "test"}, io.Discard) }()
base := fmt.Sprintf("http://127.0.0.1:%d", port)
waitFor(t, func() bool {
resp, err := http.Get(base + "/")
if err != nil {
return false
}
resp.Body.Close()
return resp.StatusCode == http.StatusOK
})
token, err := signToken([]byte(secret), "test", 0, time.Now())
if err != nil {
t.Fatal(err)
}
req, _ := http.NewRequest(http.MethodPost, base+"/api/v1/print",
strings.NewReader(`{"elements":[{"type":"text","text":"Grüße aus dem Test"}]}`))
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
var queued struct{ ID, Status string }
if err := json.NewDecoder(resp.Body).Decode(&queued); err != nil {
t.Fatal(err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusAccepted || !strings.HasPrefix(queued.ID, "job_") {
t.Fatalf("POST = %d %+v", resp.StatusCode, queued)
}
waitFor(t, func() bool {
req, _ := http.NewRequest(http.MethodGet, base+"/api/v1/jobs/"+queued.ID, nil)
req.Header.Set("Authorization", "Bearer "+token)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return false
}
defer resp.Body.Close()
var st struct{ Status string }
_ = json.NewDecoder(resp.Body).Decode(&st)
return st.Status == "done"
})
waitFor(t, func() bool {
// "Grüße" in CP437: ü is 0x81, ß is 0xE1.
return bytes.Contains(printer.received(), []byte("Gr\x81\xE1e aus dem Test"))
})
cancel()
select {
case err := <-served:
if err != nil {
t.Fatalf("serve returned %v after shutdown", err)
}
case <-time.After(15 * time.Second):
t.Fatal("serve did not shut down")
}
if _, err := http.Get(base + "/"); err == nil {
t.Error("server still accepting connections after shutdown")
}
}
func waitFor(t *testing.T, cond func() bool) {
t.Helper()
deadline := time.Now().Add(10 * time.Second)
for time.Now().Before(deadline) {
if cond() {
return
}
time.Sleep(20 * time.Millisecond)
}
t.Fatal("condition not met within 10s")
}
+40
View File
@@ -0,0 +1,40 @@
package server
import (
"strings"
"github.com/gofiber/fiber/v3"
"github.com/golang-jwt/jwt/v5"
)
// requireBearerToken rejects requests without a valid HS256 bearer token.
// Tokens are only read from the Authorization header: query-string tokens
// end up in proxy and access logs.
func requireBearerToken(secret []byte) fiber.Handler {
parser := jwt.NewParser(jwt.WithValidMethods([]string{jwt.SigningMethodHS256.Alg()}))
keyFunc := func(*jwt.Token) (any, error) { return secret, nil }
return func(c fiber.Ctx) error {
token, ok := bearerToken(c.Get(fiber.HeaderAuthorization))
if !ok {
c.Set(fiber.HeaderWWWAuthenticate, `Bearer realm="uberbringer"`)
return fiber.NewError(fiber.StatusUnauthorized, "missing bearer token")
}
if _, err := parser.Parse(token, keyFunc); err != nil {
c.Set(fiber.HeaderWWWAuthenticate, `Bearer realm="uberbringer", error="invalid_token"`)
return fiber.NewError(fiber.StatusUnauthorized, "invalid or expired token")
}
return c.Next()
}
}
// bearerToken extracts the token from an Authorization header value. The
// scheme is case-insensitive (RFC 7235).
func bearerToken(header string) (string, bool) {
const scheme = "bearer "
if len(header) <= len(scheme) || !strings.EqualFold(header[:len(scheme)], scheme) {
return "", false
}
token := strings.TrimSpace(header[len(scheme):])
return token, token != ""
}
+204
View File
@@ -0,0 +1,204 @@
package server
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"strings"
"time"
"github.com/gofiber/fiber/v3"
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/printer"
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/printqueue"
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/receipt"
)
// healthTimeout bounds the printer status check behind /healthz.
const healthTimeout = 3 * time.Second
// apiError is an error with an HTTP status and optional details.
type apiError struct {
status int
message string
details []string
}
func (e *apiError) Error() string { return e.message }
// errorResponse is the JSON body of every error.
type errorResponse struct {
Error string `json:"error"`
Details []string `json:"details,omitempty"`
}
// handleError turns errors into JSON responses. Server errors are logged and
// reported to Sentry here, once, at the HTTP boundary.
func (s *Server) handleError(c fiber.Ctx, err error) error {
resp := errorResponse{Error: "internal server error"}
status := fiber.StatusInternalServerError
var (
apiErr *apiError
fiberErr *fiber.Error
)
switch {
case errors.As(err, &apiErr):
status, resp.Error, resp.Details = apiErr.status, apiErr.message, apiErr.details
case errors.As(err, &fiberErr):
status, resp.Error = fiberErr.Code, fiberErr.Message
}
if status >= fiber.StatusInternalServerError {
s.logger.Error("request failed", "path", c.Path(), "err", err)
hubFrom(c).CaptureException(err)
}
return c.Status(status).JSON(resp)
}
func (s *Server) handleIndex(c fiber.Ctx) error {
info := 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 {
return c.SendString("User-agent: *\nDisallow:\n")
}
// handlePrint validates and queues a job.
func (s *Server) handlePrint(c fiber.Ctx) error {
job, err := decodeJob(c.Body())
if err != nil {
return err
}
if err := job.Validate(); err != nil {
var ve *receipt.ValidationError
if errors.As(err, &ve) {
return &apiError{status: fiber.StatusBadRequest, message: "invalid job", details: ve.Problems}
}
return err
}
status, err := s.jobs.Submit(job)
switch {
case errors.Is(err, printqueue.ErrQueueFull):
c.Set(fiber.HeaderRetryAfter, "10")
return fiber.NewError(fiber.StatusServiceUnavailable, "print queue is full, try again shortly")
case errors.Is(err, printqueue.ErrClosed):
return fiber.NewError(fiber.StatusServiceUnavailable, "server is shutting down")
case err != nil:
return fmt.Errorf("submitting job: %w", err)
}
c.Location("/api/v1/jobs/" + status.ID.String())
return c.Status(fiber.StatusAccepted).JSON(status)
}
// decodeJob strictly decodes a job body. Unknown fields are rejected so typos
// and the pre-refactor {"data": [...]} format fail loudly.
func decodeJob(body []byte) (receipt.Job, error) {
var job receipt.Job
dec := json.NewDecoder(bytes.NewReader(body))
dec.DisallowUnknownFields()
if err := dec.Decode(&job); err != nil {
msg := "request body is not a valid job: " + err.Error()
if strings.Contains(err.Error(), `unknown field "data"`) {
msg = `the {"data": [...]} format was replaced by {"elements": [...]}; see the README for the element format`
}
return job, &apiError{status: fiber.StatusBadRequest, message: msg}
}
if _, err := dec.Token(); !errors.Is(err, io.EOF) {
return job, &apiError{status: fiber.StatusBadRequest, message: "request body has trailing data after the job"}
}
return job, nil
}
// handleJob returns the status of one job.
func (s *Server) handleJob(c fiber.Ctx) error {
// Clone: fasthttp reuses the buffer behind route params.
id, err := printqueue.ParseJobID(strings.Clone(c.Params("id")))
if err != nil {
return fiber.NewError(fiber.StatusNotFound, "job not found")
}
status, err := s.jobs.Status(id)
if errors.Is(err, printqueue.ErrNotFound) {
return fiber.NewError(fiber.StatusNotFound, "job not found")
}
if err != nil {
return err
}
return c.JSON(status)
}
// printerHealth is the printer part of the /healthz response.
type printerHealth struct {
Reachable bool `json:"reachable"`
Status string `json:"status"`
Online *bool `json:"online,omitempty"`
CoverOpen *bool `json:"cover_open,omitempty"`
Paper string `json:"paper,omitempty"`
Error string `json:"error,omitempty"`
}
type healthResponse struct {
Status string `json:"status"`
Printer printerHealth `json:"printer"`
Queue struct {
Pending int `json:"pending"`
} `json:"queue"`
}
// handleHealth reports whether the printer is reachable and ready. It
// answers 503 when it is not, so load balancers and monitors can alert.
func (s *Server) handleHealth(c fiber.Ctx) error {
ctx, cancel := context.WithTimeout(c.Context(), healthTimeout)
defer cancel()
var resp healthResponse
resp.Queue.Pending = s.jobs.Pending()
httpStatus := fiber.StatusOK
st, err := s.printer.Status(ctx)
switch {
case errors.Is(err, printer.ErrStatusUnsupported):
resp.Status = "ok"
resp.Printer = printerHealth{Reachable: true, Status: "unknown"}
case err != nil:
s.logger.Warn("printer health check failed", "err", err)
resp.Status = "unavailable"
resp.Printer = printerHealth{Reachable: false, Status: "unreachable"}
httpStatus = fiber.StatusServiceUnavailable
default:
paper := "ok"
switch {
case st.PaperOut:
paper = "out"
case st.PaperNearEnd:
paper = "near_end"
}
resp.Printer = printerHealth{
Reachable: true,
Status: "ready",
Online: &st.Online,
CoverOpen: &st.CoverOpen,
Paper: paper,
}
resp.Status = "ok"
if !st.Ready() {
resp.Status = "degraded"
resp.Printer.Status = "not_ready"
if st.CutterError || st.Unrecoverable || st.AutoRecoverable {
resp.Printer.Error = "printer reports an error"
}
httpStatus = fiber.StatusServiceUnavailable
}
}
return c.Status(httpStatus).JSON(resp)
}
+194
View File
@@ -0,0 +1,194 @@
// Package server exposes the Überbringer HTTP API on Fiber.
package server
import (
"context"
"errors"
"log/slog"
"net"
"time"
"github.com/getsentry/sentry-go"
"github.com/gofiber/fiber/v3"
"github.com/gofiber/fiber/v3/middleware/compress"
"github.com/gofiber/fiber/v3/middleware/limiter"
recoverer "github.com/gofiber/fiber/v3/middleware/recover" // avoids shadowing the recover builtin
"github.com/gofiber/fiber/v3/middleware/requestid"
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/escpos"
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/printqueue"
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/receipt"
)
// shutdownTimeout bounds how long in-flight requests may take to finish.
const shutdownTimeout = 10 * time.Second
// Jobs is the print queue as seen by the HTTP handlers.
type Jobs interface {
Submit(job receipt.Job) (printqueue.Status, error)
Status(id printqueue.JobID) (printqueue.Status, error)
Pending() int
}
// Printer reports the printer's real-time status.
type Printer interface {
Status(ctx context.Context) (escpos.Status, error)
}
// Info describes the running build for the index route.
type Info struct {
Project string
Description string
Authors string
Version string
Build string
}
// Config configures the HTTP server.
type Config struct {
Info Info
// Secret is the HS256 key bearer tokens must be signed with.
Secret []byte
// RateLimit requests per RateWindow are allowed per client IP on /api.
RateLimit int
RateWindow time.Duration
// TrustedProxies may set ProxyHeader to the real client IP.
TrustedProxies []string
ProxyHeader string
BodyLimit int
ReadTimeout time.Duration
WriteTimeout time.Duration
IdleTimeout time.Duration
// RequestID generates request IDs.
RequestID func() string
}
// Server is the HTTP API.
type Server struct {
app *fiber.App
config Config
jobs Jobs
printer Printer
logger *slog.Logger
}
// New builds the server and its routes.
func New(config Config, jobs Jobs, printer Printer, logger *slog.Logger) *Server {
switch {
case jobs == nil || printer == nil || logger == nil:
panic("server.New: jobs, printer and logger must not be nil")
case len(config.Secret) == 0:
panic("server.New: secret must not be empty")
case config.RequestID == nil:
panic("server.New: RequestID must not be nil")
}
s := &Server{config: config, jobs: jobs, printer: printer, logger: logger}
s.app = fiber.New(fiber.Config{
AppName: config.Info.Project,
BodyLimit: config.BodyLimit,
ReadTimeout: config.ReadTimeout,
WriteTimeout: config.WriteTimeout,
IdleTimeout: config.IdleTimeout,
ErrorHandler: s.handleError,
TrustProxy: len(config.TrustedProxies) > 0,
ProxyHeader: config.ProxyHeader,
EnableIPValidation: true,
TrustProxyConfig: fiber.TrustProxyConfig{Proxies: config.TrustedProxies},
})
s.app.Use(recoverer.New())
s.app.Use(sentryMiddleware)
s.app.Use(requestid.New(requestid.Config{Generator: config.RequestID}))
s.app.Use(s.logRequests)
s.app.Use(compress.New(compress.Config{Level: compress.LevelBestSpeed}))
s.app.Get("/", s.handleIndex)
s.app.Get("/robots.txt", handleRobots)
s.app.Get("/healthz", s.handleHealth)
api := s.app.Group("/api/v1",
limiter.New(limiter.Config{
Max: config.RateLimit,
Expiration: config.RateWindow,
KeyGenerator: func(c fiber.Ctx) string { return c.IP() },
LimitReached: func(fiber.Ctx) error { return fiber.ErrTooManyRequests },
}),
requireBearerToken(config.Secret),
)
api.Post("/print", s.handlePrint)
api.Get("/jobs/:id", s.handleJob)
return s
}
// Serve accepts connections on ln until ctx is cancelled, then shuts down
// gracefully.
func (s *Server) Serve(ctx context.Context, ln net.Listener) error {
err := s.app.Listener(ln, fiber.ListenConfig{
GracefulContext: ctx,
ShutdownTimeout: shutdownTimeout,
DisableStartupMessage: true,
})
if err != nil && !errors.Is(err, net.ErrClosed) {
return err
}
return nil
}
// logRequests logs every request once, after the error handler has set the
// final status. Only the path is logged, never the query string.
func (s *Server) logRequests(c fiber.Ctx) error {
start := time.Now()
if err := c.Next(); err != nil {
if handlerErr := s.handleError(c, err); handlerErr != nil {
return handlerErr
}
}
status := c.Response().StatusCode()
level := slog.LevelInfo
if status >= fiber.StatusInternalServerError {
level = slog.LevelError
}
s.logger.LogAttrs(c.Context(), level, "request",
slog.String("method", c.Method()),
slog.String("path", c.Path()),
slog.Int("status", status),
slog.Duration("latency", time.Since(start)),
slog.String("ip", c.IP()),
slog.String("request_id", requestid.FromContext(c)),
)
return nil
}
// sentryHubKey stores the per-request Sentry hub in fiber Locals.
type sentryHubKey struct{}
// sentryMiddleware reports panics to Sentry with a per-request hub, then
// re-panics so the recover middleware can turn them into a 500. Request
// bodies are deliberately not attached: they hold the text being printed.
func sentryMiddleware(c fiber.Ctx) error {
hub := sentry.CurrentHub().Clone()
hub.Scope().SetTag("method", c.Method())
hub.Scope().SetTag("path", c.Path())
c.Locals(sentryHubKey{}, hub)
defer func() {
if r := recover(); r != nil {
hub.Recover(r)
panic(r)
}
}()
return c.Next()
}
func hubFrom(c fiber.Ctx) *sentry.Hub {
if hub, ok := c.Locals(sentryHubKey{}).(*sentry.Hub); ok {
return hub
}
return sentry.CurrentHub()
}
@@ -0,0 +1,377 @@
package server
import (
"context"
"encoding/json"
"errors"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
"github.com/golang-jwt/jwt/v5"
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/escpos"
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/printer"
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/printqueue"
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/receipt"
)
var testSecret = []byte("0123456789abcdef0123456789abcdef")
type fakeJobs struct {
mu sync.Mutex
submitted []receipt.Job
submitErr error
statuses map[printqueue.JobID]printqueue.Status
nextID printqueue.JobID
}
func (f *fakeJobs) Submit(job receipt.Job) (printqueue.Status, error) {
f.mu.Lock()
defer f.mu.Unlock()
if f.submitErr != nil {
return printqueue.Status{}, f.submitErr
}
f.submitted = append(f.submitted, job)
st := printqueue.Status{ID: f.nextID, State: printqueue.StateQueued, CreatedAt: time.Now()}
f.statuses[f.nextID] = st
return st, nil
}
func (f *fakeJobs) Status(id printqueue.JobID) (printqueue.Status, error) {
f.mu.Lock()
defer f.mu.Unlock()
st, ok := f.statuses[id]
if !ok {
return printqueue.Status{}, printqueue.ErrNotFound
}
return st, nil
}
func (f *fakeJobs) Pending() int { return 0 }
type fakePrinter struct {
status escpos.Status
err error
}
func (f fakePrinter) Status(context.Context) (escpos.Status, error) { return f.status, f.err }
func newJobID(t *testing.T) printqueue.JobID {
t.Helper()
id, err := printqueue.ParseJobID("job_01h455vb4pex5vsknk084sn02q")
if err != nil {
t.Fatal(err)
}
return id
}
func newTestServer(t *testing.T, jobs *fakeJobs, p Printer) *Server {
t.Helper()
if jobs.statuses == nil {
jobs.statuses = map[printqueue.JobID]printqueue.Status{}
}
return New(Config{
Info: Info{Project: "Überbringer", Version: "test"},
Secret: testSecret,
RateLimit: 1000,
RateWindow: time.Minute,
TrustedProxies: []string{"127.0.0.1"},
ProxyHeader: "X-Real-IP",
BodyLimit: 1 << 20,
ReadTimeout: time.Second,
WriteTimeout: time.Second,
IdleTimeout: time.Second,
RequestID: func() string { return "req_test" },
}, jobs, p, slog.New(slog.NewTextHandler(io.Discard, nil)))
}
func token(t *testing.T, secret []byte, method jwt.SigningMethod, claims jwt.Claims) string {
t.Helper()
signed, err := jwt.NewWithClaims(method, claims).SignedString(secret)
if err != nil {
t.Fatal(err)
}
return signed
}
func validToken(t *testing.T) string {
return token(t, testSecret, jwt.SigningMethodHS256, jwt.MapClaims{"user_id": "uberbringer"})
}
func do(t *testing.T, s *Server, req *http.Request) (*http.Response, map[string]any) {
t.Helper()
resp, err := s.app.Test(req)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
var parsed map[string]any
_ = json.Unmarshal(body, &parsed) // some routes return plain text
return resp, parsed
}
func printRequest(t *testing.T, body, auth string) *http.Request {
t.Helper()
req := httptest.NewRequest(http.MethodPost, "/api/v1/print", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
if auth != "" {
req.Header.Set("Authorization", auth)
}
return req
}
const validJob = `{"elements":[{"type":"text","text":"Hello"}]}`
func TestPrintAuth(t *testing.T) {
expired := token(t, testSecret, jwt.SigningMethodHS256, jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(time.Now().Add(-time.Hour)),
})
wrongKey := token(t, []byte("another-secret-another-secret-xx"), jwt.SigningMethodHS256, jwt.MapClaims{})
hs512 := token(t, testSecret, jwt.SigningMethodHS512, jwt.MapClaims{})
tests := []struct {
name string
auth string
want int
}{
{"no header", "", http.StatusUnauthorized},
{"not bearer", "Basic abc", http.StatusUnauthorized},
{"garbage token", "Bearer nope", http.StatusUnauthorized},
{"wrong key", "Bearer " + wrongKey, http.StatusUnauthorized},
{"expired", "Bearer " + expired, http.StatusUnauthorized},
{"wrong algorithm", "Bearer " + hs512, http.StatusUnauthorized},
{"legacy install.sh token", "Bearer " + validToken(t), http.StatusAccepted},
{"lowercase scheme", "bearer " + validToken(t), http.StatusAccepted},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
s := newTestServer(t, &fakeJobs{nextID: newJobID(t)}, fakePrinter{})
resp, body := do(t, s, printRequest(t, validJob, tt.auth))
if resp.StatusCode != tt.want {
t.Fatalf("status = %d, want %d (%v)", resp.StatusCode, tt.want, body)
}
if tt.want == http.StatusUnauthorized && resp.Header.Get("WWW-Authenticate") == "" {
t.Error("401 without WWW-Authenticate")
}
})
}
}
func TestPrintQueryTokenIsNotAccepted(t *testing.T) {
s := newTestServer(t, &fakeJobs{nextID: newJobID(t)}, fakePrinter{})
req := httptest.NewRequest(http.MethodPost, "/api/v1/print?token="+validToken(t), strings.NewReader(validJob))
if resp, _ := do(t, s, req); resp.StatusCode != http.StatusUnauthorized {
t.Errorf("status = %d, want 401", resp.StatusCode)
}
}
func TestPrintAccepted(t *testing.T) {
jobs := &fakeJobs{nextID: newJobID(t)}
s := newTestServer(t, jobs, fakePrinter{})
resp, body := do(t, s, printRequest(t, validJob, "Bearer "+validToken(t)))
if resp.StatusCode != http.StatusAccepted {
t.Fatalf("status = %d (%v)", resp.StatusCode, body)
}
if body["id"] != "job_01h455vb4pex5vsknk084sn02q" || body["status"] != "queued" {
t.Errorf("body = %v", body)
}
if loc := resp.Header.Get("Location"); loc != "/api/v1/jobs/job_01h455vb4pex5vsknk084sn02q" {
t.Errorf("Location = %q", loc)
}
if len(jobs.submitted) != 1 || jobs.submitted[0].Elements[0].Text != "Hello" {
t.Errorf("submitted %+v", jobs.submitted)
}
}
func TestPrintBadRequests(t *testing.T) {
tests := []struct {
name, body, wantErr string
}{
{"not json", `nope`, "not a valid job"},
{"old format", `{"data":[{"type":1,"size":1,"text":"hi"}]}`, `replaced by {"elements": [...]}`},
{"unknown element field", `{"elements":[{"type":"text","colour":"red"}]}`, `unknown field "colour"`},
{"trailing data", validJob + `{}`, "trailing data"},
{"invalid element", `{"elements":[{"type":"text","size":12}]}`, "invalid job"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
jobs := &fakeJobs{nextID: newJobID(t)}
s := newTestServer(t, jobs, fakePrinter{})
resp, body := do(t, s, printRequest(t, tt.body, "Bearer "+validToken(t)))
if resp.StatusCode != http.StatusBadRequest {
t.Fatalf("status = %d, want 400 (%v)", resp.StatusCode, body)
}
if msg, _ := body["error"].(string); !strings.Contains(msg, tt.wantErr) {
t.Errorf("error = %q, want it to contain %q", msg, tt.wantErr)
}
if len(jobs.submitted) != 0 {
t.Error("invalid job was submitted")
}
})
}
}
func TestPrintValidationDetails(t *testing.T) {
s := newTestServer(t, &fakeJobs{nextID: newJobID(t)}, fakePrinter{})
_, body := do(t, s, printRequest(t, `{"elements":[{"type":"text","size":12},{"type":"qr"}]}`, "Bearer "+validToken(t)))
details, _ := body["details"].([]any)
if len(details) != 2 {
t.Errorf("details = %v, want 2 problems", body["details"])
}
}
func TestPrintQueueFull(t *testing.T) {
s := newTestServer(t, &fakeJobs{submitErr: printqueue.ErrQueueFull}, fakePrinter{})
resp, _ := do(t, s, printRequest(t, validJob, "Bearer "+validToken(t)))
if resp.StatusCode != http.StatusServiceUnavailable || resp.Header.Get("Retry-After") == "" {
t.Errorf("status = %d, Retry-After = %q", resp.StatusCode, resp.Header.Get("Retry-After"))
}
}
func TestJobStatus(t *testing.T) {
id := newJobID(t)
jobs := &fakeJobs{statuses: map[printqueue.JobID]printqueue.Status{
id: {ID: id, State: printqueue.StateDone, Attempts: 1},
}}
s := newTestServer(t, jobs, fakePrinter{})
auth := "Bearer " + validToken(t)
tests := []struct {
path string
want int
}{
{"/api/v1/jobs/" + id.String(), http.StatusOK},
{"/api/v1/jobs/job_01h455vb4pex5vsknk084sn02r", http.StatusNotFound},
{"/api/v1/jobs/not-an-id", http.StatusNotFound},
}
for _, tt := range tests {
req := httptest.NewRequest(http.MethodGet, tt.path, nil)
req.Header.Set("Authorization", auth)
resp, body := do(t, s, req)
if resp.StatusCode != tt.want {
t.Errorf("GET %s = %d, want %d", tt.path, resp.StatusCode, tt.want)
}
if tt.want == http.StatusOK && body["status"] != "done" {
t.Errorf("body = %v", body)
}
}
req := httptest.NewRequest(http.MethodGet, "/api/v1/jobs/"+id.String(), nil)
if resp, _ := do(t, s, req); resp.StatusCode != http.StatusUnauthorized {
t.Errorf("unauthenticated status lookup = %d, want 401", resp.StatusCode)
}
}
func TestHealth(t *testing.T) {
tests := []struct {
name string
printer fakePrinter
want int
wantStatus string
wantPrinter string
wantPaper string
wantReachable bool
}{
{"ready", fakePrinter{status: escpos.Status{Online: true}}, 200, "ok", "ready", "ok", true},
{"paper low still ok", fakePrinter{status: escpos.Status{Online: true, PaperNearEnd: true}}, 200, "ok", "ready", "near_end", true},
{"paper out", fakePrinter{status: escpos.Status{PaperOut: true}}, 503, "degraded", "not_ready", "out", true},
{"no status support", fakePrinter{err: printer.ErrStatusUnsupported}, 200, "ok", "unknown", "", true},
{"unreachable", fakePrinter{err: errors.New("dial tcp: timeout")}, 503, "unavailable", "unreachable", "", false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
s := newTestServer(t, &fakeJobs{}, tt.printer)
resp, body := do(t, s, httptest.NewRequest(http.MethodGet, "/healthz", nil))
if resp.StatusCode != tt.want {
t.Fatalf("status = %d, want %d", resp.StatusCode, tt.want)
}
p, _ := body["printer"].(map[string]any)
if body["status"] != tt.wantStatus || p["status"] != tt.wantPrinter || p["reachable"] != tt.wantReachable {
t.Errorf("body = %v", body)
}
if paper, _ := p["paper"].(string); paper != tt.wantPaper {
t.Errorf("paper = %q, want %q", paper, tt.wantPaper)
}
if _, leaked := p["error"].(string); leaked && !tt.wantReachable {
t.Error("unreachable printer error text must not be exposed publicly")
}
})
}
}
func TestIndexAndRobotsAndNotFound(t *testing.T) {
s := newTestServer(t, &fakeJobs{}, fakePrinter{})
resp, body := do(t, s, httptest.NewRequest(http.MethodGet, "/", nil))
if resp.StatusCode != 200 || body["Project"] != "Überbringer" || body["Version"] != "test" {
t.Errorf("index = %d %v", resp.StatusCode, body)
}
if resp, _ := do(t, s, httptest.NewRequest(http.MethodGet, "/robots.txt", nil)); resp.StatusCode != 200 {
t.Errorf("robots = %d", resp.StatusCode)
}
resp, body = do(t, s, httptest.NewRequest(http.MethodGet, "/nope", nil))
if resp.StatusCode != 404 || body["error"] == nil {
t.Errorf("404 = %d %v, want JSON error", resp.StatusCode, body)
}
}
func TestRateLimitPerClientBehindProxy(t *testing.T) {
jobs := &fakeJobs{nextID: newJobID(t), statuses: map[printqueue.JobID]printqueue.Status{}}
s := New(Config{
Info: Info{Project: "Überbringer"},
Secret: testSecret,
RateLimit: 2,
RateWindow: time.Minute,
TrustedProxies: []string{"0.0.0.0/0"},
ProxyHeader: "X-Real-IP",
BodyLimit: 1 << 20,
ReadTimeout: time.Second,
WriteTimeout: time.Second,
IdleTimeout: time.Second,
RequestID: func() string { return "req_test" },
}, jobs, fakePrinter{}, slog.New(slog.NewTextHandler(io.Discard, nil)))
send := func(clientIP string) int {
req := printRequest(t, validJob, "Bearer "+validToken(t))
req.Header.Set("X-Real-IP", clientIP)
resp, _ := do(t, s, req)
return resp.StatusCode
}
for range 2 {
if code := send("203.0.113.1"); code != http.StatusAccepted {
t.Fatalf("status = %d, want 202", code)
}
}
if code := send("203.0.113.1"); code != http.StatusTooManyRequests {
t.Errorf("third request status = %d, want 429", code)
}
if code := send("203.0.113.2"); code != http.StatusAccepted {
t.Errorf("other client status = %d, want 202 (limits must be per client)", code)
}
}
func TestBearerToken(t *testing.T) {
tests := map[string]struct {
token string
ok bool
}{
"Bearer abc": {"abc", true},
"BEARER abc": {"abc", true},
"Bearer ": {"", false},
"Bearer": {"", false},
"Basic abc": {"", false},
"Bearer abc ": {"abc", true},
}
for header, want := range tests {
got, ok := bearerToken(header)
if got != want.token || ok != want.ok {
t.Errorf("bearerToken(%q) = %q, %v; want %q, %v", header, got, ok, want.token, want.ok)
}
}
}
+270
View File
@@ -0,0 +1,270 @@
// Package config loads and validates the Überbringer daemon configuration
// from a TOML file.
package config
import (
"errors"
"fmt"
"net/netip"
"os"
"slices"
"strings"
"time"
"github.com/BurntSushi/toml"
)
// MinSecretLength is the minimum API secret length in bytes. HS256 keys
// shorter than the 256-bit hash output weaken the signature (RFC 7518 §3.2).
const MinSecretLength = 32
// Log formats accepted by [LogConfig.Format].
const (
LogFormatText = "text"
LogFormatJSON = "json"
)
// Config is the root daemon configuration.
type Config struct {
WebServer WebServerConfig `toml:"webserver"`
API APIConfig `toml:"api"`
Printer PrinterConfig `toml:"printer"`
Queue QueueConfig `toml:"queue"`
Images ImagesConfig `toml:"images"`
Sentry SentryConfig `toml:"sentry"`
Log LogConfig `toml:"log"`
}
// WebServerConfig configures the HTTP listener.
type WebServerConfig struct {
BindIP string `toml:"bind_ip"`
Port int `toml:"port"`
// RateLimit is the number of API requests one client may make per
// RateWindow.
RateLimit int `toml:"rate_limit"`
RateWindow time.Duration `toml:"rate_window"`
// TrustedProxies lists proxy IPs or CIDR ranges whose ProxyHeader is
// trusted to carry the real client IP.
TrustedProxies []string `toml:"trusted_proxies"`
ProxyHeader string `toml:"proxy_header"`
// BodyLimit is the maximum request body size in bytes.
BodyLimit int `toml:"body_limit"`
ReadTimeout time.Duration `toml:"read_timeout"`
WriteTimeout time.Duration `toml:"write_timeout"`
IdleTimeout time.Duration `toml:"idle_timeout"`
}
// APIConfig configures API authentication.
type APIConfig struct {
// Secret is the HS256 key used to verify bearer tokens.
Secret string `toml:"secret"`
}
// PrinterConfig configures the network receipt printer.
type PrinterConfig struct {
Address string `toml:"address"`
Port int `toml:"port"`
// Model selects a printer profile, e.g. "tm-t20" or "generic-58mm".
Model string `toml:"model"`
// CodePage is the character table text is transcoded to, e.g. "cp437".
CodePage string `toml:"codepage"`
// PaperWidth overrides the profile's printable width in dots. Zero keeps
// the profile default.
PaperWidth int `toml:"paper_width"`
// Columns overrides the number of Font A characters per line used for
// word wrapping. Zero derives it from the paper width.
Columns int `toml:"columns"`
DialTimeout time.Duration `toml:"dial_timeout"`
WriteTimeout time.Duration `toml:"write_timeout"`
// Retries is how many times a failed send is retried before the job is
// marked failed.
Retries int `toml:"retries"`
RetryDelay time.Duration `toml:"retry_delay"`
}
// QueueConfig configures the print queue.
type QueueConfig struct {
// Size is the number of jobs that may wait to be printed.
Size int `toml:"size"`
// History is the number of finished jobs whose status is kept.
History int `toml:"history"`
}
// ImagesConfig configures image elements.
type ImagesConfig struct {
Timeout time.Duration `toml:"timeout"`
MaxBytes int64 `toml:"max_bytes"`
// MaxPixels caps the decoded image size to guard against decompression
// bombs.
MaxPixels int `toml:"max_pixels"`
// MaxHeight caps the printed image height in dots after scaling.
MaxHeight int `toml:"max_height"`
// AllowPrivateNetworks permits fetching from loopback, private and
// link-local addresses.
AllowPrivateNetworks bool `toml:"allow_private_networks"`
// AllowedHosts, when non-empty, restricts fetching to these hosts. Listed
// hosts may resolve to private addresses.
AllowedHosts []string `toml:"allowed_hosts"`
}
// SentryConfig configures error reporting.
type SentryConfig struct {
DSN string `toml:"dsn"`
Environment string `toml:"environment"`
Debug bool `toml:"debug"`
}
// LogConfig configures structured logging.
type LogConfig struct {
Level string `toml:"level"`
Format string `toml:"format"`
}
// Default returns a configuration with every optional setting at its
// default. API.Secret and Printer.Address have no defaults.
func Default() Config {
return Config{
WebServer: WebServerConfig{
BindIP: "127.0.0.1",
Port: 8080,
RateLimit: 60,
RateWindow: time.Minute,
TrustedProxies: []string{"127.0.0.1", "::1"},
ProxyHeader: "X-Real-IP",
BodyLimit: 4 << 20,
ReadTimeout: 15 * time.Second,
WriteTimeout: 15 * time.Second,
IdleTimeout: 60 * time.Second,
},
Printer: PrinterConfig{
Port: 9100,
Model: "tm-t20",
CodePage: "cp437",
DialTimeout: 5 * time.Second,
WriteTimeout: 30 * time.Second,
Retries: 3,
RetryDelay: time.Second,
},
Queue: QueueConfig{
Size: 100,
History: 1000,
},
Images: ImagesConfig{
Timeout: 10 * time.Second,
MaxBytes: 10 << 20,
MaxPixels: 25_000_000,
MaxHeight: 4000,
},
Sentry: SentryConfig{
Environment: "production",
},
Log: LogConfig{
Level: "info",
Format: LogFormatText,
},
}
}
// Load reads the TOML file at path on top of [Default] and validates the
// result. Keys not recognised by Config are reported as errors so typos do not
// silently fall back to defaults. When sentry.dsn is unset, the SENTRY_DSN
// environment variable is used.
func Load(path string) (*Config, error) {
cfg := Default()
meta, err := toml.DecodeFile(path, &cfg)
if err != nil {
return nil, fmt.Errorf("reading config %s: %w", path, err)
}
if undecoded := meta.Undecoded(); len(undecoded) > 0 {
keys := make([]string, len(undecoded))
for i, key := range undecoded {
keys[i] = key.String()
}
return nil, fmt.Errorf("config %s: unknown keys: %s", path, strings.Join(keys, ", "))
}
if cfg.Sentry.DSN == "" {
cfg.Sentry.DSN = os.Getenv("SENTRY_DSN")
}
if err := cfg.Validate(); err != nil {
return nil, fmt.Errorf("config %s: %w", path, err)
}
return &cfg, nil
}
// Validate reports every problem with the configuration.
func (c *Config) Validate() error {
var errs []error
check := func(ok bool, format string, args ...any) {
if !ok {
errs = append(errs, fmt.Errorf(format, args...))
}
}
ws := c.WebServer
_, ipErr := netip.ParseAddr(ws.BindIP)
check(ipErr == nil, "webserver.bind_ip: %q is not an IP address", ws.BindIP)
check(validPort(ws.Port), "webserver.port: %d is out of range 1-65535", ws.Port)
check(ws.RateLimit > 0, "webserver.rate_limit must be positive")
check(ws.RateWindow > 0, "webserver.rate_window must be positive")
check(ws.BodyLimit > 0, "webserver.body_limit must be positive")
check(ws.ReadTimeout > 0 && ws.WriteTimeout > 0 && ws.IdleTimeout > 0,
"webserver read/write/idle timeouts must be positive")
for _, proxy := range ws.TrustedProxies {
check(validIPOrPrefix(proxy), "webserver.trusted_proxies: %q is not an IP or CIDR", proxy)
}
check(len(c.API.Secret) >= MinSecretLength,
"api.secret must be at least %d bytes (generate one with `uberbringer secret`)", MinSecretLength)
p := c.Printer
check(p.Address != "", "printer.address is required")
check(validPort(p.Port), "printer.port: %d is out of range 1-65535", p.Port)
check(p.PaperWidth >= 0, "printer.paper_width must not be negative")
check(p.Columns >= 0, "printer.columns must not be negative")
check(p.DialTimeout > 0 && p.WriteTimeout > 0, "printer dial/write timeouts must be positive")
check(p.Retries >= 0, "printer.retries must not be negative")
check(p.RetryDelay > 0, "printer.retry_delay must be positive")
check(c.Queue.Size > 0, "queue.size must be positive")
check(c.Queue.History >= 0, "queue.history must not be negative")
img := c.Images
check(img.Timeout > 0, "images.timeout must be positive")
check(img.MaxBytes > 0, "images.max_bytes must be positive")
check(img.MaxPixels > 0, "images.max_pixels must be positive")
check(img.MaxHeight > 0, "images.max_height must be positive")
check(slices.Contains([]string{"debug", "info", "warn", "error"}, c.Log.Level),
"log.level: %q must be one of debug, info, warn, error", c.Log.Level)
check(c.Log.Format == LogFormatText || c.Log.Format == LogFormatJSON,
"log.format: %q must be %q or %q", c.Log.Format, LogFormatText, LogFormatJSON)
return errors.Join(errs...)
}
func validPort(port int) bool {
return port >= 1 && port <= 65535
}
func validIPOrPrefix(s string) bool {
if _, err := netip.ParseAddr(s); err == nil {
return true
}
_, err := netip.ParsePrefix(s)
return err == nil
}
+173
View File
@@ -0,0 +1,173 @@
package config_test
import (
"os"
"path/filepath"
"strings"
"testing"
"time"
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/config"
)
const validSecret = "xTw8qdxTy7Ng4DiptTqmeVy506xWLht3OhFn4kdawmM="
func writeConfig(t *testing.T, body string) string {
t.Helper()
path := filepath.Join(t.TempDir(), "config.toml")
if err := os.WriteFile(path, []byte(body), 0o600); err != nil {
t.Fatal(err)
}
return path
}
func TestLoadLegacyConfigGetsDefaults(t *testing.T) {
t.Setenv("SENTRY_DSN", "")
// The exact shape written by the original install.sh, plus a printer.
path := writeConfig(t, `
[webserver]
bind_ip = "127.0.0.1"
port = 8080
[api]
secret = "`+validSecret+`"
[printer]
address = "192.168.1.245"
`)
cfg, err := config.Load(path)
if err != nil {
t.Fatalf("Load: %v", err)
}
if cfg.Printer.Port != 9100 || cfg.Printer.Model != "tm-t20" || cfg.Printer.CodePage != "cp437" {
t.Errorf("printer defaults not applied: %+v", cfg.Printer)
}
if cfg.WebServer.RateWindow != time.Minute || cfg.Queue.Size != 100 {
t.Errorf("defaults not applied: %+v %+v", cfg.WebServer, cfg.Queue)
}
if cfg.Images.AllowPrivateNetworks {
t.Error("private networks must be blocked by default")
}
}
func TestLoadOverridesAndDurations(t *testing.T) {
path := writeConfig(t, `
[api]
secret = "`+validSecret+`"
[printer]
address = "printer.lan"
dial_timeout = "750ms"
paper_width = 384
[images]
allowed_hosts = ["images.lan"]
[sentry]
dsn = "https://key@sentry.example/1"
[log]
format = "json"
`)
cfg, err := config.Load(path)
if err != nil {
t.Fatalf("Load: %v", err)
}
if cfg.Printer.DialTimeout != 750*time.Millisecond {
t.Errorf("DialTimeout = %v, want 750ms", cfg.Printer.DialTimeout)
}
if cfg.Printer.PaperWidth != 384 || cfg.Log.Format != "json" {
t.Errorf("overrides not applied: %+v %+v", cfg.Printer, cfg.Log)
}
if len(cfg.Images.AllowedHosts) != 1 || cfg.Images.AllowedHosts[0] != "images.lan" {
t.Errorf("AllowedHosts = %v", cfg.Images.AllowedHosts)
}
if cfg.Sentry.DSN != "https://key@sentry.example/1" {
t.Errorf("DSN = %q", cfg.Sentry.DSN)
}
}
func TestLoadSentryDSNFromEnvironment(t *testing.T) {
t.Setenv("SENTRY_DSN", "https://env@sentry.example/2")
path := writeConfig(t, "[api]\nsecret = \""+validSecret+"\"\n[printer]\naddress = \"p\"\n")
cfg, err := config.Load(path)
if err != nil {
t.Fatalf("Load: %v", err)
}
if cfg.Sentry.DSN != "https://env@sentry.example/2" {
t.Errorf("DSN = %q, want value from SENTRY_DSN", cfg.Sentry.DSN)
}
}
func TestLoadErrors(t *testing.T) {
tests := []struct {
name string
body string
wantErr string
}{
{
name: "missing secret",
body: "[printer]\naddress = \"p\"\n",
wantErr: "api.secret must be at least 32 bytes",
},
{
name: "short secret",
body: "[api]\nsecret = \"short\"\n[printer]\naddress = \"p\"\n",
wantErr: "api.secret must be at least 32 bytes",
},
{
name: "missing printer address",
body: "[api]\nsecret = \"" + validSecret + "\"\n",
wantErr: "printer.address is required",
},
{
name: "unknown key",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\nadress = \"typo\"\n",
wantErr: "unknown keys: printer.adress",
},
{
name: "bad duration",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\ndial_timeout = \"soon\"\n",
wantErr: "dial_timeout",
},
{
name: "bad trusted proxy",
body: "[webserver]\ntrusted_proxies = [\"nginx\"]\n[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n",
wantErr: `"nginx" is not an IP or CIDR`,
},
{
name: "bad log level",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[log]\nlevel = \"loud\"\n",
wantErr: "log.level",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
_, err := config.Load(writeConfig(t, tt.body))
if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
t.Fatalf("Load error = %v, want it to contain %q", err, tt.wantErr)
}
})
}
}
// The documented example must stay loadable: every key in it must exist.
func TestExampleConfigLoads(t *testing.T) {
example, err := os.ReadFile(filepath.Join("..", "..", "..", "configs", "config.example.toml"))
if err != nil {
t.Fatal(err)
}
body := strings.Replace(string(example), `secret = ""`, `secret = "`+validSecret+`"`, 1)
body = strings.Replace(body, `address = ""`, `address = "192.168.1.245"`, 1)
cfg, err := config.Load(writeConfig(t, body))
if err != nil {
t.Fatalf("example config: %v", err)
}
if def := config.Default(); cfg.WebServer.RateLimit != def.WebServer.RateLimit ||
cfg.Images.MaxBytes != def.Images.MaxBytes || cfg.Printer.Model != def.Printer.Model {
t.Error("example config values drifted from the defaults it documents")
}
}
func TestLoadMissingFile(t *testing.T) {
_, err := config.Load(filepath.Join(t.TempDir(), "nope.toml"))
if err == nil {
t.Fatal("expected error for missing file")
}
}
+211
View File
@@ -0,0 +1,211 @@
package escpos
import (
"fmt"
"strings"
)
// Symbology identifies a one-dimensional barcode type. Values are the GS k
// function B type codes.
type Symbology byte
// Supported barcode symbologies.
const (
UPCA Symbology = 65
UPCE Symbology = 66
EAN13 Symbology = 67
EAN8 Symbology = 68
CODE39 Symbology = 69
CODE128 Symbology = 73
)
// HRIPosition places the human-readable interpretation (the digits) relative
// to a barcode.
type HRIPosition byte
// HRIPosition values for GS H.
const (
HRINone HRIPosition = 0
HRIAbove HRIPosition = 1
HRIBelow HRIPosition = 2
HRIBoth HRIPosition = 3
)
// Barcode module width limits for GS w.
const (
MinBarcodeWidth = 2
MaxBarcodeWidth = 6
)
const code39Charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ -.$/+%"
// ParseSymbology returns the symbology named by name, e.g. "ean13".
func ParseSymbology(name string) (Symbology, error) {
switch strings.ToLower(strings.TrimSpace(name)) {
case "upca", "upc-a":
return UPCA, nil
case "upce", "upc-e":
return UPCE, nil
case "ean13", "ean-13", "jan13":
return EAN13, nil
case "ean8", "ean-8", "jan8":
return EAN8, nil
case "code39", "code-39":
return CODE39, nil
case "code128", "code-128":
return CODE128, nil
}
return 0, fmt.Errorf("%w: unknown barcode symbology %q", ErrInvalidArgument, name)
}
// String returns the canonical symbology name.
func (s Symbology) String() string {
switch s {
case UPCA:
return "upca"
case UPCE:
return "upce"
case EAN13:
return "ean13"
case EAN8:
return "ean8"
case CODE39:
return "code39"
case CODE128:
return "code128"
}
return fmt.Sprintf("Symbology(%d)", byte(s))
}
// ValidateBarcode reports whether data can be encoded as sym. Where data
// includes the check digit, the check digit is verified.
func ValidateBarcode(sym Symbology, data string) error {
invalid := func(format string, args ...any) error {
return fmt.Errorf("%w: %s: "+format, append([]any{ErrInvalidArgument, sym}, args...)...)
}
switch sym {
case UPCA:
if !isDigits(data) || (len(data) != 11 && len(data) != 12) {
return invalid("want 11 or 12 digits")
}
if len(data) == 12 && !validCheckDigit(data) {
return invalid("check digit is wrong")
}
case UPCE:
switch {
case !isDigits(data):
return invalid("want digits only")
case len(data) >= 6 && len(data) <= 8:
case (len(data) == 11 || len(data) == 12) && data[0] == '0':
default:
return invalid("want 6-8 digits, or 11-12 digits starting with 0")
}
case EAN13:
if !isDigits(data) || (len(data) != 12 && len(data) != 13) {
return invalid("want 12 or 13 digits")
}
if len(data) == 13 && !validCheckDigit(data) {
return invalid("check digit is wrong")
}
case EAN8:
if !isDigits(data) || (len(data) != 7 && len(data) != 8) {
return invalid("want 7 or 8 digits")
}
if len(data) == 8 && !validCheckDigit(data) {
return invalid("check digit is wrong")
}
case CODE39:
if len(data) < 1 || len(data) > 255 {
return invalid("want 1-255 characters")
}
for _, r := range data {
if !strings.ContainsRune(code39Charset, r) {
return invalid("character %q not allowed (use 0-9, A-Z, space and -.$/+%%)", r)
}
}
case CODE128:
if len(data) < 1 {
return invalid("data is empty")
}
for _, r := range data {
if r < 0x20 || r > 0x7E {
return invalid("character %q not allowed (printable ASCII only)", r)
}
}
if len(code128Payload(data)) > 255 {
return invalid("data is too long")
}
default:
return fmt.Errorf("%w: unknown barcode symbology %d", ErrInvalidArgument, byte(sym))
}
return nil
}
// BarcodeHeight sets the barcode height in dots (GS h n).
func (b *Builder) BarcodeHeight(dots uint8) {
b.buf.Write([]byte{gs, 'h', dots})
}
// BarcodeWidth sets the barcode module width, [MinBarcodeWidth] to
// [MaxBarcodeWidth] (GS w n).
func (b *Builder) BarcodeWidth(module int) error {
if module < MinBarcodeWidth || module > MaxBarcodeWidth {
return fmt.Errorf("%w: barcode width %d must be within %d-%d",
ErrInvalidArgument, module, MinBarcodeWidth, MaxBarcodeWidth)
}
b.buf.Write([]byte{gs, 'w', byte(module)})
return nil
}
// BarcodeHRI sets where the human-readable digits are printed (GS H n).
func (b *Builder) BarcodeHRI(pos HRIPosition) {
b.buf.Write([]byte{gs, 'H', byte(pos)})
}
// Barcode validates data and appends a barcode (GS k m n d1...dn). CODE128
// data is printed in code set B, so callers pass plain text.
func (b *Builder) Barcode(sym Symbology, data string) error {
if err := ValidateBarcode(sym, data); err != nil {
return err
}
payload := []byte(data)
if sym == CODE128 {
payload = code128Payload(data)
}
b.buf.Write([]byte{gs, 'k', byte(sym), byte(len(payload))})
b.buf.Write(payload)
return nil
}
// code128Payload selects code set B and escapes '{', which the printer
// treats as the start of a code set or function character.
func code128Payload(data string) []byte {
return []byte("{B" + strings.ReplaceAll(data, "{", "{{"))
}
func isDigits(s string) bool {
if s == "" {
return false
}
for i := range len(s) {
if s[i] < '0' || s[i] > '9' {
return false
}
}
return true
}
// validCheckDigit verifies the GS1 mod-10 check digit in the last position of
// a UPC-A, EAN-13 or EAN-8 number.
func validCheckDigit(code string) bool {
sum := 0
body := code[:len(code)-1]
for i := range len(body) {
digit := int(body[len(body)-1-i] - '0')
if i%2 == 0 {
digit *= 3
}
sum += digit
}
return (10-sum%10)%10 == int(code[len(code)-1]-'0')
}
+181
View File
@@ -0,0 +1,181 @@
// Package escpos builds Epson ESC/POS command streams for thermal receipt
// printers.
//
// A [Builder] accumulates commands in memory. Callers send [Builder.Bytes] to
// the printer in a single write, so an invalid element never leaves a
// half-printed receipt. Commands follow the Epson ESC/POS Application
// Programming Guide; byte values are named by the control characters the
// specification uses (ESC, GS, DLE).
package escpos
import (
"bytes"
"errors"
"fmt"
)
// Control characters that introduce ESC/POS commands.
const (
ht byte = 0x09
lf byte = 0x0A
dle byte = 0x10
eot byte = 0x04
esc byte = 0x1B
gs byte = 0x1D
)
// MaxCharacterScale is the largest character width or height multiplier
// supported by GS !.
const MaxCharacterScale = 8
// ErrInvalidArgument is wrapped by every validation error the package
// returns.
var ErrInvalidArgument = errors.New("escpos: invalid argument")
// Justification aligns text, barcodes and QR codes on the line.
type Justification byte
// Justification values for ESC a.
const (
JustifyLeft Justification = 0
JustifyCenter Justification = 1
JustifyRight Justification = 2
)
// Font selects one of the printer's built-in character fonts.
type Font byte
// Font values for ESC M.
const (
FontA Font = 0
FontB Font = 1
)
// Underline selects the underline thickness.
type Underline byte
// Underline values for ESC -.
const (
UnderlineNone Underline = 0
UnderlineThin Underline = 1
UnderlineThick Underline = 2
)
// CutMode selects a full or partial paper cut.
type CutMode byte
// CutMode values for GS V function B, which feeds the paper to the cutting
// position before cutting so the last printed line is not lost.
const (
CutFull CutMode = 65
CutPartial CutMode = 66
)
// Builder accumulates an ESC/POS command stream. The zero value is ready to
// use. A Builder is not safe for concurrent use.
type Builder struct {
buf bytes.Buffer
}
// Bytes returns the accumulated command stream. The slice aliases the
// Builder's buffer and is valid until the next write.
func (b *Builder) Bytes() []byte {
return b.buf.Bytes()
}
// Len returns the number of accumulated bytes.
func (b *Builder) Len() int {
return b.buf.Len()
}
// Raw appends p unchanged. It is the escape hatch for commands the Builder
// does not model.
func (b *Builder) Raw(p []byte) {
b.buf.Write(p)
}
// Text appends already-encoded character data. Use [CodePage.Encode] to
// convert UTF-8 text first.
func (b *Builder) Text(encoded []byte) {
b.buf.Write(encoded)
}
// Initialize resets the printer to its power-on settings (ESC @).
func (b *Builder) Initialize() {
b.buf.Write([]byte{esc, '@'})
}
// LineFeed prints the line buffer and advances one line (LF).
func (b *Builder) LineFeed() {
b.buf.WriteByte(lf)
}
// Feed prints the line buffer and advances lines lines (ESC d n).
func (b *Builder) Feed(lines uint8) {
b.buf.Write([]byte{esc, 'd', lines})
}
// LineSpacing sets the line spacing in motion units (ESC 3 n).
func (b *Builder) LineSpacing(units uint8) {
b.buf.Write([]byte{esc, '3', units})
}
// DefaultLineSpacing restores the default line spacing (ESC 2).
func (b *Builder) DefaultLineSpacing() {
b.buf.Write([]byte{esc, '2'})
}
// Bold turns emphasized printing on or off (ESC E n).
func (b *Builder) Bold(on bool) {
b.buf.Write([]byte{esc, 'E', boolByte(on)})
}
// Underline sets the underline mode (ESC - n).
func (b *Builder) Underline(u Underline) {
b.buf.Write([]byte{esc, '-', byte(u)})
}
// Reverse turns white-on-black printing on or off (GS B n).
func (b *Builder) Reverse(on bool) {
b.buf.Write([]byte{gs, 'B', boolByte(on)})
}
// Justify sets the alignment (ESC a n). It takes effect at the start of the
// next line.
func (b *Builder) Justify(j Justification) {
b.buf.Write([]byte{esc, 'a', byte(j)})
}
// Font selects the character font (ESC M n).
func (b *Builder) Font(f Font) {
b.buf.Write([]byte{esc, 'M', byte(f)})
}
// Size sets the character width and height multipliers, each 1 to
// [MaxCharacterScale] (GS ! n).
func (b *Builder) Size(width, height int) error {
if width < 1 || width > MaxCharacterScale || height < 1 || height > MaxCharacterScale {
return fmt.Errorf("%w: character size %dx%d must be within 1-%d",
ErrInvalidArgument, width, height, MaxCharacterScale)
}
b.buf.Write([]byte{gs, '!', byte(width-1)<<4 | byte(height-1)})
return nil
}
// SelectCodePage selects the character table used to print text (ESC t n).
func (b *Builder) SelectCodePage(cp CodePage) {
b.buf.Write([]byte{esc, 't', cp.table()})
}
// Cut feeds the paper to the cutter plus feed motion units and cuts it
// (GS V m n).
func (b *Builder) Cut(mode CutMode, feed uint8) {
b.buf.Write([]byte{gs, 'V', byte(mode), feed})
}
func boolByte(on bool) byte {
if on {
return 1
}
return 0
}
+112
View File
@@ -0,0 +1,112 @@
package escpos
import (
"fmt"
"strings"
"unicode/utf8"
"golang.org/x/text/encoding/charmap"
)
// CodePage is a printer character table. It ties the ESC t table number the
// printer understands to the character map used to transcode UTF-8 text, so
// the two can never disagree.
type CodePage int
// Supported code pages. CodePage437 is the Epson factory default.
const (
CodePage437 CodePage = iota + 1
CodePage850
CodePage858
CodePage1252
)
// ParseCodePage returns the code page named by name, e.g. "cp437".
func ParseCodePage(name string) (CodePage, error) {
switch strings.ToLower(strings.TrimSpace(name)) {
case "cp437", "437", "pc437":
return CodePage437, nil
case "cp850", "850", "pc850":
return CodePage850, nil
case "cp858", "858", "pc858":
return CodePage858, nil
case "cp1252", "1252", "wpc1252", "windows-1252":
return CodePage1252, nil
}
return 0, fmt.Errorf("%w: unknown code page %q (want cp437, cp850, cp858 or cp1252)",
ErrInvalidArgument, name)
}
// String returns the canonical code page name.
func (cp CodePage) String() string {
switch cp {
case CodePage437:
return "cp437"
case CodePage850:
return "cp850"
case CodePage858:
return "cp858"
case CodePage1252:
return "cp1252"
}
return fmt.Sprintf("CodePage(%d)", int(cp))
}
// table returns the ESC t table number for cp.
func (cp CodePage) table() byte {
switch cp {
case CodePage850:
return 2
case CodePage858:
return 19
case CodePage1252:
return 16
}
return 0 // PC437, also the fallback for an invalid CodePage.
}
func (cp CodePage) charmap() *charmap.Charmap {
switch cp {
case CodePage850:
return charmap.CodePage850
case CodePage858:
return charmap.CodePage858
case CodePage1252:
return charmap.Windows1252
}
return charmap.CodePage437
}
// Encode transcodes UTF-8 text to cp, one byte per rune. Runes the code page
// cannot represent become '?'. Control characters other than newline and tab
// are dropped, because the printer would interpret them as commands.
func (cp CodePage) Encode(s string) []byte {
cm := cp.charmap()
out := make([]byte, 0, len(s))
for _, r := range s {
switch {
case r == '\n' || r == '\t':
out = append(out, byte(r))
case IsControl(r):
// Dropped: control bytes would be read as printer commands.
case r < utf8.RuneSelf:
out = append(out, byte(r))
default:
c, ok := cm.EncodeRune(r)
if !ok || c < 0x20 || c == 0x7F {
c = '?'
}
out = append(out, c)
}
}
return out
}
// IsControl reports whether r is a control character that [CodePage.Encode]
// drops. Newline and tab are not reported.
func IsControl(r rune) bool {
if r == '\n' || r == '\t' {
return false
}
return r < 0x20 || r == 0x7F || (r >= 0x80 && r < 0xA0) || r == utf8.RuneError
}
+426
View File
@@ -0,0 +1,426 @@
package escpos_test
import (
"bytes"
"errors"
"image"
"image/color"
"strings"
"testing"
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/escpos"
)
// Byte-exact checks against the Epson ESC/POS command reference.
func TestCommands(t *testing.T) {
tests := []struct {
name string
build func(b *escpos.Builder)
want []byte
}{
{"initialize", func(b *escpos.Builder) { b.Initialize() }, []byte{0x1B, 0x40}},
{"line feed", func(b *escpos.Builder) { b.LineFeed() }, []byte{0x0A}},
{"feed 3", func(b *escpos.Builder) { b.Feed(3) }, []byte{0x1B, 0x64, 3}},
{"line spacing", func(b *escpos.Builder) { b.LineSpacing(30) }, []byte{0x1B, 0x33, 30}},
{"default line spacing", func(b *escpos.Builder) { b.DefaultLineSpacing() }, []byte{0x1B, 0x32}},
{"bold on", func(b *escpos.Builder) { b.Bold(true) }, []byte{0x1B, 0x45, 1}},
{"bold off", func(b *escpos.Builder) { b.Bold(false) }, []byte{0x1B, 0x45, 0}},
{"underline thick", func(b *escpos.Builder) { b.Underline(escpos.UnderlineThick) }, []byte{0x1B, 0x2D, 2}},
{"reverse", func(b *escpos.Builder) { b.Reverse(true) }, []byte{0x1D, 0x42, 1}},
{"justify center", func(b *escpos.Builder) { b.Justify(escpos.JustifyCenter) }, []byte{0x1B, 0x61, 1}},
{"font b", func(b *escpos.Builder) { b.Font(escpos.FontB) }, []byte{0x1B, 0x4D, 1}},
{"code page 437", func(b *escpos.Builder) { b.SelectCodePage(escpos.CodePage437) }, []byte{0x1B, 0x74, 0}},
{"code page 850", func(b *escpos.Builder) { b.SelectCodePage(escpos.CodePage850) }, []byte{0x1B, 0x74, 2}},
{"code page 858", func(b *escpos.Builder) { b.SelectCodePage(escpos.CodePage858) }, []byte{0x1B, 0x74, 19}},
{"code page 1252", func(b *escpos.Builder) { b.SelectCodePage(escpos.CodePage1252) }, []byte{0x1B, 0x74, 16}},
{"partial cut", func(b *escpos.Builder) { b.Cut(escpos.CutPartial, 0) }, []byte{0x1D, 0x56, 66, 0}},
{"full cut", func(b *escpos.Builder) { b.Cut(escpos.CutFull, 5) }, []byte{0x1D, 0x56, 65, 5}},
{"barcode height", func(b *escpos.Builder) { b.BarcodeHeight(80) }, []byte{0x1D, 0x68, 80}},
{"barcode hri", func(b *escpos.Builder) { b.BarcodeHRI(escpos.HRIBelow) }, []byte{0x1D, 0x48, 2}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var b escpos.Builder
tt.build(&b)
if !bytes.Equal(b.Bytes(), tt.want) {
t.Errorf("got % X, want % X", b.Bytes(), tt.want)
}
})
}
}
func TestSize(t *testing.T) {
tests := []struct {
width, height int
want byte
wantErr bool
}{
{1, 1, 0x00, false},
{2, 2, 0x11, false},
{8, 8, 0x77, false},
{3, 1, 0x20, false},
{1, 4, 0x03, false},
{0, 1, 0, true},
{9, 1, 0, true},
{1, 9, 0, true},
}
for _, tt := range tests {
var b escpos.Builder
err := b.Size(tt.width, tt.height)
if tt.wantErr {
if !errors.Is(err, escpos.ErrInvalidArgument) || b.Len() != 0 {
t.Errorf("Size(%d,%d): err=%v len=%d, want ErrInvalidArgument and nothing written",
tt.width, tt.height, err, b.Len())
}
continue
}
want := []byte{0x1D, 0x21, tt.want}
if err != nil || !bytes.Equal(b.Bytes(), want) {
t.Errorf("Size(%d,%d) = % X, %v; want % X", tt.width, tt.height, b.Bytes(), err, want)
}
}
}
func TestBarcodeWidthUsesWidthCommand(t *testing.T) {
var b escpos.Builder
if err := b.BarcodeWidth(3); err != nil {
t.Fatal(err)
}
if want := []byte{0x1D, 0x77, 3}; !bytes.Equal(b.Bytes(), want) {
t.Errorf("got % X, want % X", b.Bytes(), want)
}
if err := b.BarcodeWidth(7); !errors.Is(err, escpos.ErrInvalidArgument) {
t.Errorf("BarcodeWidth(7) err = %v, want ErrInvalidArgument", err)
}
}
func TestBarcode(t *testing.T) {
tests := []struct {
name string
sym escpos.Symbology
data string
want []byte
wantErr bool
}{
{name: "ean13 with check digit", sym: escpos.EAN13, data: "4006381333931",
want: append([]byte{0x1D, 0x6B, 67, 13}, "4006381333931"...)},
{name: "ean13 without check digit", sym: escpos.EAN13, data: "400638133393",
want: append([]byte{0x1D, 0x6B, 67, 12}, "400638133393"...)},
{name: "ean13 wrong check digit", sym: escpos.EAN13, data: "4006381333932", wantErr: true},
{name: "ean13 letters", sym: escpos.EAN13, data: "40063813339A", wantErr: true},
{name: "ean8", sym: escpos.EAN8, data: "96385074",
want: append([]byte{0x1D, 0x6B, 68, 8}, "96385074"...)},
{name: "ean8 wrong length", sym: escpos.EAN8, data: "123", wantErr: true},
{name: "upca", sym: escpos.UPCA, data: "036000291452",
want: append([]byte{0x1D, 0x6B, 65, 12}, "036000291452"...)},
{name: "upce short", sym: escpos.UPCE, data: "123456",
want: append([]byte{0x1D, 0x6B, 66, 6}, "123456"...)},
{name: "upce long must start with 0", sym: escpos.UPCE, data: "12345678901", wantErr: true},
{name: "code39", sym: escpos.CODE39, data: "ABC-123",
want: append([]byte{0x1D, 0x6B, 69, 7}, "ABC-123"...)},
{name: "code39 lowercase", sym: escpos.CODE39, data: "abc", wantErr: true},
{name: "code128 code set B", sym: escpos.CODE128, data: "Hello-1",
want: append([]byte{0x1D, 0x6B, 73, 9}, "{BHello-1"...)},
{name: "code128 escapes brace", sym: escpos.CODE128, data: "a{b",
want: append([]byte{0x1D, 0x6B, 73, 6}, "{Ba{{b"...)},
{name: "code128 non-ascii", sym: escpos.CODE128, data: "Grüße", wantErr: true},
{name: "code128 too long", sym: escpos.CODE128, data: strings.Repeat("x", 254), wantErr: true},
{name: "empty", sym: escpos.CODE128, data: "", wantErr: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var b escpos.Builder
err := b.Barcode(tt.sym, tt.data)
if tt.wantErr {
if !errors.Is(err, escpos.ErrInvalidArgument) || b.Len() != 0 {
t.Fatalf("err=%v len=%d, want ErrInvalidArgument and nothing written", err, b.Len())
}
return
}
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(b.Bytes(), tt.want) {
t.Errorf("got % X, want % X", b.Bytes(), tt.want)
}
})
}
}
func TestQRCode(t *testing.T) {
var b escpos.Builder
if err := b.QRCode([]byte("hi"), 6, escpos.QRCorrectionM); err != nil {
t.Fatal(err)
}
want := []byte{
0x1D, 0x28, 0x6B, 4, 0, 0x31, 0x41, 0x32, 0, // model 2
0x1D, 0x28, 0x6B, 3, 0, 0x31, 0x43, 6, // module size
0x1D, 0x28, 0x6B, 3, 0, 0x31, 0x45, 49, // correction M
0x1D, 0x28, 0x6B, 5, 0, 0x31, 0x50, 0x30, 'h', 'i', // store
0x1D, 0x28, 0x6B, 3, 0, 0x31, 0x51, 0x30, // print
}
if !bytes.Equal(b.Bytes(), want) {
t.Errorf("got % X\nwant % X", b.Bytes(), want)
}
}
func TestQRCodeStoreLengthUsesHighByte(t *testing.T) {
var b escpos.Builder
data := bytes.Repeat([]byte{'x'}, 300)
if err := b.QRCode(data, 4, escpos.QRCorrectionL); err != nil {
t.Fatal(err)
}
store := []byte{0x1D, 0x28, 0x6B, byte(303 & 0xFF), byte(303 >> 8), 0x31, 0x50, 0x30}
if !bytes.Contains(b.Bytes(), store) {
t.Errorf("store header % X not found", store)
}
}
func TestQRCodeRejects(t *testing.T) {
tests := map[string]func(b *escpos.Builder) error{
"empty": func(b *escpos.Builder) error { return b.QRCode(nil, 4, escpos.QRCorrectionM) },
"too long": func(b *escpos.Builder) error {
return b.QRCode(make([]byte, escpos.MaxQRData+1), 4, escpos.QRCorrectionM)
},
"module too big": func(b *escpos.Builder) error { return b.QRCode([]byte("x"), 17, escpos.QRCorrectionM) },
"bad correction": func(b *escpos.Builder) error { return b.QRCode([]byte("x"), 4, 47) },
"module too small": func(b *escpos.Builder) error { return b.QRCode([]byte("x"), 0, escpos.QRCorrectionM) },
}
for name, call := range tests {
t.Run(name, func(t *testing.T) {
var b escpos.Builder
if err := call(&b); !errors.Is(err, escpos.ErrInvalidArgument) || b.Len() != 0 {
t.Errorf("err=%v len=%d, want ErrInvalidArgument and nothing written", err, b.Len())
}
})
}
}
func TestEncodeCodePage437(t *testing.T) {
tests := []struct {
name string
in string
want []byte
}{
{"ascii", "Hello, World!", []byte("Hello, World!")},
{"box drawing", "┌─┐│└┘", []byte{0xDA, 0xC4, 0xBF, 0xB3, 0xC0, 0xD9}},
{"shading", "░▒▓█", []byte{0xB0, 0xB1, 0xB2, 0xDB}},
{"double box", "╔═╗", []byte{0xC9, 0xCD, 0xBB}},
{"umlauts", "Über ä ö", []byte{0x9A, 'b', 'e', 'r', ' ', 0x84, ' ', 0x94}},
{"symbols", "£°±", []byte{0x9C, 0xF8, 0xF1}},
{"unmappable emoji", "hi 🎉", []byte("hi ?")},
{"keeps newline and tab", "a\nb\tc", []byte("a\nb\tc")},
// ESC is dropped, so the '@' that followed it is harmless text.
{"drops control characters", "a\x1b@b\x00c\r", []byte("a@bc")},
{"smiley maps below 0x20 so becomes ?", "☺", []byte("?")},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := escpos.CodePage437.Encode(tt.in)
if !bytes.Equal(got, tt.want) {
t.Errorf("Encode(%q) = % X, want % X", tt.in, got, tt.want)
}
})
}
}
func TestEncodeOtherCodePages(t *testing.T) {
if got := escpos.CodePage858.Encode("€"); !bytes.Equal(got, []byte{0xD5}) {
t.Errorf("cp858 € = % X, want D5", got)
}
if got := escpos.CodePage1252.Encode("ێ"); !bytes.Equal(got, []byte{0x80, 0xE9}) {
t.Errorf("cp1252 ێ = % X, want 80 E9", got)
}
if got := escpos.CodePage850.Encode("é"); !bytes.Equal(got, []byte{0x82}) {
t.Errorf("cp850 é = % X, want 82", got)
}
}
func TestParseCodePage(t *testing.T) {
for _, name := range []string{"cp437", "CP437", "437"} {
if cp, err := escpos.ParseCodePage(name); err != nil || cp != escpos.CodePage437 {
t.Errorf("ParseCodePage(%q) = %v, %v", name, cp, err)
}
}
if _, err := escpos.ParseCodePage("ebcdic"); !errors.Is(err, escpos.ErrInvalidArgument) {
t.Errorf("ParseCodePage(ebcdic) err = %v", err)
}
}
func TestRasterImagePacksBitsAndPadsWidth(t *testing.T) {
// 10x2 image: row 0 is black at x=0 and x=9, row 1 is all white.
img := image.NewGray(image.Rect(0, 0, 10, 2))
for i := range img.Pix {
img.Pix[i] = 0xFF
}
img.SetGray(0, 0, color.Gray{})
img.SetGray(9, 0, color.Gray{})
var b escpos.Builder
if err := b.RasterImage(img); err != nil {
t.Fatal(err)
}
want := []byte{
0x1D, 0x76, 0x30, 0, 2, 0, 2, 0, // 2 bytes wide, 2 rows
0x80, 0x40, // row 0: bit for x=0, bit for x=9
0x00, 0x00, // row 1: padding stays white
}
if !bytes.Equal(b.Bytes(), want) {
t.Errorf("got % X, want % X", b.Bytes(), want)
}
}
func TestRasterImageRespectsBoundsOrigin(t *testing.T) {
// A sub-image whose bounds do not start at (0,0).
full := image.NewGray(image.Rect(0, 0, 16, 4))
for i := range full.Pix {
full.Pix[i] = 0xFF
}
full.SetGray(8, 2, color.Gray{})
sub := full.SubImage(image.Rect(8, 2, 16, 3))
var b escpos.Builder
if err := b.RasterImage(sub); err != nil {
t.Fatal(err)
}
want := []byte{0x1D, 0x76, 0x30, 0, 1, 0, 1, 0, 0x80}
if !bytes.Equal(b.Bytes(), want) {
t.Errorf("got % X, want % X", b.Bytes(), want)
}
}
func TestRasterImageBandsTallImages(t *testing.T) {
img := image.NewGray(image.Rect(0, 0, 8, 600))
var b escpos.Builder
if err := b.RasterImage(img); err != nil {
t.Fatal(err)
}
headers := []([]byte){
{0x1D, 0x76, 0x30, 0, 1, 0, 0x00, 0x01}, // 256 rows
{0x1D, 0x76, 0x30, 0, 1, 0, 0x00, 0x01}, // 256 rows
{0x1D, 0x76, 0x30, 0, 1, 0, 88, 0}, // 88 rows
}
out := b.Bytes()
for i, h := range headers {
if !bytes.HasPrefix(out, h) {
t.Fatalf("band %d header = % X, want % X", i, out[:min(8, len(out))], h)
}
rows := int(h[6]) | int(h[7])<<8
out = out[8+rows:]
}
if len(out) != 0 {
t.Errorf("%d trailing bytes", len(out))
}
}
func TestRasterImageTransparentIsWhite(t *testing.T) {
img := image.NewNRGBA(image.Rect(0, 0, 8, 1))
img.SetNRGBA(0, 0, color.NRGBA{A: 0}) // transparent black: paper shows
img.SetNRGBA(1, 0, color.NRGBA{A: 255}) // opaque black
img.SetNRGBA(2, 0, color.NRGBA{R: 255, G: 255, B: 255, A: 255})
var b escpos.Builder
if err := b.RasterImage(img); err != nil {
t.Fatal(err)
}
if got := b.Bytes()[8]; got != 0x40 {
t.Errorf("row byte = %08b, want 01000000", got)
}
}
func TestRasterImageEmpty(t *testing.T) {
var b escpos.Builder
if err := b.RasterImage(image.NewGray(image.Rect(0, 0, 0, 0))); !errors.Is(err, escpos.ErrInvalidArgument) {
t.Errorf("err = %v, want ErrInvalidArgument", err)
}
}
func TestStatusApply(t *testing.T) {
tests := []struct {
name string
resps map[escpos.StatusKind]byte
want escpos.Status
ready bool
}{
{
name: "healthy",
resps: map[escpos.StatusKind]byte{1: 0x12, 2: 0x12, 3: 0x12, 4: 0x12},
want: escpos.Status{Online: true},
ready: true,
},
{
name: "cover open",
resps: map[escpos.StatusKind]byte{1: 0x1A, 2: 0x16, 3: 0x12, 4: 0x12},
want: escpos.Status{CoverOpen: true},
},
{
name: "paper near end",
resps: map[escpos.StatusKind]byte{1: 0x12, 2: 0x12, 3: 0x12, 4: 0x1E},
want: escpos.Status{Online: true, PaperNearEnd: true},
ready: true,
},
{
name: "paper out",
resps: map[escpos.StatusKind]byte{1: 0x1A, 2: 0x32, 3: 0x12, 4: 0x72},
want: escpos.Status{PaperOut: true},
},
{
name: "cutter error",
resps: map[escpos.StatusKind]byte{1: 0x1A, 2: 0x52, 3: 0x1A, 4: 0x12},
want: escpos.Status{CutterError: true},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var s escpos.Status
for _, kind := range escpos.StatusKinds() {
if err := s.Apply(kind, tt.resps[kind]); err != nil {
t.Fatal(err)
}
}
if s != tt.want {
t.Errorf("status = %+v, want %+v", s, tt.want)
}
if s.Ready() != tt.ready {
t.Errorf("Ready() = %v, want %v", s.Ready(), tt.ready)
}
})
}
}
func TestStatusApplyRejectsGarbage(t *testing.T) {
var s escpos.Status
if err := s.Apply(escpos.StatusPrinter, 'H'); !errors.Is(err, escpos.ErrInvalidArgument) {
t.Errorf("err = %v, want ErrInvalidArgument", err)
}
}
func TestStatusRequest(t *testing.T) {
if got := escpos.StatusRequest(escpos.StatusPaper); !bytes.Equal(got, []byte{0x10, 0x04, 4}) {
t.Errorf("got % X", got)
}
}
func TestLookupProfile(t *testing.T) {
tests := []struct {
model string
wantName string
colsA, colsB int
}{
{"tm-t20ii", "tm-t20", 48, 64},
{"TM-T88V", "tm-t88", 42, 56},
{"generic-58mm", "generic-58mm", 32, 42},
}
for _, tt := range tests {
p, err := escpos.LookupProfile(tt.model)
if err != nil {
t.Fatalf("LookupProfile(%q): %v", tt.model, err)
}
if p.Name != tt.wantName || p.Columns(escpos.FontA) != tt.colsA || p.Columns(escpos.FontB) != tt.colsB {
t.Errorf("%q: name=%s cols=%d/%d, want %s %d/%d", tt.model, p.Name,
p.Columns(escpos.FontA), p.Columns(escpos.FontB), tt.wantName, tt.colsA, tt.colsB)
}
}
if _, err := escpos.LookupProfile("sol-802"); !errors.Is(err, escpos.ErrInvalidArgument) {
t.Errorf("unknown model err = %v", err)
}
}
+53
View File
@@ -0,0 +1,53 @@
package escpos
import (
"fmt"
"strings"
)
// Profile describes the printable area and fonts of a printer model.
type Profile struct {
// Name is the canonical model name.
Name string
// DotsPerLine is the printable width in dots.
DotsPerLine int
// FontAWidth and FontBWidth are the glyph widths in dots, including
// default character spacing, at scale 1.
FontAWidth int
FontBWidth int
}
// LookupProfile returns the profile for a model name such as "tm-t20". Common
// model variants (e.g. "tm-t20ii") resolve to their family.
func LookupProfile(model string) (Profile, error) {
switch strings.ToLower(strings.TrimSpace(model)) {
case "tm-t20", "tm-t20ii", "tm-t20iii", "tm-t20iv":
// 80 mm paper at 203 dpi: 48 columns of Font A, 64 of Font B.
return Profile{Name: "tm-t20", DotsPerLine: 576, FontAWidth: 12, FontBWidth: 9}, nil
case "tm-t88", "tm-t88iv", "tm-t88v", "tm-t88vi", "tm-t88vii":
// 80 mm paper at 180 dpi: 42 columns of Font A, 56 of Font B.
return Profile{Name: "tm-t88", DotsPerLine: 512, FontAWidth: 12, FontBWidth: 9}, nil
case "generic-80mm":
return Profile{Name: "generic-80mm", DotsPerLine: 576, FontAWidth: 12, FontBWidth: 9}, nil
case "generic-58mm":
// 58 mm paper at 203 dpi: 32 columns of Font A.
return Profile{Name: "generic-58mm", DotsPerLine: 384, FontAWidth: 12, FontBWidth: 9}, nil
}
return Profile{}, fmt.Errorf("%w: unknown printer model %q (want tm-t20, tm-t88, generic-80mm or generic-58mm)",
ErrInvalidArgument, model)
}
// GlyphWidth returns the width in dots of one character in font f at scale 1.
func (p Profile) GlyphWidth(f Font) int {
if f == FontB {
return p.FontBWidth
}
return p.FontAWidth
}
// Columns returns how many characters of font f at scale 1 fit on a line.
func (p Profile) Columns(f Font) int {
return p.DotsPerLine / p.GlyphWidth(f)
}
+70
View File
@@ -0,0 +1,70 @@
package escpos
import (
"fmt"
"strings"
)
// QRCorrection is the QR code error correction level. Higher levels survive
// more damage at the cost of a denser code.
type QRCorrection byte
// QRCorrection values for GS ( k function 169.
const (
QRCorrectionL QRCorrection = 48 // about 7% recovery
QRCorrectionM QRCorrection = 49 // about 15% recovery
QRCorrectionQ QRCorrection = 50 // about 25% recovery
QRCorrectionH QRCorrection = 51 // about 30% recovery
)
// QR code limits.
const (
MaxQRData = 7089 // bytes the printer's symbol storage accepts
MinQRModuleSize = 1
MaxQRModuleSize = 16
)
// ParseQRCorrection returns the correction level named by name: L, M, Q or H.
func ParseQRCorrection(name string) (QRCorrection, error) {
switch strings.ToUpper(strings.TrimSpace(name)) {
case "L":
return QRCorrectionL, nil
case "M":
return QRCorrectionM, nil
case "Q":
return QRCorrectionQ, nil
case "H":
return QRCorrectionH, nil
}
return 0, fmt.Errorf("%w: unknown QR correction level %q (want L, M, Q or H)", ErrInvalidArgument, name)
}
// QRCode appends a model 2 QR code holding data, printed with square modules
// moduleSize dots wide.
func (b *Builder) QRCode(data []byte, moduleSize int, level QRCorrection) error {
switch {
case len(data) == 0:
return fmt.Errorf("%w: QR data is empty", ErrInvalidArgument)
case len(data) > MaxQRData:
return fmt.Errorf("%w: QR data is %d bytes, limit is %d", ErrInvalidArgument, len(data), MaxQRData)
case moduleSize < MinQRModuleSize || moduleSize > MaxQRModuleSize:
return fmt.Errorf("%w: QR module size %d must be within %d-%d",
ErrInvalidArgument, moduleSize, MinQRModuleSize, MaxQRModuleSize)
case level < QRCorrectionL || level > QRCorrectionH:
return fmt.Errorf("%w: unknown QR correction level %d", ErrInvalidArgument, byte(level))
}
// Function 165: select model 2.
b.buf.Write([]byte{gs, '(', 'k', 4, 0, '1', 'A', '2', 0})
// Function 167: module size.
b.buf.Write([]byte{gs, '(', 'k', 3, 0, '1', 'C', byte(moduleSize)})
// Function 169: error correction level.
b.buf.Write([]byte{gs, '(', 'k', 3, 0, '1', 'E', byte(level)})
// Function 180: store data. The length covers cn, fn, m and the data.
n := len(data) + 3
b.buf.Write([]byte{gs, '(', 'k', byte(n), byte(n >> 8), '1', 'P', '0'})
b.buf.Write(data)
// Function 181: print the stored symbol.
b.buf.Write([]byte{gs, '(', 'k', 3, 0, '1', 'Q', '0'})
return nil
}
+83
View File
@@ -0,0 +1,83 @@
package escpos
import (
"fmt"
"image"
"image/color"
)
// rasterBandHeight is the number of rows sent per GS v 0 command. Splitting
// tall images keeps every command within the height limits of all supported
// models (TM-T20 accepts up to 2303 rows).
const rasterBandHeight = 256
// maxRasterWidthBytes bounds the image width so xL/xH stay meaningful.
const maxRasterWidthBytes = 0xFFFF
// RasterImage appends img as one or more GS v 0 raster bit images. Pixels
// darker than 50% luminance, after compositing onto white paper, print black.
// Dither images first (see the raster package) for photographic content. The
// width is padded with white up to a multiple of 8 dots.
func (b *Builder) RasterImage(img image.Image) error {
bounds := img.Bounds()
width, height := bounds.Dx(), bounds.Dy()
if width <= 0 || height <= 0 {
return fmt.Errorf("%w: image is empty", ErrInvalidArgument)
}
widthBytes := (width + 7) / 8
if widthBytes > maxRasterWidthBytes {
return fmt.Errorf("%w: image is %d dots wide", ErrInvalidArgument, width)
}
dark := darkFunc(img)
row := make([]byte, widthBytes)
for top := 0; top < height; top += rasterBandHeight {
rows := min(rasterBandHeight, height-top)
b.buf.Write([]byte{gs, 'v', '0', 0,
byte(widthBytes), byte(widthBytes >> 8),
byte(rows), byte(rows >> 8)})
for y := top; y < top+rows; y++ {
clear(row)
for x := range width {
if dark(bounds.Min.X+x, bounds.Min.Y+y) {
row[x/8] |= 0x80 >> (x % 8)
}
}
b.buf.Write(row)
}
}
return nil
}
// darkFunc returns a pixel test for img, with fast paths for the image types
// the raster package produces.
func darkFunc(img image.Image) func(x, y int) bool {
switch m := img.(type) {
case *image.Paletted:
dark := make([]bool, len(m.Palette))
for i, c := range m.Palette {
dark[i] = isDark(c)
}
return func(x, y int) bool {
idx := m.ColorIndexAt(x, y)
return int(idx) < len(dark) && dark[idx]
}
case *image.Gray:
return func(x, y int) bool {
return m.GrayAt(x, y).Y < 0x80
}
}
return func(x, y int) bool {
return isDark(img.At(x, y))
}
}
// isDark composites c onto white and reports whether its luminance is below
// 50%. RGBA returns alpha-premultiplied values, so adding the uncovered
// fraction of white is enough to composite.
func isDark(c color.Color) bool {
r, g, bl, a := c.RGBA()
white := 0xFFFF - a
luma := (299*(r+white) + 587*(g+white) + 114*(bl+white)) / 1000
return luma < 0x8000
}
+75
View File
@@ -0,0 +1,75 @@
package escpos
import "fmt"
// StatusKind selects which real-time status byte DLE EOT requests.
type StatusKind byte
// StatusKind values for DLE EOT n.
const (
StatusPrinter StatusKind = 1
StatusOffline StatusKind = 2
StatusError StatusKind = 3
StatusPaper StatusKind = 4
)
// StatusKinds lists every status kind in the order a full query sends them.
func StatusKinds() []StatusKind {
return []StatusKind{StatusPrinter, StatusOffline, StatusError, StatusPaper}
}
// Status is the printer state decoded from DLE EOT responses.
type Status struct {
Online bool
CoverOpen bool
PaperNearEnd bool
PaperOut bool
CutterError bool
Unrecoverable bool
// AutoRecoverable reports an error the printer clears by itself, such as
// a print head that is too hot.
AutoRecoverable bool
}
// Ready reports whether the printer can print right now.
func (s Status) Ready() bool {
return s.Online && !s.CoverOpen && !s.PaperOut && !s.CutterError && !s.Unrecoverable && !s.AutoRecoverable
}
// StatusRequest returns the real-time DLE EOT n command for kind. Real-time
// commands are executed immediately, even while the printer is busy.
func StatusRequest(kind StatusKind) []byte {
return []byte{dle, eot, byte(kind)}
}
// statusFixedMask and statusFixedBits describe the bits every DLE EOT
// response has fixed: bits 0 and 7 are 0, bits 1 and 4 are 1.
const (
statusFixedMask byte = 0x93
statusFixedBits byte = 0x12
)
// Apply decodes resp, the printer's answer to StatusRequest(kind), into s.
func (s *Status) Apply(kind StatusKind, resp byte) error {
if resp&statusFixedMask != statusFixedBits {
return fmt.Errorf("%w: 0x%02X is not a DLE EOT %d response", ErrInvalidArgument, resp, kind)
}
bit := func(n uint) bool { return resp&(1<<n) != 0 }
switch kind {
case StatusPrinter:
s.Online = !bit(3)
case StatusOffline:
s.CoverOpen = bit(2)
s.PaperOut = s.PaperOut || bit(5)
case StatusError:
s.CutterError = bit(3)
s.Unrecoverable = bit(5)
s.AutoRecoverable = bit(6)
case StatusPaper:
s.PaperNearEnd = bit(2) && bit(3)
s.PaperOut = s.PaperOut || (bit(5) && bit(6))
default:
return fmt.Errorf("%w: unknown status kind %d", ErrInvalidArgument, kind)
}
return nil
}
+138
View File
@@ -0,0 +1,138 @@
// Package printer talks to a network receipt printer over a raw TCP socket
// (the "port 9100" / JetDirect protocol).
package printer
import (
"context"
"errors"
"fmt"
"net"
"time"
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/escpos"
)
// statusTimeout bounds how long the printer may take to answer one real-time
// status request.
const statusTimeout = 2 * time.Second
// ErrStatusUnsupported is returned by Status when the printer accepts the
// connection but does not answer DLE EOT requests.
var ErrStatusUnsupported = errors.New("printer: no answer to status request")
// Client sends data to one printer. Network printers accept a single
// connection at a time, so the Client serialises its connections. It is safe
// for concurrent use.
type Client struct {
addr string
dialTimeout time.Duration
writeTimeout time.Duration
dialer net.Dialer
// slot holds a token while a connection is open; acquiring it respects
// context cancellation, unlike a mutex.
slot chan struct{}
}
// NewClient returns a Client for the printer at addr ("host:port").
func NewClient(addr string, dialTimeout, writeTimeout time.Duration) *Client {
if addr == "" {
panic("printer.NewClient: addr must not be empty")
}
if dialTimeout <= 0 || writeTimeout <= 0 {
panic("printer.NewClient: timeouts must be positive")
}
return &Client{
addr: addr,
dialTimeout: dialTimeout,
writeTimeout: writeTimeout,
dialer: net.Dialer{Timeout: dialTimeout},
slot: make(chan struct{}, 1),
}
}
// Addr returns the printer address.
func (c *Client) Addr() string {
return c.addr
}
// Send writes data to the printer in one connection.
func (c *Client) Send(ctx context.Context, data []byte) error {
conn, release, err := c.connect(ctx)
if err != nil {
return err
}
defer release()
if err := conn.SetWriteDeadline(c.deadline(ctx, c.writeTimeout)); err != nil {
return fmt.Errorf("setting printer write deadline: %w", err)
}
if _, err := conn.Write(data); err != nil {
return fmt.Errorf("writing to printer %s: %w", c.addr, err)
}
return nil
}
// Status queries the printer's real-time status. It returns
// ErrStatusUnsupported when the printer is reachable but does not answer.
func (c *Client) Status(ctx context.Context) (escpos.Status, error) {
var status escpos.Status
conn, release, err := c.connect(ctx)
if err != nil {
return status, err
}
defer release()
resp := make([]byte, 1)
for _, kind := range escpos.StatusKinds() {
deadline := c.deadline(ctx, statusTimeout)
if err := conn.SetDeadline(deadline); err != nil {
return status, fmt.Errorf("setting printer deadline: %w", err)
}
if _, err := conn.Write(escpos.StatusRequest(kind)); err != nil {
return status, fmt.Errorf("requesting printer status: %w", err)
}
if _, err := conn.Read(resp); err != nil {
var netErr net.Error
if errors.As(err, &netErr) && netErr.Timeout() {
return status, ErrStatusUnsupported
}
return status, fmt.Errorf("reading printer status: %w", err)
}
if err := status.Apply(kind, resp[0]); err != nil {
return status, ErrStatusUnsupported
}
}
return status, nil
}
// connect waits for the connection slot and dials the printer. The returned
// release func closes the connection and frees the slot.
func (c *Client) connect(ctx context.Context) (net.Conn, func(), error) {
select {
case c.slot <- struct{}{}:
case <-ctx.Done():
return nil, nil, fmt.Errorf("waiting for printer %s: %w", c.addr, ctx.Err())
}
conn, err := c.dialer.DialContext(ctx, "tcp", c.addr)
if err != nil {
<-c.slot
return nil, nil, fmt.Errorf("connecting to printer %s: %w", c.addr, err)
}
release := func() {
// Close errors after a completed write carry no information the
// caller can act on: the data has already been handed to the OS.
_ = conn.Close()
<-c.slot
}
return conn, release, nil
}
// deadline returns now+d, or the context deadline if that is sooner.
func (c *Client) deadline(ctx context.Context, d time.Duration) time.Time {
deadline := time.Now().Add(d)
if ctxDeadline, ok := ctx.Deadline(); ok && ctxDeadline.Before(deadline) {
return ctxDeadline
}
return deadline
}
+128
View File
@@ -0,0 +1,128 @@
package printer_test
import (
"bytes"
"context"
"errors"
"io"
"net"
"testing"
"time"
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/escpos"
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/printer"
)
// fakePrinter accepts one connection per handle call.
func fakePrinter(t *testing.T, handle func(net.Conn)) string {
t.Helper()
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = ln.Close() })
go func() {
for {
conn, err := ln.Accept()
if err != nil {
return
}
go func() {
defer conn.Close()
handle(conn)
}()
}
}()
return ln.Addr().String()
}
func TestSend(t *testing.T) {
received := make(chan []byte, 1)
addr := fakePrinter(t, func(conn net.Conn) {
data, _ := io.ReadAll(conn)
received <- data
})
client := printer.NewClient(addr, time.Second, time.Second)
if err := client.Send(context.Background(), []byte("receipt")); err != nil {
t.Fatal(err)
}
select {
case got := <-received:
if !bytes.Equal(got, []byte("receipt")) {
t.Errorf("printer got %q", got)
}
case <-time.After(2 * time.Second):
t.Fatal("printer received nothing")
}
}
func TestSendUnreachable(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
addr := ln.Addr().String()
_ = ln.Close() // nothing listens here now
client := printer.NewClient(addr, 500*time.Millisecond, time.Second)
if err := client.Send(context.Background(), []byte("x")); err == nil {
t.Fatal("expected a connection error")
}
}
func TestSendRespectsCancelledContextWhileBusy(t *testing.T) {
release := make(chan struct{})
addr := fakePrinter(t, func(conn net.Conn) {
<-release
_, _ = io.Copy(io.Discard, conn)
})
t.Cleanup(func() { close(release) })
client := printer.NewClient(addr, time.Second, 5*time.Second)
// Hold the single connection slot with a status query that never gets
// an answer, then try to send with a short deadline.
go func() { _, _ = client.Status(context.Background()) }()
time.Sleep(100 * time.Millisecond)
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
if err := client.Send(ctx, []byte("x")); !errors.Is(err, context.DeadlineExceeded) {
t.Errorf("err = %v, want context.DeadlineExceeded", err)
}
}
func TestStatus(t *testing.T) {
answers := map[byte]byte{1: 0x12, 2: 0x12, 3: 0x12, 4: 0x1E} // paper near end
addr := fakePrinter(t, func(conn net.Conn) {
req := make([]byte, 3)
for {
if _, err := io.ReadFull(conn, req); err != nil {
return
}
if req[0] != 0x10 || req[1] != 0x04 {
return
}
_, _ = conn.Write([]byte{answers[req[2]]})
}
})
client := printer.NewClient(addr, time.Second, time.Second)
status, err := client.Status(context.Background())
if err != nil {
t.Fatal(err)
}
if want := (escpos.Status{Online: true, PaperNearEnd: true}); status != want {
t.Errorf("status = %+v, want %+v", status, want)
}
}
func TestStatusUnsupported(t *testing.T) {
addr := fakePrinter(t, func(conn net.Conn) {
_, _ = io.Copy(io.Discard, conn) // a printer that never answers
})
client := printer.NewClient(addr, time.Second, time.Second)
ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond)
defer cancel()
if _, err := client.Status(ctx); !errors.Is(err, printer.ErrStatusUnsupported) {
t.Errorf("err = %v, want ErrStatusUnsupported", err)
}
}
+294
View File
@@ -0,0 +1,294 @@
// Package printqueue prints jobs one at a time, in submission order, and
// keeps track of their status.
package printqueue
import (
"context"
"errors"
"fmt"
"log/slog"
"sync"
"time"
"go.jetify.com/typeid"
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/receipt"
)
// jobTimeout bounds rendering and sending one job, including retries.
const jobTimeout = 2 * time.Minute
var (
// ErrQueueFull is returned by Submit when no more jobs can wait.
ErrQueueFull = errors.New("print queue is full")
// ErrClosed is returned by Submit once the queue has shut down.
ErrClosed = errors.New("print queue is shut down")
// ErrNotFound is returned by Status for unknown or expired job IDs.
ErrNotFound = errors.New("job not found")
errShuttingDown = errors.New("server shutting down before the job was printed")
)
// jobPrefix gives job IDs their "job_" prefix.
type jobPrefix struct{}
// Prefix implements typeid.PrefixType.
func (jobPrefix) Prefix() string { return "job" }
// JobID identifies a print job, e.g. "job_01h455vb4pex5vsknk084sn02q". It is
// a TypeID: a UUIDv7, so IDs sort by creation time.
type JobID struct {
typeid.TypeID[jobPrefix]
}
// ParseJobID parses s as a JobID.
func ParseJobID(s string) (JobID, error) {
return typeid.Parse[JobID](s)
}
// State is a job's position in its lifecycle.
type State string
// Job states.
const (
StateQueued State = "queued"
StatePrinting State = "printing"
StateDone State = "done"
StateFailed State = "failed"
)
// Status describes a job.
type Status struct {
ID JobID `json:"id"`
State State `json:"status"`
Error string `json:"error,omitempty"`
Attempts int `json:"attempts,omitempty"`
CreatedAt time.Time `json:"created_at"`
StartedAt *time.Time `json:"started_at,omitempty"`
FinishedAt *time.Time `json:"finished_at,omitempty"`
}
// Renderer turns a job into printer bytes.
type Renderer interface {
Render(ctx context.Context, job receipt.Job) ([]byte, error)
}
// Sender delivers bytes to the printer.
type Sender interface {
Send(ctx context.Context, data []byte) error
}
// Options configures a Queue.
type Options struct {
// Size is how many jobs may wait.
Size int
// History is how many finished jobs keep their status.
History int
// Retries is how many times a failed send is retried; RetryDelay is the
// first wait, doubling after each attempt.
Retries int
RetryDelay time.Duration
// OnFailure, if set, is called for every job that fails, e.g. to report
// it to an error tracker.
OnFailure func(id JobID, err error)
}
type queuedJob struct {
id JobID
job receipt.Job
}
// Queue runs print jobs on a single worker. It is safe for concurrent use.
type Queue struct {
renderer Renderer
sender Sender
logger *slog.Logger
options Options
jobs chan queuedJob
// mu guards statuses, finished and closed.
mu sync.Mutex
statuses map[JobID]*Status
finished []JobID // oldest first, for history eviction
closed bool
}
// New returns a Queue. Call Run to start printing.
func New(renderer Renderer, sender Sender, logger *slog.Logger, options Options) *Queue {
if renderer == nil || sender == nil || logger == nil {
panic("printqueue.New: renderer, sender and logger must not be nil")
}
if options.Size <= 0 {
panic("printqueue.New: size must be positive")
}
if options.RetryDelay <= 0 {
options.RetryDelay = time.Second
}
return &Queue{
renderer: renderer,
sender: sender,
logger: logger,
options: options,
jobs: make(chan queuedJob, options.Size),
statuses: make(map[JobID]*Status),
}
}
// Submit queues job. The job should already be validated so callers can
// report problems synchronously; it is validated again when rendered.
func (q *Queue) Submit(job receipt.Job) (Status, error) {
id, err := typeid.New[JobID]()
if err != nil {
return Status{}, fmt.Errorf("generating job ID: %w", err)
}
q.mu.Lock()
defer q.mu.Unlock()
if q.closed {
return Status{}, ErrClosed
}
select {
case q.jobs <- queuedJob{id: id, job: job}:
default:
return Status{}, ErrQueueFull
}
status := &Status{ID: id, State: StateQueued, CreatedAt: time.Now().UTC()}
q.statuses[id] = status
return *status, nil
}
// Status returns the status of job id.
func (q *Queue) Status(id JobID) (Status, error) {
q.mu.Lock()
defer q.mu.Unlock()
status, ok := q.statuses[id]
if !ok {
return Status{}, ErrNotFound
}
return *status, nil
}
// Pending returns the number of jobs waiting to print.
func (q *Queue) Pending() int {
return len(q.jobs)
}
// Run prints jobs until ctx is cancelled. A job that is printing when ctx is
// cancelled is finished; jobs still waiting are marked failed.
func (q *Queue) Run(ctx context.Context) error {
for {
select {
case <-ctx.Done():
q.shutdown()
return nil
case qj := <-q.jobs:
// select picks randomly when both cases are ready, so check
// again: no new job may start once shutdown has begun.
if ctx.Err() != nil {
q.finish(qj.id, 0, errShuttingDown)
q.shutdown()
return nil
}
q.process(ctx, qj)
}
}
}
func (q *Queue) process(ctx context.Context, qj queuedJob) {
// Detach from shutdown so a receipt that has started is not cut short,
// but keep a bound so a stuck printer cannot hold the worker forever.
jobCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), jobTimeout)
defer cancel()
q.update(qj.id, func(s *Status) {
now := time.Now().UTC()
s.State, s.StartedAt = StatePrinting, &now
})
logger := q.logger.With("job_id", qj.id.String())
logger.Info("printing job", "elements", len(qj.job.Elements), "copies", max(qj.job.Copies, 1))
attempts, err := q.print(ctx, jobCtx, qj.job)
q.finish(qj.id, attempts, err)
if err != nil {
logger.Error("job failed", "attempts", attempts, "err", err)
if q.options.OnFailure != nil {
q.options.OnFailure(qj.id, err)
}
return
}
logger.Info("job printed", "attempts", attempts)
}
// print renders job once and sends it, retrying failed sends with backoff.
// Retries stop early when runCtx is cancelled.
func (q *Queue) print(runCtx, jobCtx context.Context, job receipt.Job) (int, error) {
data, err := q.renderer.Render(jobCtx, job)
if err != nil {
return 0, fmt.Errorf("rendering: %w", err)
}
delay := q.options.RetryDelay
for attempt := 1; ; attempt++ {
err := q.sender.Send(jobCtx, data)
if err == nil {
return attempt, nil
}
if attempt > q.options.Retries {
return attempt, err
}
q.logger.Warn("send failed, retrying", "attempt", attempt, "retry_in", delay, "err", err)
select {
case <-time.After(delay):
case <-runCtx.Done():
return attempt, fmt.Errorf("server shutting down after %d attempts: %w", attempt, err)
case <-jobCtx.Done():
return attempt, fmt.Errorf("giving up after %d attempts: %w", attempt, err)
}
delay *= 2
}
}
func (q *Queue) finish(id JobID, attempts int, err error) {
q.update(id, func(s *Status) {
now := time.Now().UTC()
s.FinishedAt, s.Attempts = &now, attempts
s.State = StateDone
if err != nil {
s.State, s.Error = StateFailed, err.Error()
}
})
q.mu.Lock()
defer q.mu.Unlock()
q.finished = append(q.finished, id)
for len(q.finished) > q.options.History {
delete(q.statuses, q.finished[0])
q.finished = q.finished[1:]
}
}
func (q *Queue) update(id JobID, fn func(*Status)) {
q.mu.Lock()
defer q.mu.Unlock()
if s, ok := q.statuses[id]; ok {
fn(s)
}
}
// shutdown stops accepting jobs and fails those still waiting.
func (q *Queue) shutdown() {
q.mu.Lock()
q.closed = true
q.mu.Unlock()
for {
select {
case qj := <-q.jobs:
q.finish(qj.id, 0, errShuttingDown)
default:
return
}
}
}
+255
View File
@@ -0,0 +1,255 @@
package printqueue_test
import (
"context"
"errors"
"io"
"log/slog"
"strings"
"sync"
"testing"
"time"
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/printqueue"
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/receipt"
)
type fakeRenderer struct{ err error }
func (f fakeRenderer) Render(_ context.Context, job receipt.Job) ([]byte, error) {
if f.err != nil {
return nil, f.err
}
return []byte(job.Elements[0].Text), nil
}
// fakeSender fails the first failures sends, then records data.
type fakeSender struct {
mu sync.Mutex
failures int
sent []string
block chan struct{} // if set, Send waits for it to close
}
func (f *fakeSender) Send(_ context.Context, data []byte) error {
if f.block != nil {
<-f.block
}
f.mu.Lock()
defer f.mu.Unlock()
if f.failures > 0 {
f.failures--
return errors.New("printer offline")
}
f.sent = append(f.sent, string(data))
return nil
}
func (f *fakeSender) Sent() []string {
f.mu.Lock()
defer f.mu.Unlock()
return append([]string(nil), f.sent...)
}
func job(text string) receipt.Job {
return receipt.Job{Elements: []receipt.Element{{Type: "text", Text: text}}}
}
func discardLogger() *slog.Logger {
return slog.New(slog.NewTextHandler(io.Discard, nil))
}
func newQueue(r printqueue.Renderer, s printqueue.Sender, opts printqueue.Options) *printqueue.Queue {
if opts.Size == 0 {
opts.Size = 10
}
if opts.History == 0 {
opts.History = 100
}
if opts.RetryDelay == 0 {
opts.RetryDelay = time.Millisecond
}
return printqueue.New(r, s, discardLogger(), opts)
}
// startQueue runs q until the test ends and returns a func that stops it and
// waits for Run to return.
func startQueue(t *testing.T, q *printqueue.Queue) (stop func()) {
t.Helper()
ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
go func() {
defer close(done)
if err := q.Run(ctx); err != nil {
t.Error(err)
}
}()
var once sync.Once
stop = func() { once.Do(func() { cancel(); <-done }) }
t.Cleanup(stop)
return stop
}
func waitForState(t *testing.T, q *printqueue.Queue, id printqueue.JobID, want printqueue.State) printqueue.Status {
t.Helper()
deadline := time.Now().Add(5 * time.Second)
for time.Now().Before(deadline) {
st, err := q.Status(id)
if err != nil {
t.Fatal(err)
}
if st.State == want {
return st
}
time.Sleep(5 * time.Millisecond)
}
st, _ := q.Status(id)
t.Fatalf("job %s state = %s, want %s", id, st.State, want)
return st
}
func TestSubmitAndPrintInOrder(t *testing.T) {
sender := &fakeSender{}
q := newQueue(fakeRenderer{}, sender, printqueue.Options{})
startQueue(t, q)
var last printqueue.Status
for _, text := range []string{"one", "two", "three"} {
st, err := q.Submit(job(text))
if err != nil {
t.Fatal(err)
}
if st.State != printqueue.StateQueued || !strings.HasPrefix(st.ID.String(), "job_") {
t.Errorf("submit status = %+v", st)
}
last = st
}
done := waitForState(t, q, last.ID, printqueue.StateDone)
if done.StartedAt == nil || done.FinishedAt == nil || done.Attempts != 1 {
t.Errorf("done status = %+v", done)
}
if got := sender.Sent(); strings.Join(got, ",") != "one,two,three" {
t.Errorf("sent %v, want one,two,three", got)
}
}
func TestRetriesThenSucceeds(t *testing.T) {
sender := &fakeSender{failures: 2}
q := newQueue(fakeRenderer{}, sender, printqueue.Options{Retries: 3})
startQueue(t, q)
st, _ := q.Submit(job("x"))
done := waitForState(t, q, st.ID, printqueue.StateDone)
if done.Attempts != 3 {
t.Errorf("attempts = %d, want 3", done.Attempts)
}
}
func TestFailsAfterRetries(t *testing.T) {
var reported []printqueue.JobID
var mu sync.Mutex
sender := &fakeSender{failures: 10}
q := newQueue(fakeRenderer{}, sender, printqueue.Options{
Retries: 2,
OnFailure: func(id printqueue.JobID, _ error) {
mu.Lock()
defer mu.Unlock()
reported = append(reported, id)
},
})
startQueue(t, q)
st, _ := q.Submit(job("x"))
failed := waitForState(t, q, st.ID, printqueue.StateFailed)
if failed.Attempts != 3 || !strings.Contains(failed.Error, "printer offline") {
t.Errorf("failed status = %+v", failed)
}
mu.Lock()
defer mu.Unlock()
if len(reported) != 1 || reported[0] != st.ID {
t.Errorf("OnFailure got %v", reported)
}
}
func TestRenderFailureIsNotRetried(t *testing.T) {
sender := &fakeSender{}
q := newQueue(fakeRenderer{err: errors.New("image blocked")}, sender, printqueue.Options{Retries: 3})
startQueue(t, q)
st, _ := q.Submit(job("x"))
failed := waitForState(t, q, st.ID, printqueue.StateFailed)
if !strings.Contains(failed.Error, "image blocked") || len(sender.Sent()) != 0 {
t.Errorf("failed status = %+v, sent %v", failed, sender.Sent())
}
}
func TestQueueFull(t *testing.T) {
q := newQueue(fakeRenderer{}, &fakeSender{}, printqueue.Options{Size: 2})
// Not running, so nothing drains the queue.
for range 2 {
if _, err := q.Submit(job("x")); err != nil {
t.Fatal(err)
}
}
if _, err := q.Submit(job("x")); !errors.Is(err, printqueue.ErrQueueFull) {
t.Errorf("err = %v, want ErrQueueFull", err)
}
if q.Pending() != 2 {
t.Errorf("Pending = %d, want 2", q.Pending())
}
}
func TestShutdownFinishesCurrentJobAndFailsWaiting(t *testing.T) {
sender := &fakeSender{block: make(chan struct{})}
q := newQueue(fakeRenderer{}, sender, printqueue.Options{})
stop := startQueue(t, q)
first, _ := q.Submit(job("first"))
waitForState(t, q, first.ID, printqueue.StatePrinting)
second, _ := q.Submit(job("second"))
stopped := make(chan struct{})
go func() { stop(); close(stopped) }()
time.Sleep(20 * time.Millisecond) // let Run observe the cancellation
close(sender.block) // the in-flight send completes
<-stopped
if st, _ := q.Status(first.ID); st.State != printqueue.StateDone {
t.Errorf("in-flight job state = %s, want done", st.State)
}
if st, _ := q.Status(second.ID); st.State != printqueue.StateFailed || !strings.Contains(st.Error, "shutting down") {
t.Errorf("waiting job = %+v, want failed with shutting down", st)
}
if _, err := q.Submit(job("late")); !errors.Is(err, printqueue.ErrClosed) {
t.Errorf("submit after shutdown err = %v, want ErrClosed", err)
}
}
func TestHistoryEviction(t *testing.T) {
sender := &fakeSender{}
q := newQueue(fakeRenderer{}, sender, printqueue.Options{History: 2})
startQueue(t, q)
var ids []printqueue.JobID
for range 3 {
st, _ := q.Submit(job("x"))
ids = append(ids, st.ID)
waitForState(t, q, st.ID, printqueue.StateDone)
}
if _, err := q.Status(ids[0]); !errors.Is(err, printqueue.ErrNotFound) {
t.Errorf("oldest job err = %v, want ErrNotFound", err)
}
if _, err := q.Status(ids[2]); err != nil {
t.Errorf("newest job err = %v", err)
}
}
func TestParseJobID(t *testing.T) {
q := newQueue(fakeRenderer{}, &fakeSender{}, printqueue.Options{})
st, _ := q.Submit(job("x"))
parsed, err := printqueue.ParseJobID(st.ID.String())
if err != nil || parsed != st.ID {
t.Errorf("ParseJobID(%s) = %v, %v", st.ID, parsed, err)
}
for _, bad := range []string{"", "nope", "req_01h455vb4pex5vsknk084sn02q", "job_zzz"} {
if _, err := printqueue.ParseJobID(bad); err == nil {
t.Errorf("ParseJobID(%q) succeeded", bad)
}
}
}
+92
View File
@@ -0,0 +1,92 @@
// Package raster prepares images for thermal printing: it decodes them within
// a pixel budget, scales them to the print head width, and dithers them to
// pure black and white.
package raster
import (
"bytes"
"errors"
"fmt"
"image"
"image/color"
"image/draw"
// Register the formats Decode accepts.
_ "image/gif" // registers GIF decoding
_ "image/jpeg" // registers JPEG decoding
_ "image/png" // registers PNG decoding
xdraw "golang.org/x/image/draw"
_ "golang.org/x/image/webp" // registers WebP decoding
)
var (
// ErrTooLarge is returned when an image exceeds the pixel budget.
ErrTooLarge = errors.New("raster: image exceeds pixel limit")
// ErrInvalidSize is returned for zero or negative target sizes.
ErrInvalidSize = errors.New("raster: invalid size")
)
// Decode decodes PNG, JPEG, GIF or WebP data. The header is checked first,
// so an image whose declared size exceeds maxPixels is rejected before any
// pixel memory is allocated.
func Decode(data []byte, maxPixels int) (image.Image, error) {
cfg, format, err := image.DecodeConfig(bytes.NewReader(data))
if err != nil {
return nil, fmt.Errorf("reading image header: %w", err)
}
if cfg.Width <= 0 || cfg.Height <= 0 {
return nil, fmt.Errorf("%w: %dx%d", ErrInvalidSize, cfg.Width, cfg.Height)
}
if int64(cfg.Width)*int64(cfg.Height) > int64(maxPixels) {
return nil, fmt.Errorf("%w: %dx%d is more than %d pixels", ErrTooLarge, cfg.Width, cfg.Height, maxPixels)
}
img, _, err := image.Decode(bytes.NewReader(data))
if err != nil {
return nil, fmt.Errorf("decoding %s image: %w", format, err)
}
return img, nil
}
// palette is the two-colour palette thermal printers can reproduce.
// Index 0 is white so a freshly allocated image is blank paper.
func palette() color.Palette {
return color.Palette{color.White, color.Black}
}
// Monochrome scales img to width dots, keeping its aspect ratio, composites it
// onto white paper, and Floyd–Steinberg dithers it to black and white.
func Monochrome(img image.Image, width int) (*image.Paletted, error) {
src := img.Bounds()
if width <= 0 || src.Dx() <= 0 || src.Dy() <= 0 {
return nil, fmt.Errorf("%w: cannot scale %dx%d to width %d", ErrInvalidSize, src.Dx(), src.Dy(), width)
}
height := max(1, int(int64(src.Dy())*int64(width)/int64(src.Dx())))
// Scale onto white grayscale so transparency becomes paper and the
// dither works on luminance rather than RGB distance.
gray := image.NewGray(image.Rect(0, 0, width, height))
draw.Draw(gray, gray.Bounds(), image.White, image.Point{}, draw.Src)
xdraw.CatmullRom.Scale(gray, gray.Bounds(), img, src, draw.Over, nil)
out := image.NewPaletted(gray.Bounds(), palette())
draw.FloydSteinberg.Draw(out, out.Bounds(), gray, image.Point{})
return out, nil
}
// Place returns a width-dot-wide white canvas with img drawn at x. It is used
// to align images, because printers do not apply justification to raster
// images consistently.
func Place(img *image.Paletted, width, x int) (*image.Paletted, error) {
b := img.Bounds()
if width < b.Dx() || x < 0 || x+b.Dx() > width {
return nil, fmt.Errorf("%w: cannot place %d-dot image at %d on %d dots", ErrInvalidSize, b.Dx(), x, width)
}
if x == 0 && width == b.Dx() {
return img, nil
}
out := image.NewPaletted(image.Rect(0, 0, width, b.Dy()), palette())
draw.Draw(out, image.Rect(x, 0, x+b.Dx(), b.Dy()), img, b.Min, draw.Src)
return out, nil
}
+133
View File
@@ -0,0 +1,133 @@
package raster_test
import (
"bytes"
"errors"
"image"
"image/color"
"image/png"
"testing"
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/raster"
)
func encodePNG(t *testing.T, img image.Image) []byte {
t.Helper()
var buf bytes.Buffer
if err := png.Encode(&buf, img); err != nil {
t.Fatal(err)
}
return buf.Bytes()
}
func gradient(w, h int) *image.Gray {
img := image.NewGray(image.Rect(0, 0, w, h))
for y := range h {
for x := range w {
img.SetGray(x, y, color.Gray{Y: uint8(x * 255 / max(1, w-1))})
}
}
return img
}
func TestDecode(t *testing.T) {
data := encodePNG(t, gradient(40, 20))
img, err := raster.Decode(data, 1000)
if err != nil {
t.Fatal(err)
}
if img.Bounds().Dx() != 40 || img.Bounds().Dy() != 20 {
t.Errorf("bounds = %v", img.Bounds())
}
}
func TestDecodeRejectsOversizedBeforeDecoding(t *testing.T) {
data := encodePNG(t, gradient(40, 20))
if _, err := raster.Decode(data, 799); !errors.Is(err, raster.ErrTooLarge) {
t.Errorf("err = %v, want ErrTooLarge", err)
}
}
func TestDecodeRejectsGarbage(t *testing.T) {
if _, err := raster.Decode([]byte("not an image"), 1000); err == nil {
t.Error("expected an error")
}
}
func TestMonochromeScalesAndKeepsAspect(t *testing.T) {
out, err := raster.Monochrome(gradient(1152, 400), 576)
if err != nil {
t.Fatal(err)
}
if got := out.Bounds(); got.Dx() != 576 || got.Dy() != 200 {
t.Errorf("bounds = %v, want 576x200", got)
}
}
func TestMonochromeIsBlackAndWhiteAndDithers(t *testing.T) {
out, err := raster.Monochrome(gradient(200, 50), 200)
if err != nil {
t.Fatal(err)
}
if len(out.Palette) != 2 {
t.Fatalf("palette has %d colours, want 2", len(out.Palette))
}
// A dither of a left-to-right gradient has mixed pixels in the middle,
// unlike a hard threshold which would split it into two solid halves.
black := 0
for y := range 50 {
for x := 90; x < 110; x++ {
if out.ColorIndexAt(x, y) == 1 {
black++
}
}
}
if total := 50 * 20; black == 0 || black == total {
t.Errorf("mid-gradient has %d/%d black pixels, want a mix", black, total)
}
}
func TestMonochromeTransparentBecomesWhite(t *testing.T) {
src := image.NewNRGBA(image.Rect(0, 0, 16, 16)) // fully transparent
out, err := raster.Monochrome(src, 16)
if err != nil {
t.Fatal(err)
}
for i, idx := range out.Pix {
if idx != 0 {
t.Fatalf("pixel %d is black, want white paper", i)
}
}
}
func TestMonochromeInvalidWidth(t *testing.T) {
if _, err := raster.Monochrome(gradient(10, 10), 0); !errors.Is(err, raster.ErrInvalidSize) {
t.Errorf("err = %v, want ErrInvalidSize", err)
}
}
func TestPlace(t *testing.T) {
img, err := raster.Monochrome(image.NewGray(image.Rect(0, 0, 8, 2)), 8) // all black
if err != nil {
t.Fatal(err)
}
out, err := raster.Place(img, 24, 8)
if err != nil {
t.Fatal(err)
}
if out.Bounds().Dx() != 24 {
t.Fatalf("width = %d", out.Bounds().Dx())
}
for x := range 24 {
want := uint8(0)
if x >= 8 && x < 16 {
want = 1
}
if got := out.ColorIndexAt(x, 0); got != want {
t.Errorf("x=%d index=%d, want %d", x, got, want)
}
}
if _, err := raster.Place(img, 12, 8); !errors.Is(err, raster.ErrInvalidSize) {
t.Errorf("overflowing place err = %v", err)
}
}
+389
View File
@@ -0,0 +1,389 @@
// Package receipt defines print jobs, validates them, and lays them out as
// ESC/POS command streams with code page transcoding and word wrapping.
package receipt
import (
"encoding/base64"
"encoding/hex"
"fmt"
"net/url"
"strings"
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/escpos"
)
// Element types.
const (
TypeText = "text"
TypeFeed = "feed"
TypeQR = "qr"
TypeBarcode = "barcode"
TypeImage = "image"
TypeRaw = "raw"
TypeCut = "cut"
)
// Job limits.
const (
MaxElements = 500
MaxCopies = 5
)
// Element defaults.
const (
defaultQRSize = 6
defaultBarcodeHeight = 80
defaultBarcodeWidth = 3
)
// Job is a receipt to print.
type Job struct {
Elements []Element `json:"elements"`
// Copies is how many times the receipt is printed, each with its own
// cut. Zero means one.
Copies int `json:"copies,omitempty"`
}
// Element is one item on a receipt. Type selects which fields apply; fields
// that do not apply to the type are ignored. Width and Height mean character
// multipliers for text, module width and bar height for barcodes, and target
// width in dots for images.
type Element struct {
Type string `json:"type"`
// Text.
Text string `json:"text,omitempty"`
Bold bool `json:"bold,omitempty"`
Size int `json:"size,omitempty"`
Width int `json:"width,omitempty"`
Height int `json:"height,omitempty"`
Font string `json:"font,omitempty"`
Align string `json:"align,omitempty"`
Underline int `json:"underline,omitempty"`
Invert bool `json:"invert,omitempty"`
Newline *bool `json:"newline,omitempty"`
Wrap *bool `json:"wrap,omitempty"`
// Feed.
Lines int `json:"lines,omitempty"`
// QR code and barcode.
Data string `json:"data,omitempty"`
Correction string `json:"correction,omitempty"`
Symbology string `json:"symbology,omitempty"`
HRI string `json:"hri,omitempty"`
// Image.
URL string `json:"url,omitempty"`
Base64 string `json:"base64,omitempty"`
// Raw.
Hex string `json:"hex,omitempty"`
// Cut.
Mode string `json:"mode,omitempty"`
}
// ValidationError lists every problem found in a job.
type ValidationError struct {
Problems []string
}
// Error implements error.
func (e *ValidationError) Error() string {
return "invalid job: " + strings.Join(e.Problems, "; ")
}
// Validate checks the whole job and reports every problem, so nothing is sent
// to the printer unless the entire receipt can be printed.
func (j Job) Validate() error {
var problems []string
switch {
case len(j.Elements) == 0:
problems = append(problems, "elements: at least one element is required")
case len(j.Elements) > MaxElements:
problems = append(problems, fmt.Sprintf("elements: %d elements, limit is %d", len(j.Elements), MaxElements))
}
if j.Copies < 0 || j.Copies > MaxCopies {
problems = append(problems, fmt.Sprintf("copies must be 1-%d", MaxCopies))
}
for i, el := range j.Elements {
if err := el.validate(); err != nil {
problems = append(problems, fmt.Sprintf("elements[%d] (%s): %v", i, el.Type, err))
}
}
if len(problems) > 0 {
return &ValidationError{Problems: problems}
}
return nil
}
func (j Job) copies() int {
return max(j.Copies, 1)
}
func (el Element) validate() error {
var err error
switch el.Type {
case TypeText:
_, err = el.textSpec()
case TypeFeed:
_, err = el.feedLines()
case TypeQR:
_, err = el.qrSpec()
case TypeBarcode:
_, err = el.barcodeSpec()
case TypeImage:
_, err = el.imageSpec()
case TypeRaw:
_, err = el.rawBytes()
case TypeCut:
_, err = el.cutMode()
case "":
err = fmt.Errorf("type is required")
default:
err = fmt.Errorf("unknown type %q (want text, feed, qr, barcode, image, raw or cut)", el.Type)
}
return err
}
type textSpec struct {
width, height int
bold bool
font escpos.Font
align escpos.Justification
underline escpos.Underline
invert bool
newline bool
wrap bool
}
func (el Element) textSpec() (textSpec, error) {
s := textSpec{
width: 1,
height: 1,
bold: el.Bold,
invert: el.Invert,
newline: el.Newline == nil || *el.Newline,
wrap: el.Wrap == nil || *el.Wrap,
}
if el.Size != 0 {
s.width, s.height = el.Size, el.Size
}
if el.Width != 0 {
s.width = el.Width
}
if el.Height != 0 {
s.height = el.Height
}
if s.width < 1 || s.width > escpos.MaxCharacterScale || s.height < 1 || s.height > escpos.MaxCharacterScale {
return s, fmt.Errorf("size, width and height must be 1-%d", escpos.MaxCharacterScale)
}
var err error
if s.font, err = parseFont(el.Font); err != nil {
return s, err
}
if s.align, err = parseAlign(el.Align); err != nil {
return s, err
}
switch el.Underline {
case 0, 1, 2:
s.underline = escpos.Underline(el.Underline)
default:
return s, fmt.Errorf("underline must be 0, 1 or 2")
}
return s, nil
}
func (el Element) feedLines() (uint8, error) {
switch {
case el.Lines == 0:
return 1, nil
case el.Lines < 1 || el.Lines > 255:
return 0, fmt.Errorf("lines must be 1-255")
}
return uint8(el.Lines), nil
}
type qrSpec struct {
size int
correction escpos.QRCorrection
align escpos.Justification
}
func (el Element) qrSpec() (qrSpec, error) {
s := qrSpec{size: defaultQRSize, correction: escpos.QRCorrectionM}
if el.Size != 0 {
s.size = el.Size
}
switch {
case el.Data == "":
return s, fmt.Errorf("data is required")
case len(el.Data) > escpos.MaxQRData:
return s, fmt.Errorf("data is %d bytes, limit is %d", len(el.Data), escpos.MaxQRData)
case s.size < escpos.MinQRModuleSize || s.size > escpos.MaxQRModuleSize:
return s, fmt.Errorf("size must be %d-%d", escpos.MinQRModuleSize, escpos.MaxQRModuleSize)
}
var err error
if el.Correction != "" {
if s.correction, err = escpos.ParseQRCorrection(el.Correction); err != nil {
return s, fmt.Errorf("correction must be L, M, Q or H")
}
}
if s.align, err = parseAlign(el.Align); err != nil {
return s, err
}
return s, nil
}
type barcodeSpec struct {
symbology escpos.Symbology
height int
width int
hri escpos.HRIPosition
align escpos.Justification
}
func (el Element) barcodeSpec() (barcodeSpec, error) {
s := barcodeSpec{height: defaultBarcodeHeight, width: defaultBarcodeWidth, hri: escpos.HRIBelow}
if el.Symbology == "" {
return s, fmt.Errorf("symbology is required (ean13, ean8, upca, upce, code39 or code128)")
}
var err error
if s.symbology, err = escpos.ParseSymbology(el.Symbology); err != nil {
return s, fmt.Errorf("unknown symbology %q (want ean13, ean8, upca, upce, code39 or code128)", el.Symbology)
}
if err := escpos.ValidateBarcode(s.symbology, el.Data); err != nil {
return s, fmt.Errorf("data: %w", err)
}
if el.Height != 0 {
s.height = el.Height
}
if el.Width != 0 {
s.width = el.Width
}
if s.height < 1 || s.height > 255 {
return s, fmt.Errorf("height must be 1-255 dots")
}
if s.width < escpos.MinBarcodeWidth || s.width > escpos.MaxBarcodeWidth {
return s, fmt.Errorf("width must be %d-%d", escpos.MinBarcodeWidth, escpos.MaxBarcodeWidth)
}
switch strings.ToLower(el.HRI) {
case "", "below":
s.hri = escpos.HRIBelow
case "none":
s.hri = escpos.HRINone
case "above":
s.hri = escpos.HRIAbove
case "both":
s.hri = escpos.HRIBoth
default:
return s, fmt.Errorf("hri must be none, above, below or both")
}
if s.align, err = parseAlign(el.Align); err != nil {
return s, err
}
return s, nil
}
type imageSpec struct {
url string
data []byte
width int
align escpos.Justification
}
func (el Element) imageSpec() (imageSpec, error) {
s := imageSpec{width: el.Width}
switch {
case el.URL != "" && el.Base64 != "":
return s, fmt.Errorf("set url or base64, not both")
case el.URL != "":
u, err := url.Parse(el.URL)
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
return s, fmt.Errorf("url must be an absolute http or https URL")
}
s.url = el.URL
case el.Base64 != "":
data, err := decodeBase64Image(el.Base64)
if err != nil {
return s, fmt.Errorf("base64: %w", err)
}
s.data = data
default:
return s, fmt.Errorf("url or base64 is required")
}
if s.width < 0 {
return s, fmt.Errorf("width must be positive")
}
var err error
if s.align, err = parseAlign(el.Align); err != nil {
return s, err
}
return s, nil
}
// decodeBase64Image accepts standard base64, with or without padding, and
// data URIs such as "data:image/png;base64,....".
func decodeBase64Image(s string) ([]byte, error) {
if rest, ok := strings.CutPrefix(s, "data:"); ok {
_, payload, found := strings.Cut(rest, ",")
if !found {
return nil, fmt.Errorf("malformed data URI")
}
s = payload
}
s = strings.TrimSpace(s)
if data, err := base64.StdEncoding.DecodeString(s); err == nil {
return data, nil
}
data, err := base64.RawStdEncoding.DecodeString(strings.TrimRight(s, "="))
if err != nil {
return nil, fmt.Errorf("not valid base64")
}
return data, nil
}
func (el Element) rawBytes() ([]byte, error) {
if el.Hex == "" {
return nil, fmt.Errorf("hex is required")
}
data, err := hex.DecodeString(strings.ReplaceAll(el.Hex, " ", ""))
if err != nil {
return nil, fmt.Errorf("hex: %v", err)
}
return data, nil
}
func (el Element) cutMode() (escpos.CutMode, error) {
switch strings.ToLower(el.Mode) {
case "", "partial":
return escpos.CutPartial, nil
case "full":
return escpos.CutFull, nil
}
return 0, fmt.Errorf("mode must be partial or full")
}
func parseAlign(s string) (escpos.Justification, error) {
switch strings.ToLower(s) {
case "", "left":
return escpos.JustifyLeft, nil
case "center", "centre":
return escpos.JustifyCenter, nil
case "right":
return escpos.JustifyRight, nil
}
return 0, fmt.Errorf("align must be left, center or right")
}
func parseFont(s string) (escpos.Font, error) {
switch strings.ToLower(s) {
case "", "a":
return escpos.FontA, nil
case "b":
return escpos.FontB, nil
}
return 0, fmt.Errorf("font must be a or b")
}
+136
View File
@@ -0,0 +1,136 @@
package receipt
import (
"strings"
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/escpos"
)
// tabWidth matches the printer's default horizontal tab stops.
const tabWidth = 8
// sanitize removes control characters that would be read as printer
// commands, keeping newlines and tabs, and normalises CRLF to LF.
func sanitize(s string) string {
return strings.Map(func(r rune) rune {
if escpos.IsControl(r) {
return -1
}
return r
}, s)
}
// expandTabs replaces tabs with spaces up to the next tab stop. startCol is
// the column the text starts at; columns restart at zero after a newline.
func expandTabs(s string, startCol int) string {
if !strings.ContainsRune(s, '\t') {
return s
}
var b strings.Builder
col := startCol
for _, r := range s {
switch r {
case '\t':
n := tabWidth - col%tabWidth
b.WriteString(strings.Repeat(" ", n))
col += n
case '\n':
b.WriteRune(r)
col = 0
default:
b.WriteRune(r)
col++
}
}
return b.String()
}
// wrap breaks text into lines of at most width runes, so that no word is
// split across lines. The first line has only first runes available, because
// it continues whatever is already on the current printer line. A first line
// of "" means the text must start on a fresh line.
//
// Spaces at a break are dropped, each newline-separated paragraph wraps on
// its own, and leading indentation on a paragraph is kept. Only a word longer
// than a whole line is split, at the line edge.
func wrap(text string, first, width int) []string {
width = max(width, 1)
first = min(max(first, 0), width)
var lines []string
for i, para := range strings.Split(text, "\n") {
avail := width
if i == 0 {
avail = first
}
lines = append(lines, wrapParagraph([]rune(para), avail, width)...)
}
return lines
}
func wrapParagraph(para []rune, first, width int) []string {
var (
lines []string
line []rune
avail = first
// pending records a break point: spaces that did not fit were
// dropped, so the next word must start a new line.
pending bool
)
breakLine := func() {
lines = append(lines, string(trimTrailingSpaces(line)))
line = line[:0]
avail = width
pending = false
}
for _, tok := range tokenize(para) {
if tok[0] == ' ' {
switch {
case len(line) == 0 && len(lines) > 0:
// Spaces at the start of a wrapped line are dropped.
case !pending && len(line)+len(tok) <= avail:
line = append(line, tok...)
case len(line) > 0:
pending = true
}
continue
}
if pending {
breakLine()
}
if len(line)+len(tok) > avail {
if len(line) > 0 || avail < width {
breakLine()
}
for len(tok) > width {
line = append(line, tok[:width]...)
breakLine()
tok = tok[width:]
}
}
line = append(line, tok...)
}
return append(lines, string(line))
}
// tokenize splits s into alternating runs of spaces and non-spaces.
func tokenize(s []rune) [][]rune {
var tokens [][]rune
start := 0
for i := 1; i <= len(s); i++ {
if i == len(s) || (s[i] == ' ') != (s[start] == ' ') {
tokens = append(tokens, s[start:i])
start = i
}
}
return tokens
}
func trimTrailingSpaces(r []rune) []rune {
end := len(r)
for end > 0 && r[end-1] == ' ' {
end--
}
return r[:end]
}
+115
View File
@@ -0,0 +1,115 @@
package receipt
import (
"reflect"
"testing"
)
func TestWrap(t *testing.T) {
tests := []struct {
name string
text string
first, width int
want []string
}{
{
name: "fits", text: "hello world", first: 48, width: 48,
want: []string{"hello world"},
},
{
name: "breaks at word boundary", text: "the quick brown fox", first: 10, width: 10,
want: []string{"the quick", "brown fox"},
},
{
name: "never splits a word that fits on a line",
text: "Thank you for shopping with us today", first: 12, width: 12,
want: []string{"Thank you", "for shopping", "with us", "today"},
},
{
name: "hard splits only words longer than a line", text: "see https://example.com/very/long ok", first: 12, width: 12,
want: []string{"see", "https://exam", "ple.com/very", "/long ok"},
},
{
name: "runs of spaces kept inside a line", text: "a b", first: 10, width: 10,
want: []string{"a b"},
},
{
name: "spaces at a break are dropped", text: "aaaa b", first: 5, width: 5,
want: []string{"aaaa", "b"},
},
{
name: "paragraphs wrap independently", text: "one two\n\nthree", first: 5, width: 5,
want: []string{"one", "two", "", "three"},
},
{
name: "indent kept on first line only", text: " indented text here", first: 10, width: 10,
want: []string{" indented", "text here"},
},
{
name: "inline continuation fits", text: " world", first: 6, width: 10,
want: []string{" world"},
},
{
name: "inline continuation breaks before the word", text: "world", first: 3, width: 10,
want: []string{"", "world"},
},
{
name: "inline continuation keeps filling then wraps", text: " big wide world", first: 8, width: 10,
want: []string{" big", "wide world"},
},
{
name: "trailing space kept for inline use", text: "Total: ", first: 48, width: 48,
want: []string{"Total: "},
},
{
name: "empty", text: "", first: 10, width: 10,
want: []string{""},
},
{
name: "unicode counted as runes", text: "Grüße an Übermorgen", first: 10, width: 10,
want: []string{"Grüße an", "Übermorgen"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := wrap(tt.text, tt.first, tt.width)
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("wrap(%q, %d, %d) = %q, want %q", tt.text, tt.first, tt.width, got, tt.want)
}
for i, line := range got {
limit := tt.width
if i == 0 {
limit = tt.first
}
if n := len([]rune(line)); n > limit {
t.Errorf("line %d %q has %d runes, limit %d", i, line, n, limit)
}
}
})
}
}
func TestExpandTabs(t *testing.T) {
tests := []struct {
in string
start int
want string
}{
{"a\tb", 0, "a b"},
{"abcdefgh\tx", 0, "abcdefgh x"},
{"\tx", 3, " x"},
{"a\n\tb", 5, "a\n b"},
{"none", 0, "none"},
}
for _, tt := range tests {
if got := expandTabs(tt.in, tt.start); got != tt.want {
t.Errorf("expandTabs(%q, %d) = %q, want %q", tt.in, tt.start, got, tt.want)
}
}
}
func TestSanitize(t *testing.T) {
if got := sanitize("a\x1b@b\r\n\tc\x00"); got != "a@b\n\tc" {
t.Errorf("sanitize = %q", got)
}
}
+359
View File
@@ -0,0 +1,359 @@
package receipt_test
import (
"bytes"
"context"
"encoding/base64"
"errors"
"image"
"image/color"
"image/png"
"strings"
"testing"
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/escpos"
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/receipt"
)
type fakeFetcher struct {
data []byte
err error
urls []string
}
func (f *fakeFetcher) Fetch(_ context.Context, url string) ([]byte, error) {
f.urls = append(f.urls, url)
return f.data, f.err
}
func newRenderer(t *testing.T, fetcher receipt.Fetcher) *receipt.Renderer {
t.Helper()
profile, err := escpos.LookupProfile("tm-t20")
if err != nil {
t.Fatal(err)
}
return receipt.NewRenderer(receipt.Options{
Profile: profile,
CodePage: escpos.CodePage437,
MaxPixels: 10_000_000,
MaxHeight: 4000,
}, fetcher)
}
func pngData(t *testing.T, w, h int) []byte {
t.Helper()
img := image.NewGray(image.Rect(0, 0, w, h))
for i := range img.Pix {
img.Pix[i] = 0xFF
}
img.SetGray(0, 0, color.Gray{})
var buf bytes.Buffer
if err := png.Encode(&buf, img); err != nil {
t.Fatal(err)
}
return buf.Bytes()
}
func boolPtr(b bool) *bool { return &b }
var (
initialize = []byte{0x1B, 0x40}
selectCP437 = []byte{0x1B, 0x74, 0}
partialCut = []byte{0x1D, 0x56, 66, 0}
sizeOne = []byte{0x1D, 0x21, 0x00}
sizeTwo = []byte{0x1D, 0x21, 0x11}
justifyLeft = []byte{0x1B, 0x61, 0}
justifyRight = []byte{0x1B, 0x61, 2}
)
func render(t *testing.T, job receipt.Job) []byte {
t.Helper()
out, err := newRenderer(t, &fakeFetcher{}).Render(context.Background(), job)
if err != nil {
t.Fatalf("Render: %v", err)
}
return out
}
// printedLines returns the text the printer would print between line feeds,
// with ESC/POS commands removed. It understands only the commands the
// renderer emits for text jobs.
func printedLines(t *testing.T, out []byte) []string {
t.Helper()
var lines []string
var cur []byte
for i := 0; i < len(out); i++ {
switch c := out[i]; c {
case 0x1B: // ESC x n, or ESC @ / ESC 2
switch out[i+1] {
case '@', '2':
i++
default:
i += 2
}
case 0x1D: // GS x n, or GS V m n
if out[i+1] == 'V' {
i += 3
} else {
i += 2
}
case 0x0A:
lines = append(lines, string(cur))
cur = nil
default:
cur = append(cur, c)
}
}
if len(cur) > 0 {
lines = append(lines, string(cur))
}
return lines
}
func TestRenderTextJob(t *testing.T) {
out := render(t, receipt.Job{Elements: []receipt.Element{{Type: "text", Text: "Hi"}}})
if !bytes.HasPrefix(out, append(append([]byte{}, initialize...), selectCP437...)) {
t.Errorf("stream must start with ESC @ and ESC t 0, got % X", out[:min(5, len(out))])
}
if !bytes.HasSuffix(out, partialCut) {
t.Errorf("stream must end with a partial cut, got % X", out[len(out)-4:])
}
if got := printedLines(t, out); len(got) != 1 || got[0] != "Hi" {
t.Errorf("printed %q, want [\"Hi\"]", got)
}
}
func TestRenderTranscodesToCodePage437(t *testing.T) {
out := render(t, receipt.Job{Elements: []receipt.Element{{Type: "text", Text: "┌─┐ Ü 🎉"}}})
if !bytes.Contains(out, []byte{0xDA, 0xC4, 0xBF, ' ', 0x9A, ' ', '?'}) {
t.Errorf("CP437 bytes not found in % X", out)
}
if bytes.Contains(out, []byte("┌")) {
t.Error("raw UTF-8 leaked into the stream")
}
}
func TestRenderWrapsAtPaperWidth(t *testing.T) {
paragraph := strings.Repeat("lorem ipsum dolor sit amet ", 12)
out := render(t, receipt.Job{Elements: []receipt.Element{
{Type: "text", Text: paragraph},
{Type: "text", Text: paragraph, Size: 2},
}})
lines := printedLines(t, out)
if len(lines) < 4 {
t.Fatalf("expected wrapped output, got %q", lines)
}
words := map[string]bool{"lorem": true, "ipsum": true, "dolor": true, "sit": true, "amet": true}
for _, line := range lines {
if len(line) > 48 {
t.Errorf("line %q is %d chars, Font A size 1 fits 48", line, len(line))
}
for _, word := range strings.Fields(line) {
if !words[word] {
t.Errorf("word %q was split across lines", word)
}
}
}
sizeTwoStart := bytes.Index(out, sizeTwo)
for _, line := range printedLines(t, out[sizeTwoStart:]) {
if len(line) > 24 {
t.Errorf("size-2 line %q is %d chars, limit 24", line, len(line))
}
}
}
func TestRenderInlineTextContinuesLine(t *testing.T) {
out := render(t, receipt.Job{Elements: []receipt.Element{
{Type: "text", Text: "Total: ", Newline: boolPtr(false)},
{Type: "text", Text: "£5.00", Bold: true},
}})
if got := printedLines(t, out); len(got) != 1 || got[0] != "Total: \x9C5.00" {
t.Errorf("printed %q, want one line", got)
}
}
func TestRenderInlineMixedSizesWraps(t *testing.T) {
// 40 Font A columns used, then a size-2 word needing 2x6 = 12 columns:
// it cannot fit in the remaining 8 and must move to the next line.
out := render(t, receipt.Job{Elements: []receipt.Element{
{Type: "text", Text: strings.Repeat("x", 40), Newline: boolPtr(false)},
{Type: "text", Text: "BIGONE", Size: 2},
}})
lines := printedLines(t, out)
if len(lines) != 2 || lines[0] != strings.Repeat("x", 40) || lines[1] != "BIGONE" {
t.Errorf("printed %q", lines)
}
}
func TestRenderNoWrap(t *testing.T) {
long := strings.Repeat("y", 60)
out := render(t, receipt.Job{Elements: []receipt.Element{{Type: "text", Text: long, Wrap: boolPtr(false)}}})
if got := printedLines(t, out); len(got) != 1 || got[0] != long {
t.Errorf("printed %q, want the text untouched", got)
}
}
func TestRenderTextStyles(t *testing.T) {
out := render(t, receipt.Job{Elements: []receipt.Element{
{Type: "text", Text: "x", Bold: true, Underline: 2, Invert: true, Align: "right", Font: "b"},
}})
for name, cmd := range map[string][]byte{
"bold": {0x1B, 0x45, 1},
"underline": {0x1B, 0x2D, 2},
"reverse": {0x1D, 0x42, 1},
"font b": {0x1B, 0x4D, 1},
"right": justifyRight,
} {
if !bytes.Contains(out, cmd) {
t.Errorf("%s command % X missing", name, cmd)
}
}
// Styles are reset after the element.
if !bytes.Contains(out, append([]byte{0x1B, 0x45, 0, 0x1B, 0x2D, 0, 0x1D, 0x42, 0}, sizeOne...)) {
t.Error("styles not reset after text")
}
}
func TestRenderElements(t *testing.T) {
out := render(t, receipt.Job{Elements: []receipt.Element{
{Type: "feed", Lines: 3},
{Type: "qr", Data: "https://example.com", Align: "center"},
{Type: "barcode", Symbology: "code128", Data: "ABC-1"},
{Type: "raw", Hex: "1B 40"},
{Type: "cut", Mode: "full"},
}})
for name, cmd := range map[string][]byte{
"feed": {0x1B, 0x64, 3},
"qr store": append([]byte{0x1D, 0x28, 0x6B, 22, 0, 0x31, 0x50, 0x30}, "https://example.com"...),
"barcode": append([]byte{0x1D, 0x6B, 73, 7}, "{BABC-1"...),
"width": {0x1D, 0x77, 3},
"full cut": {0x1D, 0x56, 65, 0},
} {
if !bytes.Contains(out, cmd) {
t.Errorf("%s command % X missing", name, cmd)
}
}
if bytes.HasSuffix(out, partialCut) {
t.Error("an explicit final cut must not be followed by another")
}
}
func TestRenderCopies(t *testing.T) {
out := render(t, receipt.Job{Copies: 3, Elements: []receipt.Element{{Type: "text", Text: "copy"}}})
if n := bytes.Count(out, partialCut); n != 3 {
t.Errorf("%d cuts, want 3", n)
}
if n := bytes.Count(out, initialize); n != 1 {
t.Errorf("%d initialize commands, want 1", n)
}
}
func TestRenderBase64ImageCentered(t *testing.T) {
data := base64.StdEncoding.EncodeToString(pngData(t, 100, 10))
out := render(t, receipt.Job{Elements: []receipt.Element{{Type: "image", Base64: data, Align: "center"}}})
// The image is placed on a full-width 576-dot (72-byte) canvas.
header := []byte{0x1D, 0x76, 0x30, 0, 72, 0, 10, 0}
i := bytes.Index(out, header)
if i < 0 {
t.Fatalf("raster header % X not found", header)
}
if !bytes.Contains(out[:i], justifyLeft) {
t.Error("image must be sent left-justified; alignment is in the bitmap")
}
// The dark pixel at x=0 lands at x=(576-100)/2=238: byte 29, bit 6.
if got := out[i+8+29]; got != 0x02 {
t.Errorf("first row byte 29 = %08b, want 00000010", got)
}
}
func TestRenderImageFromURL(t *testing.T) {
fetcher := &fakeFetcher{data: pngData(t, 1200, 300)}
out, err := newRenderer(t, fetcher).Render(context.Background(), receipt.Job{Elements: []receipt.Element{
{Type: "image", URL: "https://images.example/logo.png"},
}})
if err != nil {
t.Fatal(err)
}
if len(fetcher.urls) != 1 || fetcher.urls[0] != "https://images.example/logo.png" {
t.Errorf("fetched %v", fetcher.urls)
}
// Scaled down to 576 dots wide, 144 tall.
if !bytes.Contains(out, []byte{0x1D, 0x76, 0x30, 0, 72, 0, 144, 0}) {
t.Error("scaled raster header not found")
}
}
func TestRenderFetchFailureProducesNothing(t *testing.T) {
fetchErr := errors.New("blocked")
out, err := newRenderer(t, &fakeFetcher{err: fetchErr}).Render(context.Background(), receipt.Job{Elements: []receipt.Element{
{Type: "text", Text: "before"},
{Type: "image", URL: "https://images.example/x.png"},
}})
if !errors.Is(err, fetchErr) || out != nil {
t.Errorf("Render = %d bytes, %v; want nil and the fetch error", len(out), err)
}
}
func TestValidate(t *testing.T) {
tests := []struct {
name string
job receipt.Job
wantErr string
}{
{"no elements", receipt.Job{}, "at least one element"},
{"too many copies", receipt.Job{Copies: 6, Elements: []receipt.Element{{Type: "cut"}}}, "copies must be 1-5"},
{"missing type", receipt.Job{Elements: []receipt.Element{{}}}, "type is required"},
{"unknown type", receipt.Job{Elements: []receipt.Element{{Type: "sparkle"}}}, `unknown type "sparkle"`},
{"text size", receipt.Job{Elements: []receipt.Element{{Type: "text", Size: 9}}}, "elements[0] (text): size, width and height must be 1-8"},
{"text align", receipt.Job{Elements: []receipt.Element{{Type: "text", Align: "middle"}}}, "align must be left, center or right"},
{"text font", receipt.Job{Elements: []receipt.Element{{Type: "text", Font: "c"}}}, "font must be a or b"},
{"underline", receipt.Job{Elements: []receipt.Element{{Type: "text", Underline: 3}}}, "underline must be 0, 1 or 2"},
{"feed lines", receipt.Job{Elements: []receipt.Element{{Type: "feed", Lines: 300}}}, "lines must be 1-255"},
{"qr data", receipt.Job{Elements: []receipt.Element{{Type: "qr"}}}, "data is required"},
{"qr size", receipt.Job{Elements: []receipt.Element{{Type: "qr", Data: "x", Size: 17}}}, "size must be 1-16"},
{"qr correction", receipt.Job{Elements: []receipt.Element{{Type: "qr", Data: "x", Correction: "Z"}}}, "correction must be L, M, Q or H"},
{"barcode symbology", receipt.Job{Elements: []receipt.Element{{Type: "barcode", Data: "1"}}}, "symbology is required"},
{"barcode data", receipt.Job{Elements: []receipt.Element{{Type: "barcode", Symbology: "ean13", Data: "12"}}}, "want 12 or 13 digits"},
{"barcode width", receipt.Job{Elements: []receipt.Element{{Type: "barcode", Symbology: "code39", Data: "A", Width: 9}}}, "width must be 2-6"},
{"image source", receipt.Job{Elements: []receipt.Element{{Type: "image"}}}, "url or base64 is required"},
{"image both", receipt.Job{Elements: []receipt.Element{{Type: "image", URL: "https://x/y", Base64: "AA=="}}}, "not both"},
{"image scheme", receipt.Job{Elements: []receipt.Element{{Type: "image", URL: "file:///etc/passwd"}}}, "http or https"},
{"image base64", receipt.Job{Elements: []receipt.Element{{Type: "image", Base64: "!!!"}}}, "not valid base64"},
{"raw hex", receipt.Job{Elements: []receipt.Element{{Type: "raw", Hex: "zz"}}}, "hex:"},
{"cut mode", receipt.Job{Elements: []receipt.Element{{Type: "cut", Mode: "half"}}}, "mode must be partial or full"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := tt.job.Validate()
var ve *receipt.ValidationError
if !errors.As(err, &ve) {
t.Fatalf("err = %v, want *ValidationError", err)
}
if !strings.Contains(err.Error(), tt.wantErr) {
t.Errorf("err = %q, want it to contain %q", err, tt.wantErr)
}
})
}
}
func TestValidateReportsEveryProblem(t *testing.T) {
err := receipt.Job{Elements: []receipt.Element{
{Type: "text", Size: 0},
{Type: "feed", Lines: -1},
{Type: "qr"},
}}.Validate()
var ve *receipt.ValidationError
if !errors.As(err, &ve) || len(ve.Problems) != 2 {
t.Fatalf("problems = %v, want 2 (feed and qr)", err)
}
}
func TestValidateAcceptsDataURI(t *testing.T) {
job := receipt.Job{Elements: []receipt.Element{{
Type: "image",
Base64: "data:image/png;base64," + base64.StdEncoding.EncodeToString([]byte("x")),
}}}
if err := job.Validate(); err != nil {
t.Errorf("Validate: %v", err)
}
}
+295
View File
@@ -0,0 +1,295 @@
package receipt
import (
"bytes"
"context"
"fmt"
"image"
"strings"
"unicode/utf8"
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/escpos"
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/raster"
)
// Fetcher downloads remote image data.
type Fetcher interface {
Fetch(ctx context.Context, url string) ([]byte, error)
}
// Options configures a Renderer.
type Options struct {
// Profile describes the printer; its DotsPerLine is the image width.
Profile escpos.Profile
// CodePage is the character table text is transcoded to.
CodePage escpos.CodePage
// Columns, when positive, overrides the Font A characters per line used
// for word wrapping.
Columns int
// MaxPixels caps decoded image size; MaxHeight caps printed image height
// in dots.
MaxPixels int
MaxHeight int
}
// Renderer turns jobs into ESC/POS command streams. It is safe for concurrent
// use.
type Renderer struct {
options Options
fetcher Fetcher
}
// NewRenderer returns a Renderer. fetcher loads images given by URL.
func NewRenderer(options Options, fetcher Fetcher) *Renderer {
if fetcher == nil {
panic("receipt.NewRenderer: fetcher must not be nil")
}
if options.Profile.DotsPerLine <= 0 || options.Profile.FontAWidth <= 0 || options.Profile.FontBWidth <= 0 {
panic("receipt.NewRenderer: profile must be set")
}
if options.MaxPixels <= 0 || options.MaxHeight <= 0 {
panic("receipt.NewRenderer: image limits must be positive")
}
return &Renderer{options: options, fetcher: fetcher}
}
// Render validates job, loads its images and returns the complete command
// stream. Nothing is returned unless the whole receipt rendered, so a failure
// never reaches the printer half-done.
func (r *Renderer) Render(ctx context.Context, job Job) ([]byte, error) {
if err := job.Validate(); err != nil {
return nil, err
}
images, err := r.loadImages(ctx, job)
if err != nil {
return nil, err
}
var body escpos.Builder
p := printer{b: &body, lineDots: r.textLineDots(), profile: r.options.Profile, codePage: r.options.CodePage}
for i, el := range job.Elements {
if err := p.element(el, images[i]); err != nil {
return nil, fmt.Errorf("rendering elements[%d] (%s): %w", i, el.Type, err)
}
}
p.endLine()
if last := job.Elements[len(job.Elements)-1]; last.Type != TypeCut {
body.Cut(escpos.CutPartial, 0)
}
var out escpos.Builder
out.Initialize()
out.SelectCodePage(r.options.CodePage)
for range job.copies() {
out.Raw(body.Bytes())
}
return bytes.Clone(out.Bytes()), nil
}
// textLineDots is the line width used for text layout.
func (r *Renderer) textLineDots() int {
if r.options.Columns > 0 {
return r.options.Columns * r.options.Profile.FontAWidth
}
return r.options.Profile.DotsPerLine
}
// loadImages fetches, decodes and dithers every image before anything is
// rendered, keyed by element index.
func (r *Renderer) loadImages(ctx context.Context, job Job) (map[int]*image.Paletted, error) {
images := make(map[int]*image.Paletted)
for i, el := range job.Elements {
if el.Type != TypeImage {
continue
}
img, err := r.loadImage(ctx, el)
if err != nil {
return nil, fmt.Errorf("elements[%d] (image): %w", i, err)
}
images[i] = img
}
return images, nil
}
func (r *Renderer) loadImage(ctx context.Context, el Element) (*image.Paletted, error) {
spec, err := el.imageSpec()
if err != nil {
return nil, err
}
data := spec.data
if spec.url != "" {
if data, err = r.fetcher.Fetch(ctx, spec.url); err != nil {
return nil, err
}
}
src, err := raster.Decode(data, r.options.MaxPixels)
if err != nil {
return nil, err
}
paper := r.options.Profile.DotsPerLine
width := min(src.Bounds().Dx(), paper)
if spec.width > 0 {
if spec.width > paper {
return nil, fmt.Errorf("width %d is wider than the %d-dot paper", spec.width, paper)
}
width = spec.width
}
mono, err := raster.Monochrome(src, width)
if err != nil {
return nil, err
}
if h := mono.Bounds().Dy(); h > r.options.MaxHeight {
return nil, fmt.Errorf("image is %d dots tall after scaling, limit is %d", h, r.options.MaxHeight)
}
var x int
switch spec.align {
case escpos.JustifyCenter:
x = (paper - width) / 2
case escpos.JustifyRight:
x = paper - width
}
return raster.Place(mono, paper, x)
}
// printer writes elements to a Builder while tracking the horizontal print
// position, in dots, so inline text can continue and wrap across elements.
type printer struct {
b *escpos.Builder
lineDots int
profile escpos.Profile
codePage escpos.CodePage
x int
}
func (p *printer) element(el Element, img *image.Paletted) error {
switch el.Type {
case TypeText:
return p.text(el)
case TypeFeed:
lines, err := el.feedLines()
if err != nil {
return err
}
p.b.Feed(lines)
p.x = 0
case TypeQR:
spec, err := el.qrSpec()
if err != nil {
return err
}
p.endLine()
p.b.Justify(spec.align)
return p.b.QRCode([]byte(el.Data), spec.size, spec.correction)
case TypeBarcode:
spec, err := el.barcodeSpec()
if err != nil {
return err
}
p.endLine()
p.b.Justify(spec.align)
p.b.BarcodeHeight(uint8(spec.height))
if err := p.b.BarcodeWidth(spec.width); err != nil {
return err
}
p.b.BarcodeHRI(spec.hri)
return p.b.Barcode(spec.symbology, el.Data)
case TypeImage:
p.endLine()
// Alignment is baked into the image; see Renderer.loadImage.
p.b.Justify(escpos.JustifyLeft)
return p.b.RasterImage(img)
case TypeRaw:
data, err := el.rawBytes()
if err != nil {
return err
}
p.b.Raw(data)
// The position after arbitrary bytes is unknown; assume a fresh line.
p.x = 0
case TypeCut:
mode, err := el.cutMode()
if err != nil {
return err
}
p.endLine()
p.b.Cut(mode, 0)
default:
return fmt.Errorf("unknown type %q", el.Type)
}
return nil
}
func (p *printer) text(el Element) error {
spec, err := el.textSpec()
if err != nil {
return err
}
glyph := p.profile.GlyphWidth(spec.font) * spec.width
p.b.Justify(spec.align)
p.b.Font(spec.font)
if err := p.b.Size(spec.width, spec.height); err != nil {
return err
}
p.b.Bold(spec.bold)
p.b.Underline(spec.underline)
p.b.Reverse(spec.invert)
text := sanitize(el.Text)
if spec.wrap {
text = expandTabs(text, p.x/glyph)
lines := wrap(text, (p.lineDots-p.x)/glyph, p.lineDots/glyph)
for i, line := range lines {
if i > 0 {
p.b.LineFeed()
p.x = 0
}
p.b.Text(p.codePage.Encode(line))
p.x += utf8.RuneCountInString(line) * glyph
}
} else {
p.b.Text(p.codePage.Encode(text))
p.advance(text, glyph)
}
if spec.newline {
p.b.LineFeed()
p.x = 0
}
// Reset styles so they cannot leak into barcodes, QR codes or raw data.
p.b.Bold(false)
p.b.Underline(escpos.UnderlineNone)
p.b.Reverse(false)
if err := p.b.Size(1, 1); err != nil {
return err
}
p.b.Font(escpos.FontA)
return nil
}
// advance updates the position after unwrapped text, which the printer wraps
// by itself when it overflows.
func (p *printer) advance(text string, glyph int) {
if i := strings.LastIndexByte(text, '\n'); i >= 0 {
p.x = 0
text = text[i+1:]
}
p.x += utf8.RuneCountInString(text) * glyph
if p.lineDots > 0 {
p.x %= p.lineDots
}
}
// endLine finishes a partially printed line so the next element starts at
// the left margin.
func (p *printer) endLine() {
if p.x > 0 {
p.b.LineFeed()
p.x = 0
}
}
+216
View File
@@ -0,0 +1,216 @@
// Package safehttp fetches remote resources on behalf of API clients while
// refusing to connect to internal network addresses, which guards against
// server-side request forgery (SSRF).
//
// Addresses are checked at dial time, after DNS resolution, so a hostname that
// resolves (or re-resolves) to a private address is refused too.
package safehttp
import (
"context"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/netip"
"net/url"
"strings"
"syscall"
"time"
)
// maxRedirects bounds redirect chains.
const maxRedirects = 5
var (
// ErrBlockedAddress is returned when a destination resolves to an address
// that is not allowed.
ErrBlockedAddress = errors.New("safehttp: destination address is not allowed")
// ErrHostNotAllowed is returned when an allowlist is configured and the
// host is not on it.
ErrHostNotAllowed = errors.New("safehttp: host is not on the allowlist")
// ErrScheme is returned for URLs that are not http or https.
ErrScheme = errors.New("safehttp: only http and https URLs are allowed")
// ErrTooLarge is returned when a response body exceeds the size limit.
ErrTooLarge = errors.New("safehttp: response exceeds size limit")
)
// Options configures a Client.
type Options struct {
// Timeout bounds a whole fetch, including redirects and reading the body.
Timeout time.Duration
// MaxBytes is the largest response body accepted.
MaxBytes int64
// AllowPrivate permits loopback, private, link-local and other
// non-public destinations.
AllowPrivate bool
// AllowedHosts, when non-empty, restricts fetches to these hostnames.
// Listed hosts may resolve to private addresses.
AllowedHosts []string
}
// Client fetches URLs with SSRF protection. It is safe for concurrent use.
type Client struct {
http *http.Client
maxBytes int64
allowPrivate bool
allowed map[string]struct{}
}
// New returns a Client configured by o.
func New(o Options) *Client {
c := &Client{
maxBytes: o.MaxBytes,
allowPrivate: o.AllowPrivate,
allowed: make(map[string]struct{}, len(o.AllowedHosts)),
}
for _, host := range o.AllowedHosts {
c.allowed[strings.ToLower(host)] = struct{}{}
}
guarded := &net.Dialer{Timeout: o.Timeout, Control: c.checkDialAddress}
plain := &net.Dialer{Timeout: o.Timeout}
transport := &http.Transport{
// No proxy: a proxy would make the dial-time address check useless.
Proxy: nil,
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
host, _, err := net.SplitHostPort(addr)
if err != nil {
return nil, err
}
if c.allowlisted(host) {
return plain.DialContext(ctx, network, addr)
}
return guarded.DialContext(ctx, network, addr)
},
ForceAttemptHTTP2: true,
MaxIdleConns: 10,
IdleConnTimeout: 30 * time.Second,
TLSHandshakeTimeout: o.Timeout,
ResponseHeaderTimeout: o.Timeout,
}
c.http = &http.Client{
Transport: transport,
Timeout: o.Timeout,
CheckRedirect: func(req *http.Request, via []*http.Request) error {
if len(via) >= maxRedirects {
return fmt.Errorf("safehttp: stopped after %d redirects", maxRedirects)
}
return c.checkURL(req.URL)
},
}
return c
}
// Fetch GETs rawURL and returns the response body.
func (c *Client) Fetch(ctx context.Context, rawURL string) ([]byte, error) {
u, err := url.Parse(rawURL)
if err != nil {
return nil, fmt.Errorf("parsing URL: %w", err)
}
if err := c.checkURL(u); err != nil {
return nil, err
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)
if err != nil {
return nil, fmt.Errorf("building request: %w", err)
}
req.Header.Set("User-Agent", "uberbringer")
resp, err := c.http.Do(req)
if err != nil {
return nil, fmt.Errorf("fetching %s: %w", u.Redacted(), err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("fetching %s: unexpected status %s", u.Redacted(), resp.Status)
}
if resp.ContentLength > c.maxBytes {
return nil, fmt.Errorf("%w: %d bytes, limit is %d", ErrTooLarge, resp.ContentLength, c.maxBytes)
}
body, err := io.ReadAll(io.LimitReader(resp.Body, c.maxBytes+1))
if err != nil {
return nil, fmt.Errorf("reading %s: %w", u.Redacted(), err)
}
if int64(len(body)) > c.maxBytes {
return nil, fmt.Errorf("%w: limit is %d bytes", ErrTooLarge, c.maxBytes)
}
return body, nil
}
// checkURL validates the scheme and, when an allowlist is set, the host.
func (c *Client) checkURL(u *url.URL) error {
if u.Scheme != "http" && u.Scheme != "https" {
return fmt.Errorf("%w: %q", ErrScheme, u.Scheme)
}
if u.Hostname() == "" {
return fmt.Errorf("safehttp: URL has no host")
}
if len(c.allowed) > 0 && !c.allowlisted(u.Hostname()) {
return fmt.Errorf("%w: %s", ErrHostNotAllowed, u.Hostname())
}
return nil
}
func (c *Client) allowlisted(host string) bool {
_, ok := c.allowed[strings.ToLower(host)]
return ok
}
// checkDialAddress runs after DNS resolution with the concrete IP the dialer
// is about to connect to.
func (c *Client) checkDialAddress(_, address string, _ syscall.RawConn) error {
if c.allowPrivate {
return nil
}
addrPort, err := netip.ParseAddrPort(address)
if err != nil {
return fmt.Errorf("%w: %s", ErrBlockedAddress, address)
}
if !IsPublic(addrPort.Addr()) {
return fmt.Errorf("%w: %s", ErrBlockedAddress, addrPort.Addr())
}
return nil
}
// nonPublic lists ranges that are not reachable on the public internet and
// are not already covered by the netip.Addr predicates in IsPublic. It is
// effectively constant and must not be modified.
var nonPublic = []netip.Prefix{
netip.MustParsePrefix("0.0.0.0/8"), // "this" network
netip.MustParsePrefix("100.64.0.0/10"), // carrier-grade NAT
netip.MustParsePrefix("192.0.0.0/24"), // IETF protocol assignments
netip.MustParsePrefix("192.0.2.0/24"), // TEST-NET-1
netip.MustParsePrefix("198.18.0.0/15"), // benchmarking
netip.MustParsePrefix("198.51.100.0/24"), // TEST-NET-2
netip.MustParsePrefix("203.0.113.0/24"), // TEST-NET-3
netip.MustParsePrefix("240.0.0.0/4"), // reserved, includes broadcast
netip.MustParsePrefix("2001:db8::/32"), // documentation
netip.MustParsePrefix("64:ff9b:1::/48"), // local-use NAT64
}
// IsPublic reports whether addr is a globally routable unicast address.
// Loopback, private (RFC 1918 and IPv6 ULA), link-local (which includes cloud
// metadata endpoints), multicast and reserved ranges are not public.
func IsPublic(addr netip.Addr) bool {
addr = addr.Unmap()
if !addr.IsValid() || addr.IsLoopback() || addr.IsPrivate() || addr.IsUnspecified() ||
addr.IsLinkLocalUnicast() || addr.IsLinkLocalMulticast() ||
addr.IsInterfaceLocalMulticast() || addr.IsMulticast() {
return false
}
for _, prefix := range nonPublic {
if prefix.Contains(addr) {
return false
}
}
return true
}
+150
View File
@@ -0,0 +1,150 @@
package safehttp_test
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"net/netip"
"net/url"
"strings"
"testing"
"time"
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/safehttp"
)
func newServer(t *testing.T, body string) *httptest.Server {
t.Helper()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte(body)) // test server; the client side asserts the outcome
}))
t.Cleanup(srv.Close)
return srv
}
func options() safehttp.Options {
return safehttp.Options{Timeout: 5 * time.Second, MaxBytes: 1 << 20}
}
func TestFetchBlocksLoopbackByDefault(t *testing.T) {
srv := newServer(t, "secret")
_, err := safehttp.New(options()).Fetch(context.Background(), srv.URL)
if !errors.Is(err, safehttp.ErrBlockedAddress) {
t.Fatalf("err = %v, want ErrBlockedAddress", err)
}
}
func TestFetchBlocksHostnameResolvingToLoopback(t *testing.T) {
srv := newServer(t, "secret")
u, _ := url.Parse(srv.URL)
u.Host = "localhost:" + u.Port()
_, err := safehttp.New(options()).Fetch(context.Background(), u.String())
if !errors.Is(err, safehttp.ErrBlockedAddress) {
t.Fatalf("err = %v, want ErrBlockedAddress", err)
}
}
func TestFetchAllowPrivate(t *testing.T) {
srv := newServer(t, "hello")
o := options()
o.AllowPrivate = true
body, err := safehttp.New(o).Fetch(context.Background(), srv.URL)
if err != nil || string(body) != "hello" {
t.Fatalf("Fetch = %q, %v", body, err)
}
}
func TestFetchAllowlistedHostMayBePrivate(t *testing.T) {
srv := newServer(t, "hello")
o := options()
o.AllowedHosts = []string{"127.0.0.1"}
body, err := safehttp.New(o).Fetch(context.Background(), srv.URL)
if err != nil || string(body) != "hello" {
t.Fatalf("Fetch = %q, %v", body, err)
}
}
func TestFetchAllowlistRejectsOtherHosts(t *testing.T) {
o := options()
o.AllowedHosts = []string{"images.example"}
_, err := safehttp.New(o).Fetch(context.Background(), "https://evil.example/x.png")
if !errors.Is(err, safehttp.ErrHostNotAllowed) {
t.Fatalf("err = %v, want ErrHostNotAllowed", err)
}
}
func TestFetchRedirectToOtherHostIsChecked(t *testing.T) {
target := newServer(t, "internal")
targetURL, _ := url.Parse(target.URL)
// The allowlisted redirector sends the client to "localhost", which is
// not on the allowlist, so the redirect must be refused.
redirector := httptest.NewServer(http.RedirectHandler("http://localhost:"+targetURL.Port(), http.StatusFound))
t.Cleanup(redirector.Close)
o := options()
o.AllowedHosts = []string{"127.0.0.1"}
_, err := safehttp.New(o).Fetch(context.Background(), redirector.URL)
if !errors.Is(err, safehttp.ErrHostNotAllowed) {
t.Fatalf("err = %v, want ErrHostNotAllowed", err)
}
}
func TestFetchRejectsSchemes(t *testing.T) {
for _, raw := range []string{"file:///etc/passwd", "ftp://example.com/x", "gopher://x"} {
_, err := safehttp.New(options()).Fetch(context.Background(), raw)
if !errors.Is(err, safehttp.ErrScheme) {
t.Errorf("Fetch(%q) err = %v, want ErrScheme", raw, err)
}
}
}
func TestFetchSizeLimit(t *testing.T) {
srv := newServer(t, strings.Repeat("x", 2048))
o := options()
o.AllowPrivate = true
o.MaxBytes = 1024
_, err := safehttp.New(o).Fetch(context.Background(), srv.URL)
if !errors.Is(err, safehttp.ErrTooLarge) {
t.Fatalf("err = %v, want ErrTooLarge", err)
}
}
func TestFetchNon200(t *testing.T) {
srv := httptest.NewServer(http.NotFoundHandler())
t.Cleanup(srv.Close)
o := options()
o.AllowPrivate = true
if _, err := safehttp.New(o).Fetch(context.Background(), srv.URL); err == nil {
t.Fatal("expected error for 404")
}
}
func TestIsPublic(t *testing.T) {
tests := map[string]bool{
"8.8.8.8": true,
"1.1.1.1": true,
"2606:4700::1111": true,
"127.0.0.1": false,
"10.1.2.3": false,
"172.16.0.1": false,
"192.168.1.245": false,
"169.254.169.254": false, // cloud metadata
"100.64.0.1": false,
"0.0.0.0": false,
"255.255.255.255": false,
"::1": false,
"fd00::1": false,
"fe80::1": false,
"::ffff:127.0.0.1": false, // IPv4-mapped loopback
"::ffff:192.168.0.1": false,
"224.0.0.1": false,
"2001:db8::1": false,
"::ffff:93.184.216.34": true,
}
for raw, want := range tests {
if got := safehttp.IsPublic(netip.MustParseAddr(raw)); got != want {
t.Errorf("IsPublic(%s) = %v, want %v", raw, got, want)
}
}
}