From 803113550887191e57c006957de864e3f09c23cf Mon Sep 17 00:00:00 2001 From: William Gill Date: Tue, 1 Dec 2026 12:46:57 -0600 Subject: [PATCH] Keep finished jobs' content within queue.content_bytes A job's content, its JSON, went from the store in the commit that finished it. The store is to keep it for longer, so that a finished job can be previewed or sent again by ID, but a count of jobs cannot bound that: at webserver.body_limit, 1000 finished jobs come to about 4 GB. The new key queue.content_bytes (default 64 MiB, 0 to 1 GiB) bounds the content of finished jobs instead, newest first. Statuses stay as queue.history says; a job past the budget keeps its status without its content. Unfinished jobs always keep their content, and so do uncertain ones while their status is kept, since a reprint needs it. What goes is dropped in the commit that finishes the job pushing it out. With the memory store the content is kept in memory, so the daemon may hold up to the budget more than before; at 1.5 KB per text job, the 1000 jobs of history take about 1.5 MB. Part of stage 1c of docs/plans/job-store.md. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 + configs/config.example.toml | 3 + docs/configuration.md | 1 + internal/app/uberbringer/serve.go | 11 +-- internal/pkg/config/config.go | 16 +++- internal/pkg/config/config_test.go | 31 ++++++- internal/pkg/printqueue/queue.go | 84 +++++++++++++----- internal/pkg/printqueue/queue_store_test.go | 4 +- internal/pkg/printqueue/retention_test.go | 98 +++++++++++++++++++++ 9 files changed, 220 insertions(+), 32 deletions(-) create mode 100644 internal/pkg/printqueue/retention_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 10949c8..dec458a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -87,6 +87,10 @@ version may break callers; such changes are listed under **Breaking**. - `GET /api/v1/jobs/:id` reports `sent_at`, when the first attempt was about to write to the printer. A failed job with `sent_at` reached the printer and may have printed in part; one without it never did. +- `queue.content_bytes` (default 64 MiB, at most 1 GiB) bounds the content + of finished jobs kept, newest first, each job as its JSON. Jobs not yet + finished keep theirs whatever the total, and so do `uncertain` jobs while + their status is kept. - `image` elements take `"optional": true`: an image that cannot be fetched or decoded prints as `[image unavailable]` instead of failing the job, and one whose `width` is wider than the paper shrinks to it. diff --git a/configs/config.example.toml b/configs/config.example.toml index 6c96754..4ab1829 100644 --- a/configs/config.example.toml +++ b/configs/config.example.toml @@ -136,6 +136,9 @@ [queue] size = 100 # jobs that may wait; more get 503 history = 1000 # finished jobs whose status is kept + # Bytes of finished jobs' content kept, newest first, 64 MiB; at most + # 1 GiB. Waiting jobs always keep theirs. + content_bytes = 67108864 [state] # The directory the ntfy subscriptions keep their state in, so that a diff --git a/docs/configuration.md b/docs/configuration.md index 83d5644..4890140 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -174,6 +174,7 @@ Quiet hours are off unless the subscription has a |-----|---------|---------| | `size` | `100` | Jobs that may wait to print; more get `503` `queue_full` | | `history` | `1000` | Finished jobs whose status is kept; an older job's ID answers `404` `job_not_found` | +| `content_bytes` | `67108864` | The bytes of finished jobs' content kept, newest first, each job as its JSON: 64 MiB, at most 1 GiB (`1073741824`). Jobs not yet finished keep theirs whatever the total, and so do `uncertain` jobs while their status is kept. The content is kept in memory | ### state diff --git a/internal/app/uberbringer/serve.go b/internal/app/uberbringer/serve.go index 4a9fa2f..6c4859d 100644 --- a/internal/app/uberbringer/serve.go +++ b/internal/app/uberbringer/serve.go @@ -90,11 +90,12 @@ func run(ctx context.Context, cfg *config.Config, build BuildInfo, out io.Writer store := printqueue.NewMemoryStore() defer closeStore(store, logger) queue := printqueue.New(renderer, printerClient, store, logger, printqueue.Options{ - Size: cfg.Queue.Size, - History: cfg.Queue.History, - Retries: cfg.Printer.Retries, - RetryDelay: cfg.Printer.RetryDelay, - OnFailure: reportJobFailure, + Size: cfg.Queue.Size, + History: cfg.Queue.History, + ContentBytes: cfg.Queue.ContentBytes, + Retries: cfg.Printer.Retries, + RetryDelay: cfg.Printer.RetryDelay, + OnFailure: reportJobFailure, }) // Restored jobs go ahead of new ones, so nothing may submit before. if err := queue.Restore(ctx); err != nil { diff --git a/internal/pkg/config/config.go b/internal/pkg/config/config.go index e52e513..8d9ad11 100644 --- a/internal/pkg/config/config.go +++ b/internal/pkg/config/config.go @@ -39,6 +39,9 @@ const MaxLineSpacing = 255 // MaxCutFeed is the largest printer.cut_feed, the most ESC d feeds at once. const MaxCutFeed = 255 +// MaxContentBytes is the largest queue.content_bytes, 1 GiB. +const MaxContentBytes = 1 << 30 + // Log formats accepted by [LogConfig.Format]. const ( LogFormatText = "text" @@ -313,6 +316,12 @@ type QueueConfig struct { // History is the number of finished jobs whose status is kept. History int `mapstructure:"history"` + + // ContentBytes is how many bytes of finished jobs' content are kept, + // newest first. Unfinished jobs, and uncertain ones while their status + // is kept, keep theirs whatever the total. It is an int64, as are the + // sizes it bounds. + ContentBytes int64 `mapstructure:"content_bytes"` } // StateConfig configures where the daemon keeps what must survive a @@ -403,8 +412,9 @@ func Default() Config { }, }, Queue: QueueConfig{ - Size: 100, - History: 1000, + Size: 100, + History: 1000, + ContentBytes: 64 << 20, }, Images: ImagesConfig{ Timeout: 10 * time.Second, @@ -978,6 +988,8 @@ func (c *Config) Validate() error { check(c.Queue.Size > 0, "queue.size must be positive") check(c.Queue.History >= 0, "queue.history must not be negative") + check(c.Queue.ContentBytes >= 0 && c.Queue.ContentBytes <= MaxContentBytes, + "queue.content_bytes must be 0-%d (1 GiB)", MaxContentBytes) check(len(c.Ntfy.Subscriptions) == 0 || strings.TrimSpace(c.State.Dir) != "", `state.dir is required when an ntfy subscription is configured, e.g. "/var/lib/uberbringer"`) diff --git a/internal/pkg/config/config_test.go b/internal/pkg/config/config_test.go index 2e196a9..ca774f4 100644 --- a/internal/pkg/config/config_test.go +++ b/internal/pkg/config/config_test.go @@ -406,7 +406,7 @@ func TestExampleConfigLoads(t *testing.T) { cfg.Printer.CutFeed != def.Printer.CutFeed || cfg.Format.Timezone != def.Format.Timezone || cfg.Format.TimeLayout != def.Format.TimeLayout || cfg.Ntfy.Format != def.Ntfy.Format || len(cfg.Ntfy.Markers) != 0 || - cfg.State != def.State || len(cfg.Ntfy.Subscriptions) != 0 { + cfg.State != def.State || cfg.Queue != def.Queue || len(cfg.Ntfy.Subscriptions) != 0 { t.Error("example config values drifted from the defaults it documents") } } @@ -691,3 +691,32 @@ func TestValue(t *testing.T) { }) } } + +// queue.content_bytes defaults to 64 MiB and takes 0 to 1 GiB. +func TestLoadContentBytes(t *testing.T) { + base := "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n" + cfg, err := config.Load(writeConfig(t, base)) + if err != nil || cfg.Queue.ContentBytes != 64<<20 { + t.Fatalf("default content_bytes %d, %v; want 67108864", cfg.Queue.ContentBytes, err) + } + for _, tt := range []struct { + value string + want int64 + ok bool + }{ + {"0", 0, true}, + {"1073741824", 1 << 30, true}, + {"-1", 0, false}, + {"1073741825", 0, false}, + } { + cfg, err := config.Load(writeConfig(t, base+"[queue]\ncontent_bytes = "+tt.value+"\n")) + switch { + case tt.ok && err != nil: + t.Errorf("content_bytes = %s: %v", tt.value, err) + case tt.ok && cfg.Queue.ContentBytes != tt.want: + t.Errorf("content_bytes = %s gave %d", tt.value, cfg.Queue.ContentBytes) + case !tt.ok && (err == nil || !strings.Contains(err.Error(), "queue.content_bytes must be 0-1073741824")): + t.Errorf("content_bytes = %s: err %v, want it refused", tt.value, err) + } + } +} diff --git a/internal/pkg/printqueue/queue.go b/internal/pkg/printqueue/queue.go index c314f73..e43a824 100644 --- a/internal/pkg/printqueue/queue.go +++ b/internal/pkg/printqueue/queue.go @@ -125,6 +125,11 @@ type Options struct { // History is how many finished jobs keep their status. History int + // ContentBytes bounds the stored content of finished jobs: the newest + // keep theirs up to this many bytes in all. Unfinished jobs, and + // uncertain ones while their status is kept, always keep theirs. + ContentBytes int64 + // Retries is how many times a failed send is retried; RetryDelay is the // first wait, doubling after each attempt. Retries int @@ -650,10 +655,10 @@ func (q *Queue) finish(ctx context.Context, d *delivery, attempts int, cause err q.mu.Lock() finishing := d.job.finishedWith(d, next) - prune, drop := q.retention(d.job, finishing) + r := q.retention(d, next, finishing) q.mu.Unlock() - if err := q.store.Finish(ctx, next, prune, next.State == StoredFailed); err != nil { + if err := q.store.Finish(ctx, next, r.rows, next.State == StoredFailed); err != nil { q.release(d) return fmt.Errorf("recording job %s as %s: %w", d.job.rec.ID, next.State, err) } @@ -663,13 +668,15 @@ func (q *Queue) finish(ctx context.Context, d *delivery, attempts int, cause err d.Delivery, d.taken = next, false if finishing { d.job.finished = true - d.job.rec.Size = 0 q.finished = append(q.finished, d.job) } - for _, e := range drop { + for _, e := range r.statuses { delete(q.jobs, e.rec.ID) } - q.finished = q.finished[len(drop):] + q.finished = q.finished[len(r.statuses):] + for _, e := range r.content { + e.rec.Size = 0 + } return nil } @@ -687,30 +694,63 @@ func (e *entry) finishedWith(d *delivery, next Delivery) bool { return true } -// retention returns what goes once e, if finishing, has joined the -// finished jobs: the oldest finished jobs beyond History, as rows for the -// store and as entries, a prefix of q.finished, and the content of e, -// which a finished job no longer needs. The caller holds q.mu. -func (q *Queue) retention(e *entry, finishing bool) (Prune, []*entry) { +// pruning is what retention lets go of: the rows for the store, the jobs +// whose status goes, a prefix of the finished jobs, and those whose +// content goes while their status stays. +type pruning struct { + rows Prune + statuses []*entry + content []*entry +} + +// retention returns what goes once d is in state next and its job, if +// finishing, has joined the finished jobs. Statuses: the oldest finished +// jobs beyond History, each with its deliveries and content. Content: the +// finished jobs' newest first up to ContentBytes, apart from an uncertain +// job's, which a reprint needs and which stays while its status does. +// Unfinished jobs keep theirs. The caller holds q.mu. +func (q *Queue) retention(d *delivery, next Delivery, finishing bool) pruning { finished := q.finished if finishing { - finished = append(finished[:len(finished):len(finished)], e) + finished = append(finished[:len(finished):len(finished)], d.job) } - drop := slices.Clone(finished[:max(len(finished)-q.options.History, 0)]) - var p Prune - for _, old := range drop { - p.Jobs = append(p.Jobs, old.rec.Seq) - for _, d := range old.deliveries { - p.Deliveries = append(p.Deliveries, d.Seq) + cut := max(len(finished)-q.options.History, 0) + r := pruning{statuses: slices.Clone(finished[:cut])} + for _, e := range r.statuses { + r.rows.Jobs = append(r.rows.Jobs, e.rec.Seq) + for _, d := range e.deliveries { + r.rows.Deliveries = append(r.rows.Deliveries, d.Seq) } - if old.rec.Size > 0 { - p.Content = append(p.Content, old.rec.Seq) + if e.rec.Size > 0 { + r.rows.Content = append(r.rows.Content, e.rec.Seq) } } - if finishing && len(drop) < len(finished) && e.rec.Size > 0 { - p.Content = append(p.Content, e.rec.Seq) + var used int64 + for _, e := range slices.Backward(finished[cut:]) { + if e.rec.Size == 0 || e.uncertainWith(d, next) { + continue + } + if used += e.rec.Size; used > q.options.ContentBytes { + r.rows.Content = append(r.rows.Content, e.rec.Seq) + r.content = append(r.content, e) + } } - return p, drop + return r +} + +// uncertainWith reports whether any of e's deliveries is uncertain once d +// is in state next. +func (e *entry) uncertainWith(d *delivery, next Delivery) bool { + for _, other := range e.deliveries { + state := other.State + if other == d { + state = next.State + } + if state == StoredUncertain { + return true + } + } + return false } // stop stops the queue after a store error: Submit answers ErrClosed from diff --git a/internal/pkg/printqueue/queue_store_test.go b/internal/pkg/printqueue/queue_store_test.go index 00fa7bf..648916a 100644 --- a/internal/pkg/printqueue/queue_store_test.go +++ b/internal/pkg/printqueue/queue_store_test.go @@ -551,8 +551,8 @@ func TestUndecodableJobFails(t *testing.T) { } // Statuses beyond History go from the store with their deliveries in the -// commit that finishes the job pushing them out, and a job's content goes -// in the commit that finishes it. +// commit that finishes the job pushing them out, and with no content +// budget a job's content goes in the commit that finishes it. func TestHistoryPrunesTheStore(t *testing.T) { inner := printqueue.NewMemoryStore() q := newQueueOn(inner, fakeRenderer{}, &fakeSender{}, discardLogger(), printqueue.Options{History: 2}) diff --git a/internal/pkg/printqueue/retention_test.go b/internal/pkg/printqueue/retention_test.go new file mode 100644 index 0000000..778ca3f --- /dev/null +++ b/internal/pkg/printqueue/retention_test.go @@ -0,0 +1,98 @@ +package printqueue_test + +import ( + "context" + "encoding/json" + "errors" + "testing" + + "uberbringer/internal/pkg/printqueue" +) + +// contentKept reports whether store still has job seq's content. +func contentKept(t *testing.T, store printqueue.Store, seq uint64) bool { + t.Helper() + _, err := store.Job(context.Background(), seq) + if err != nil && !errors.Is(err, printqueue.ErrContentGone) { + t.Fatal(err) + } + return err == nil +} + +// Finished jobs keep their content newest first within ContentBytes. An +// uncertain job keeps its content, uncounted, while its status stays, and +// an unfinished job always keeps its own. +func TestRetentionByContentBytes(t *testing.T) { + ctx := context.Background() + content, _ := json.Marshal(job("aaaa")) + size := int64(len(content)) + + store := printqueue.NewDurableMemoryStore() + uncertain := storeJob(t, store, 1, newJobID(t), job("a long receipt that may have printed"), printqueue.DefaultPrinter) + sending := uncertain.Deliveries[0] + sending.Attempts = 1 + if err := store.Sending(ctx, sending); err != nil { + t.Fatal(err) + } + + sender := &fakeSender{gate: make(chan struct{})} + q := newQueueOn(store, fakeRenderer{}, sender, discardLogger(), + printqueue.Options{History: 10, ContentBytes: 2*size + size/2}) + if err := q.Restore(ctx); err != nil { + t.Fatal(err) + } + startQueue(t, q) + var ids []printqueue.JobID + for range 4 { + st, err := q.Submit(job("aaaa"), printqueue.Meta{}) + if err != nil { + t.Fatal(err) + } + ids = append(ids, st.ID) + } + for _, id := range ids { + sender.gate <- struct{}{} + waitForState(t, q, id, printqueue.StateDone) + } + waiting, _ := q.Submit(job("aaaa"), printqueue.Meta{}) + waitFor(t, func() bool { st, _ := q.Status(waiting.ID); return st.State == printqueue.StatePrinting }) + + for seq, want := range map[uint64]bool{1: true, 2: false, 3: false, 4: true, 5: true, 6: true} { + if got := contentKept(t, store, seq); got != want { + t.Errorf("job %d keeps its content: %v, want %v", seq, got, want) + } + } + for _, id := range append(ids, uncertain.ID) { + if _, err := q.Status(id); err != nil { + t.Errorf("status of %s: %v; dropping content must keep it", id, err) + } + } + close(sender.gate) + waitForState(t, q, waiting.ID, printqueue.StateDone) +} + +// An uncertain job's content goes with its status. +func TestRetentionDropsUncertainContentWithItsStatus(t *testing.T) { + ctx := context.Background() + store := printqueue.NewDurableMemoryStore() + uncertain := storeJob(t, store, 1, newJobID(t), job("x"), printqueue.DefaultPrinter) + if err := store.Sending(ctx, uncertain.Deliveries[0]); err != nil { + t.Fatal(err) + } + q := newQueueOn(store, fakeRenderer{}, &fakeSender{}, discardLogger(), printqueue.Options{History: 1, ContentBytes: 1 << 20}) + if err := q.Restore(ctx); err != nil { + t.Fatal(err) + } + if !contentKept(t, store, 1) { + t.Fatal("the uncertain job lost its content at the restart") + } + startQueue(t, q) + st, _ := q.Submit(job("y"), printqueue.Meta{}) + waitForState(t, q, st.ID, printqueue.StateDone) + if _, err := q.Status(uncertain.ID); !errors.Is(err, printqueue.ErrNotFound) { + t.Errorf("uncertain job's status: %v, want it gone past History", err) + } + if contentKept(t, store, 1) || !contentKept(t, store, 2) { + t.Error("want the uncertain job's content gone with its status, and the new job's kept") + } +}