Keep print jobs on disk in state.dir
Breaking: with state.dir set, jobs still waiting when the daemon stops or crashes print after the next start, in order and however old, instead of being marked failed or forgotten; a client that resends such jobs must stop. The Docker image sets state.dir, so a container keeps its jobs in /var/lib/uberbringer, and loses them with the container unless a volume is mounted there. The owner decided that jobs survive a restart and that a restart never prints a receipt twice. When state.dir is set, the daemon now opens the SQLite job store there, jobs.db, and the queue restores it before the subscriptions are made and before anything is served, so restored jobs go ahead of new ones and a second daemon on the directory stops before it reads the subscriptions' state. Without state.dir the queue keeps its jobs in memory, as before. The store closes once the queue has stopped. A job's sending mark is synced before its first byte, so one caught mid write reads uncertain after the restart and is never sent again; a job that had not reached the printer prints once. A store that cannot be opened stops the start with an error naming the file, rather than starting empty and forgetting which receipts are in doubt. The unit gains UMask=0077, so the store's files are its user's alone, and says why systemd's 90 s stop timeout is enough; the Dockerfile and docs/docker.md ask for --stop-timeout 40. design.md replaces "The queue lives in memory" with the store, the state machine, the sync policy, store failures, stage 1a's numbers, and that the ARM builds ship the store untested on ARM hardware. install.md and docker.md say how to set aside a store that will not open; configuration.md, api.md, cli.md and ntfy.md say what survives a restart. The license notices gain the driver's modules. TestServeRestart runs the daemon twice on one directory: jobs queued when the first run stops, its printer refusing connections, print in order after the restart, ahead of a new job, and a job seeded in sending between the runs reads uncertain and never reaches the printer. Part of stage 1d of docs/plans/job-store.md (decisions 14 and 15). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
341353f702
commit
5cc4614ad7
20 files changed
+5144
-93
No files matched your search
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,243 @@
|
||||
package uberbringer
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"go.jetify.com/typeid"
|
||||
|
||||
"uberbringer/internal/pkg/config"
|
||||
"uberbringer/internal/pkg/jobstore"
|
||||
"uberbringer/internal/pkg/printqueue"
|
||||
)
|
||||
|
||||
// daemon is a run of the daemon in a test, with a token for its API.
|
||||
type daemon struct {
|
||||
base string
|
||||
token string
|
||||
cancel context.CancelFunc
|
||||
served chan error
|
||||
}
|
||||
|
||||
// startDaemon runs the daemon on cfg until stop is called, and waits until
|
||||
// it answers.
|
||||
func startDaemon(t *testing.T, cfg *config.Config) *daemon {
|
||||
t.Helper()
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = ln.Close() })
|
||||
listen := func(context.Context, string) (net.Listener, error) { return ln, nil }
|
||||
token, err := signToken([]byte(cfg.API.Secret), tokenSpec{subject: "test"}, time.Now())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
d := &daemon{base: "http://" + ln.Addr().String(), token: token, cancel: cancel, served: make(chan error, 1)}
|
||||
t.Cleanup(cancel)
|
||||
go func() { d.served <- run(ctx, cfg, BuildInfo{Version: "test"}, io.Discard, listen, skipSync) }()
|
||||
waitFor(t, func() bool {
|
||||
resp, err := http.Get(d.base + "/")
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
resp.Body.Close()
|
||||
return resp.StatusCode == http.StatusOK
|
||||
})
|
||||
return d
|
||||
}
|
||||
|
||||
// stop shuts the daemon down and waits for it.
|
||||
func (d *daemon) stop(t *testing.T) {
|
||||
t.Helper()
|
||||
d.cancel()
|
||||
select {
|
||||
case err := <-d.served:
|
||||
if err != nil {
|
||||
t.Fatalf("the daemon returned %v after shutdown", err)
|
||||
}
|
||||
case <-time.After(15 * time.Second):
|
||||
t.Fatal("the daemon did not shut down")
|
||||
}
|
||||
}
|
||||
|
||||
// print sends a receipt of one line of text and returns its job's ID.
|
||||
func (d *daemon) print(t *testing.T, text string) string {
|
||||
t.Helper()
|
||||
body := fmt.Sprintf(`{"elements":[{"type":"text","text":%q}]}`, text)
|
||||
req, _ := http.NewRequest(http.MethodPost, d.base+"/api/v1/print", strings.NewReader(body))
|
||||
req.Header.Set("Authorization", "Bearer "+d.token)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
var queued struct{ ID string }
|
||||
if err := json.NewDecoder(resp.Body).Decode(&queued); err != nil || resp.StatusCode != http.StatusAccepted {
|
||||
t.Fatalf("POST /api/v1/print = %d, %v", resp.StatusCode, err)
|
||||
}
|
||||
return queued.ID
|
||||
}
|
||||
|
||||
// jobStatus is the part of a job's status the tests read.
|
||||
type jobStatus struct {
|
||||
Status, Error string
|
||||
}
|
||||
|
||||
// status returns the status of job id, or job_not_found's code.
|
||||
func (d *daemon) status(t *testing.T, id string) jobStatus {
|
||||
t.Helper()
|
||||
req, _ := http.NewRequest(http.MethodGet, d.base+"/api/v1/jobs/"+id, nil)
|
||||
req.Header.Set("Authorization", "Bearer "+d.token)
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
var st struct {
|
||||
jobStatus
|
||||
Code string
|
||||
}
|
||||
if err := json.NewDecoder(resp.Body).Decode(&st); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if st.Code != "" {
|
||||
return jobStatus{Status: st.Code}
|
||||
}
|
||||
return st.jobStatus
|
||||
}
|
||||
|
||||
// seedSending stores a job whose delivery is in sending, as the daemon
|
||||
// leaves one that dies while it writes the job to the printer.
|
||||
func seedSending(t *testing.T, dir, text string) string {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
store, err := jobstore.Open(ctx, dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() {
|
||||
if err := store.Close(); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}()
|
||||
id, err := typeid.New[printqueue.JobID]()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
r := printqueue.Record{
|
||||
Seq: 100, ID: id, Source: "print", Ref: "req_seeded", CreatedAt: now,
|
||||
Deliveries: []printqueue.Delivery{{Seq: 100, Printer: printqueue.DefaultPrinter, State: printqueue.StoredQueued}},
|
||||
}
|
||||
job := fmt.Sprintf(`{"elements":[{"type":"text","text":%q}]}`, text)
|
||||
if err := store.Add(ctx, r, []byte(job), false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
d := r.Deliveries[0]
|
||||
d.Attempts, d.StartedAt, d.SentAt = 1, now, now
|
||||
if err := store.Sending(ctx, d); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return id.String()
|
||||
}
|
||||
|
||||
// A job store that cannot be opened stops the start with an error naming
|
||||
// its file, rather than starting empty.
|
||||
func TestRunRefusesAStoreItCannotOpen(t *testing.T) {
|
||||
stateDir := t.TempDir()
|
||||
file := filepath.Join(stateDir, jobstore.FileName)
|
||||
if err := os.WriteFile(file, bytes.Repeat([]byte("not a database "), 500), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg := testConfig(9100)
|
||||
cfg.State.Dir = stateDir
|
||||
err := run(context.Background(), cfg, BuildInfo{Version: "test"}, io.Discard, noListen(t), skipSync)
|
||||
if err == nil || !strings.Contains(err.Error(), file) {
|
||||
t.Errorf("run = %v, want an error naming %s", err, file)
|
||||
}
|
||||
}
|
||||
|
||||
// freePort returns a port on 127.0.0.1 that nothing listens on, so that a
|
||||
// connection to it is refused until a listener takes it.
|
||||
func freePort(t *testing.T) int {
|
||||
t.Helper()
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
port := ln.Addr().(*net.TCPAddr).Port
|
||||
if err := ln.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return port
|
||||
}
|
||||
|
||||
// TestServeRestart runs the daemon twice on one state directory. Jobs still
|
||||
// queued when the first run stops print after the restart, ahead of a job
|
||||
// sent after it, and their statuses answer; a job that was being sent when
|
||||
// the daemon died reads uncertain and never reaches the printer.
|
||||
func TestServeRestart(t *testing.T) {
|
||||
stateDir := t.TempDir()
|
||||
|
||||
// The first run's printer refuses connections, so its jobs stay queued.
|
||||
cfg := testConfig(freePort(t))
|
||||
cfg.State.Dir = stateDir
|
||||
cfg.Printer.RetryDelay = time.Minute
|
||||
first := startDaemon(t, cfg)
|
||||
one := first.print(t, "first receipt")
|
||||
two := first.print(t, "second receipt")
|
||||
first.stop(t)
|
||||
|
||||
seeded := seedSending(t, stateDir, "never sent again")
|
||||
|
||||
// The second run's printer comes up only once a new job is queued, so
|
||||
// the restored jobs are still waiting when it arrives.
|
||||
port := freePort(t)
|
||||
cfg = testConfig(port)
|
||||
cfg.State.Dir = stateDir
|
||||
cfg.Printer.RetryDelay = 100 * time.Millisecond
|
||||
cfg.Printer.Retries = 10
|
||||
second := startDaemon(t, cfg)
|
||||
if st := second.status(t, seeded); st.Status != "uncertain" || !strings.Contains(st.Error, "may have printed") {
|
||||
t.Errorf("the job seeded in sending: %+v, want it uncertain", st)
|
||||
}
|
||||
three := second.print(t, "third receipt")
|
||||
for _, id := range []string{one, two, three} {
|
||||
if st := second.status(t, id); st.Status == "done" {
|
||||
t.Fatalf("job %s printed before the printer was up", id)
|
||||
}
|
||||
}
|
||||
printer := startFakePrinterOn(t, fmt.Sprintf("127.0.0.1:%d", port))
|
||||
waitFor(t, func() bool { return second.status(t, three).Status == "done" })
|
||||
for _, id := range []string{one, two} {
|
||||
if st := second.status(t, id); st.Status != "done" {
|
||||
t.Errorf("job %s: %+v after the restart, want done", id, st)
|
||||
}
|
||||
}
|
||||
|
||||
received := printer.received()
|
||||
at := func(text string) int { return bytes.Index(received, []byte(text)) }
|
||||
if !(at("first receipt") >= 0 && at("first receipt") < at("second receipt") && at("second receipt") < at("third receipt")) {
|
||||
t.Errorf("the printer received %q, want the restored jobs in order, then the new one", received)
|
||||
}
|
||||
if at("never sent again") >= 0 {
|
||||
t.Error("the job that was being sent was sent again")
|
||||
}
|
||||
if st := second.status(t, seeded); st.Status != "uncertain" {
|
||||
t.Errorf("the seeded job: %+v, want it still uncertain", st)
|
||||
}
|
||||
second.stop(t)
|
||||
}
|
||||
@@ -18,6 +18,7 @@ import (
|
||||
"uberbringer/internal/app/uberbringer/server"
|
||||
"uberbringer/internal/pkg/config"
|
||||
"uberbringer/internal/pkg/escpos"
|
||||
"uberbringer/internal/pkg/jobstore"
|
||||
"uberbringer/internal/pkg/printer"
|
||||
"uberbringer/internal/pkg/printqueue"
|
||||
"uberbringer/internal/pkg/receipt"
|
||||
@@ -75,10 +76,15 @@ func run(ctx context.Context, cfg *config.Config, build BuildInfo, out io.Writer
|
||||
if err := prepareStateDir(cfg.State.Dir); err != nil {
|
||||
return err
|
||||
}
|
||||
subscribers, err := newSubscribers(cfg, logger, syncState)
|
||||
// The store locks its file, so a second daemon on the same directory
|
||||
// stops here, before it reads the subscriptions' state files.
|
||||
store, err := openStore(ctx, cfg.State.Dir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// This runs once run returns, after the group below, so the queue has
|
||||
// stopped before the store closes.
|
||||
defer closeStore(store, logger)
|
||||
|
||||
fetcher := safehttp.New(safehttp.Options{
|
||||
Timeout: cfg.Images.Timeout,
|
||||
@@ -90,8 +96,6 @@ func run(ctx context.Context, cfg *config.Config, build BuildInfo, out io.Writer
|
||||
printerClient := printer.NewClient(
|
||||
net.JoinHostPort(cfg.Printer.Address, strconv.Itoa(cfg.Printer.Port)),
|
||||
cfg.Printer.DialTimeout, cfg.Printer.WriteTimeout)
|
||||
store := printqueue.NewMemoryStore()
|
||||
defer closeStore(store, logger)
|
||||
queue := printqueue.New(renderer, printerClient, store, logger, printqueue.Options{
|
||||
Size: cfg.Queue.Size,
|
||||
History: cfg.Queue.History,
|
||||
@@ -104,6 +108,10 @@ func run(ctx context.Context, cfg *config.Config, build BuildInfo, out io.Writer
|
||||
if err := queue.Restore(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
subscribers, err := newSubscribers(cfg, logger, syncState)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
srv := server.New(server.Config{
|
||||
Info: server.Info{
|
||||
Project: Project,
|
||||
@@ -256,6 +264,19 @@ func runQueue(ctx context.Context, queue *printqueue.Queue, logger *slog.Logger)
|
||||
return nil
|
||||
}
|
||||
|
||||
// openStore opens the job store in the state directory dir, or keeps jobs
|
||||
// in memory when there is none.
|
||||
func openStore(ctx context.Context, dir string) (printqueue.Store, error) {
|
||||
if dir == "" {
|
||||
return printqueue.NewMemoryStore(), nil
|
||||
}
|
||||
store, err := jobstore.Open(ctx, dir)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return store, nil
|
||||
}
|
||||
|
||||
// closeStore releases the job store once the daemon has stopped.
|
||||
func closeStore(store printqueue.Store, logger *slog.Logger) {
|
||||
if err := store.Close(); err != nil {
|
||||
|
||||
@@ -32,7 +32,13 @@ type fakePrinter struct {
|
||||
|
||||
func startFakePrinter(t *testing.T) *fakePrinter {
|
||||
t.Helper()
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
return startFakePrinterOn(t, "127.0.0.1:0")
|
||||
}
|
||||
|
||||
// startFakePrinterOn starts a fake printer listening on addr.
|
||||
func startFakePrinterOn(t *testing.T, addr string) *fakePrinter {
|
||||
t.Helper()
|
||||
ln, err := net.Listen("tcp", addr)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -327,9 +327,10 @@ type QueueConfig struct {
|
||||
// StateConfig configures where the daemon keeps what must survive a
|
||||
// restart.
|
||||
type StateConfig struct {
|
||||
// Dir is the directory each ntfy subscription keeps its state in: its
|
||||
// cursor, the IDs it has seen and the messages it holds. It has no
|
||||
// default, and is required when a subscription is configured.
|
||||
// Dir is the directory of the job store, jobs.db, and of each ntfy
|
||||
// subscription's state: its cursor, the IDs it has seen and the
|
||||
// messages it holds. It has no default; empty keeps jobs in memory, and
|
||||
// it is required when a subscription is configured.
|
||||
Dir string `mapstructure:"dir"`
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user