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>
259 lines
7.1 KiB
Go
259 lines
7.1 KiB
Go
package printqueue_test
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"io"
|
|
"log/slog"
|
|
"strings"
|
|
"sync"
|
|
"testing"
|
|
"time"
|
|
|
|
"uberbringer/internal/pkg/printqueue"
|
|
"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. cancel cancels Run's context and
|
|
// wait blocks until Run has returned.
|
|
func startQueue(t *testing.T, q *printqueue.Queue) (cancel, wait func()) {
|
|
t.Helper()
|
|
ctx, cancelRun := context.WithCancel(context.Background())
|
|
done := make(chan struct{})
|
|
go func() {
|
|
defer close(done)
|
|
if err := q.Run(ctx); err != nil {
|
|
t.Error(err)
|
|
}
|
|
}()
|
|
wait = func() { <-done }
|
|
t.Cleanup(func() { cancelRun(); wait() })
|
|
return cancelRun, wait
|
|
}
|
|
|
|
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) {
|
|
reported := make(chan printqueue.JobID, 2)
|
|
sender := &fakeSender{failures: 10}
|
|
q := newQueue(fakeRenderer{}, sender, printqueue.Options{
|
|
Retries: 2,
|
|
OnFailure: func(id printqueue.JobID, _ error) { reported <- id },
|
|
})
|
|
cancel, wait := 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)
|
|
}
|
|
// OnFailure runs after the job is marked failed, so wait for it.
|
|
select {
|
|
case id := <-reported:
|
|
if id != st.ID {
|
|
t.Errorf("OnFailure got %s, want %s", id, st.ID)
|
|
}
|
|
case <-time.After(5 * time.Second):
|
|
t.Fatal("OnFailure was not called")
|
|
}
|
|
cancel()
|
|
wait()
|
|
if n := len(reported); n != 0 {
|
|
t.Errorf("OnFailure called %d more times, want once", n)
|
|
}
|
|
}
|
|
|
|
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{})
|
|
cancel, wait := startQueue(t, q)
|
|
|
|
first, _ := q.Submit(job("first"))
|
|
waitForState(t, q, first.ID, printqueue.StatePrinting)
|
|
second, _ := q.Submit(job("second"))
|
|
|
|
// Cancel while the first send is still blocked, so Run is shutting down
|
|
// by the time that send completes.
|
|
cancel()
|
|
close(sender.block)
|
|
wait()
|
|
|
|
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)
|
|
}
|
|
}
|
|
}
|