Files
uberbringer/internal/pkg/printer/printer.go
T
57_WolveandClaude Opus 5.5 9b91109550
Test / Lint, test and build (push) Successful in 3m17s
Adopt norn's CI, release, API and docs practices; bare module path
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>
2026-11-29 23:27:48 -06:00

147 lines
4.6 KiB
Go

// 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"
"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()
writeDeadline, _ := c.deadline(ctx, c.writeTimeout)
if err := conn.SetWriteDeadline(writeDeadline); 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, normalized so that offline
// causes are only reported while the printer is offline. It returns
// ErrStatusUnsupported when the printer is reachable but gives no answer
// within statusTimeout, and an error wrapping context.DeadlineExceeded when
// ctx ran out first, since the printer may simply not have answered yet.
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, fromContext := 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() {
if fromContext {
return status, fmt.Errorf("reading printer status: %w", context.DeadlineExceeded)
}
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.Normalized(), 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, and
// whether the context deadline was the one chosen.
func (c *Client) deadline(ctx context.Context, d time.Duration) (time.Time, bool) {
deadline := time.Now().Add(d)
if ctxDeadline, ok := ctx.Deadline(); ok && ctxDeadline.Before(deadline) {
return ctxDeadline, true
}
return deadline, false
}