Test / Lint, test and build (push) Successful in 3m17s
Module
- The module path is now the bare "uberbringer"; imports read
uberbringer/internal/... The banner keeps the Gitea URL.
CI and releases
- Workflows move to .gitea/workflows: test.yml (every branch push:
gofmt, goimports, tidy, vet, staticcheck, race tests, goreleaser
snapshot), security.yml (govulncheck weekly and on main) and a hardened
release.yml (v* tags on main only, tags fetched, goreleaser pinned to
2.20.3). The broken labeler workflow is removed.
- go.mod pins toolchain go1.27.4, which fixes GO-2026-6859; workflows
check that the running Go matches it.
- .goreleaser.yaml: tidy check that never writes, reproducible file times,
prerelease: auto, a release header linking CHANGELOG.md, and archives
that ship CHANGELOG.md, the example config and the systemd unit.
- Makefile mirrors the CI gate; .dockerignore is an allowlist.
API and tests
- Every error answers {"error", "code", "details"} with a stable code from
server/errors.go; the framework's own error text is never sent.
- Panics and unexpected errors are logged and reported to Sentry once;
refusals are not logged as failures. /healthz sends no-store.
- TestRoutesConform requires auth, rate limiting and the body limit on
every /api/v1 route.
- Race-prone tests no longer rely on freed ports or sleeps; serve takes
an injected listener.
- The test config uses a placeholder secret instead of a real one.
Install and packaging
- install.sh resolves the latest release through the Gitea API, verifies
checksums, requests a certificate only when none exists, installs the
hardened packaging/uberbringer.service and writes the first token to a
0600 file instead of printing it. It is now executable in git.
Docs
- CLAUDE.md, CHANGELOG.md (0.2.0 with breaking changes and upgrade
steps), docs/design.md, and docs/plans/formatters.md for the planned
CP437 blocks, modules and ntfy printing. README updated throughout.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
191 lines
5.9 KiB
Go
191 lines
5.9 KiB
Go
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"
|
|
|
|
"uberbringer/internal/app/uberbringer/server"
|
|
"uberbringer/internal/pkg/config"
|
|
"uberbringer/internal/pkg/escpos"
|
|
"uberbringer/internal/pkg/printer"
|
|
"uberbringer/internal/pkg/printqueue"
|
|
"uberbringer/internal/pkg/receipt"
|
|
"uberbringer/internal/pkg/safehttp"
|
|
)
|
|
|
|
// sentryFlushTimeout bounds how long shutdown waits for queued error reports.
|
|
const sentryFlushTimeout = 2 * time.Second
|
|
|
|
// serve loads the config at configPath and runs the daemon on the address it
|
|
// names 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
|
|
}
|
|
return run(ctx, cfg, build, out, listenTCP)
|
|
}
|
|
|
|
// listenFunc opens the HTTP listener on addr.
|
|
type listenFunc func(ctx context.Context, addr string) (net.Listener, error)
|
|
|
|
func listenTCP(ctx context.Context, addr string) (net.Listener, error) {
|
|
var lc net.ListenConfig
|
|
return lc.Listen(ctx, "tcp", addr)
|
|
}
|
|
|
|
// run wires every component from cfg, opens the HTTP listener with listen
|
|
// once the wiring has succeeded, and serves until ctx is cancelled.
|
|
func run(ctx context.Context, cfg *config.Config, build BuildInfo, out io.Writer, listen listenFunc) error {
|
|
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))
|
|
ln, err := listen(ctx, 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()
|
|
}
|