Refactor to Go standards; add print queue and own ESC/POS library
CI / Lint, test and scan (push) Successful in 1m41s
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:
1 parent
bb73348433
commit
6502d9551d
807 files changed
+6659
-500291
No files matched your search
@@ -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
|
||||
}
|
||||
Reference in new issue
Block a user