diff --git a/internal/pkg/jobstore/store.go b/internal/pkg/jobstore/store.go index 142901d..b8af2ba 100644 --- a/internal/pkg/jobstore/store.go +++ b/internal/pkg/jobstore/store.go @@ -18,7 +18,8 @@ var errNotOpen = errors.New("not stored, or already finished") // Load implements printqueue.Store. It turns every delivery in sending into // uncertain, and reads the jobs, in one commit. A record's Size is its -// content's length, read without the content. +// content's length, read without the content. A record reads as Unique +// while its source and reference are among those kept. func (s *Store) Load(ctx context.Context) (printqueue.Loaded, error) { s.mu.Lock() defer s.mu.Unlock() @@ -28,7 +29,10 @@ func (s *Store) Load(ctx context.Context) (printqueue.Loaded, error) { if loaded.Uncertain, err = endSends(ctx, tx, time.Now().UTC()); err != nil { return fmt.Errorf("ending interrupted sends: %w", err) } - loaded.Records, err = readRecords(ctx, tx) + if loaded.Records, err = readRecords(ctx, tx); err != nil { + return err + } + loaded.Refs, err = readRefs(ctx, tx) return err }) if err != nil { @@ -65,7 +69,9 @@ func endSends(ctx context.Context, tx *sql.Tx, now time.Time) ([]uint64, error) // deliveries in sequence order. func readRecords(ctx context.Context, tx *sql.Tx) ([]printqueue.Record, error) { rows, err := tx.QueryContext(ctx, ` - SELECT j.seq, j.id, j.source, j.ref, j.sequence, j.created_at, COALESCE(length(c.job), 0) + SELECT j.seq, j.id, j.source, j.ref, j.sequence, j.created_at, + EXISTS (SELECT 1 FROM refs r WHERE r.source = j.source AND r.ref = j.ref AND r.id = j.id), + COALESCE(length(c.job), 0) FROM jobs j LEFT JOIN content c ON c.seq = j.seq ORDER BY j.seq`) if err != nil { @@ -77,7 +83,7 @@ func readRecords(ctx context.Context, tx *sql.Tx) ([]printqueue.Record, error) { var r printqueue.Record var id string var created int64 - if err := rows.Scan(&r.Seq, &id, &r.Source, &r.Ref, &r.Sequence, &created, &r.Size); err != nil { + if err := rows.Scan(&r.Seq, &id, &r.Source, &r.Ref, &r.Sequence, &created, &r.Unique, &r.Size); err != nil { return nil, errors.Join(fmt.Errorf("reading jobs: %w", err), rows.Close()) } if r.ID, err = printqueue.ParseJobID(id); err != nil { @@ -127,8 +133,35 @@ func known(state printqueue.StoredState) bool { return state == printqueue.StoredQueued || state == printqueue.StoredSending || state.Finished() } -// Add implements printqueue.Store: the job, its deliveries and its content, -// in one commit. +// readRefs returns the kept references of unique jobs, by source, the first +// kept first within each. +func readRefs(ctx context.Context, tx *sql.Tx) ([]printqueue.UniqueRef, error) { + rows, err := tx.QueryContext(ctx, `SELECT source, ref, id FROM refs ORDER BY source, kept`) + if err != nil { + return nil, fmt.Errorf("reading references: %w", err) + } + var refs []printqueue.UniqueRef + for rows.Next() { + var r printqueue.UniqueRef + var id string + if err := rows.Scan(&r.Source, &r.Ref, &id); err != nil { + return nil, errors.Join(fmt.Errorf("reading references: %w", err), rows.Close()) + } + if r.ID, err = printqueue.ParseJobID(id); err != nil { + return nil, errors.Join(fmt.Errorf("reading references: a job ID: %w", err), rows.Close()) + } + refs = append(refs, r) + } + if err := errors.Join(rows.Err(), rows.Close()); err != nil { + return nil, fmt.Errorf("reading references: %w", err) + } + return refs, nil +} + +// Add implements printqueue.Store: the job, its deliveries, its content +// and, for a unique job, its reference, in one commit. The references of a +// source beyond printqueue.KeptRefs go in the same commit, the first kept +// first. func (s *Store) Add(ctx context.Context, r printqueue.Record, job []byte, sync bool) error { s.mu.Lock() defer s.mu.Unlock() @@ -154,6 +187,9 @@ func (s *Store) Add(ctx context.Context, r printqueue.Record, job []byte, sync b if _, err := tx.ExecContext(ctx, `INSERT INTO content (seq, job) VALUES (?, ?)`, r.Seq, job); err != nil { return fmt.Errorf("its content: %w", err) } + if r.Unique { + return keepRef(ctx, tx, r) + } return nil }) if err != nil { @@ -162,6 +198,29 @@ func (s *Store) Add(ctx context.Context, r printqueue.Record, job []byte, sync b return nil } +// keepRef keeps the source and reference of unique job r as the newest of +// its source, and drops the oldest beyond printqueue.KeptRefs, in the order +// they were kept, as the queue forgets them. A reference kept for an +// earlier job is dropped first, so that r's is the newest. Job IDs do not +// give that order: one minted after the clock was set back, as on a host +// whose clock does not run while it is off, sorts before those kept. +func keepRef(ctx context.Context, tx *sql.Tx, r printqueue.Record) error { + if _, err := tx.ExecContext(ctx, `DELETE FROM refs WHERE source = ? AND ref = ?`, r.Source, r.Ref); err != nil { + return fmt.Errorf("its earlier reference: %w", err) + } + if _, err := tx.ExecContext(ctx, + `INSERT INTO refs (source, ref, id) VALUES (?, ?, ?)`, r.Source, r.Ref, r.ID.String()); err != nil { + return fmt.Errorf("its reference: %w", err) + } + if _, err := tx.ExecContext(ctx, + `DELETE FROM refs WHERE source = ?1 AND kept < + (SELECT kept FROM refs WHERE source = ?1 ORDER BY kept DESC LIMIT 1 OFFSET ?2)`, + r.Source, printqueue.KeptRefs-1); err != nil { + return fmt.Errorf("pruning references: %w", err) + } + return nil +} + // Sending implements printqueue.Store, with a synced commit that changes // only d's row. func (s *Store) Sending(ctx context.Context, d printqueue.Delivery) error { diff --git a/internal/pkg/jobstore/store_test.go b/internal/pkg/jobstore/store_test.go index ba73e13..10dacb2 100644 --- a/internal/pkg/jobstore/store_test.go +++ b/internal/pkg/jobstore/store_test.go @@ -1,12 +1,14 @@ package jobstore import ( + "bytes" "context" "database/sql" "errors" "fmt" "os" "path/filepath" + "reflect" "slices" "strings" "testing" @@ -70,7 +72,7 @@ func TestRecordsSurviveAReopen(t *testing.T) { ctx := context.Background() s := openStore(t, t.TempDir()) one := record(t, 1, "default") - one.Source, one.Ref, one.Sequence = "ntfy:home", "msg1", "alerts/seq1" + one.Source, one.Ref, one.Sequence, one.Unique = "ntfy:home", "msg1", "alerts/seq1", true three := record(t, 2, "default", "kitchen", "bar") add(t, s, one, `{"elements":[{"type":"text","text":"one"}]}`) add(t, s, three, `{"elements":[]}`) @@ -105,6 +107,10 @@ func TestRecordsSurviveAReopen(t *testing.T) { sending.State, sending.Error = printqueue.StoredUncertain, printqueue.InterruptedSend wantThree.Deliveries = []printqueue.Delivery{failed, three.Deliveries[1], sending} checkRecord(t, got, wantThree) + + if len(loaded.Refs) != 1 || loaded.Refs[0] != (printqueue.UniqueRef{Source: "ntfy:home", Ref: "msg1", ID: one.ID}) { + t.Errorf("refs %+v, want job 1's", loaded.Refs) + } } // checkRecord compares every field, times by ==, so a lost nanosecond or @@ -261,7 +267,7 @@ func TestSyncedCommits(t *testing.T) { if err := s.Add(ctx, u, []byte(`{}`), true); err != nil { t.Fatal(err) } - check("a unique insert", commit{full, 3}) + check("a unique insert", commit{full, 4}) d := r.Deliveries[0] d.Attempts, d.StartedAt, d.SentAt = 1, at(1, 0), at(1, 1) @@ -400,6 +406,85 @@ func TestLoadEndsSendsUncertainOnce(t *testing.T) { } } +// The references of unique jobs are kept, the newest KeptRefs of each +// source, apart from the jobs, whose pruning leaves them. +func TestRefsKeepTheNewestPerSource(t *testing.T) { + ctx := context.Background() + s := openStore(t, t.TempDir()) + var third printqueue.UniqueRef + for seq := uint64(1); seq <= printqueue.KeptRefs+2; seq++ { + r := record(t, seq, "default") + r.Source, r.Ref, r.Unique = "ntfy:home", fmt.Sprintf("msg%d", seq), true + if seq == 3 { + third = printqueue.UniqueRef{Source: r.Source, Ref: r.Ref, ID: r.ID} + } + add(t, s, r, `{}`) + done := r.Deliveries[0] + done.State = printqueue.StoredDone + p := printqueue.Prune{Jobs: []uint64{seq}, Deliveries: []uint64{done.Seq}, Content: []uint64{seq}} + if err := s.Finish(ctx, done, p, false); err != nil { + t.Fatal(err) + } + } + other := record(t, 1000, "default") + other.Source, other.Ref, other.Unique = "ntfy:work", "msg1", true + add(t, s, other, `{}`) + add(t, s, record(t, 1001, "default"), `{}`) + + loaded := load(t, s) + if len(loaded.Records) != 2 { + t.Errorf("%d records, want only the last two jobs", len(loaded.Records)) + } + if len(loaded.Refs) != printqueue.KeptRefs+1 { + t.Fatalf("%d refs, want %d for ntfy:home and 1 for ntfy:work", len(loaded.Refs), printqueue.KeptRefs+1) + } + if loaded.Refs[0] != third || loaded.Refs[printqueue.KeptRefs] != (printqueue.UniqueRef{Source: "ntfy:work", Ref: "msg1", ID: other.ID}) { + t.Errorf("refs start with %+v and end with %+v", loaded.Refs[0], loaded.Refs[printqueue.KeptRefs]) + } + + // A reference kept for an earlier job is taken over by a new one. + again := record(t, 1002, "default") + again.Source, again.Ref, again.Unique = "ntfy:home", "msg5", true + add(t, s, again, `{}`) + refs := load(t, s).Refs + if i := slices.IndexFunc(refs, func(r printqueue.UniqueRef) bool { return r.Ref == "msg5" }); i < 0 || refs[i].ID != again.ID { + t.Errorf("msg5 is not kept for the new job: %+v", refs) + } + if len(refs) != printqueue.KeptRefs+1 { + t.Errorf("%d refs, want %d", len(refs), printqueue.KeptRefs+1) + } +} + +// References are kept in the order they were kept, not by job ID: one +// whose job was minted after the clock went back, so that its ID sorts +// before every kept one, is kept, and the first kept goes. +func TestRefsKeepTheNewestWhateverTheJobID(t *testing.T) { + s := openStore(t, t.TempDir()) + for seq := uint64(1); seq <= printqueue.KeptRefs; seq++ { + r := record(t, seq, "default") + r.Source, r.Ref, r.Unique = "ntfy:home", fmt.Sprintf("msg%d", seq), true + add(t, s, r, `{}`) + } + early, err := printqueue.ParseJobID("job_00000000000000000000000000") + if err != nil { + t.Fatal(err) + } + late := record(t, 1000, "default") + late.ID, late.Source, late.Ref, late.Unique = early, "ntfy:home", "after the clock went back", true + add(t, s, late, `{}`) + + refs := load(t, s).Refs + if len(refs) != printqueue.KeptRefs { + t.Fatalf("%d refs, want %d", len(refs), printqueue.KeptRefs) + } + if newest := refs[len(refs)-1]; newest.Ref != late.Ref || newest.ID != early { + t.Errorf("newest ref %+v, want the one kept last", newest) + } + if refs[0].Ref != "msg2" { + t.Errorf("oldest ref %+v, want msg2, msg1 having gone", refs[0]) + } +} + // The log grows by a bounded number of pages per job: an insert, a synced // sending mark, and done with the pruning of the job ten before it. The // bound has headroom; the number is logged. @@ -450,6 +535,81 @@ func TestWALFramesPerJob(t *testing.T) { } } +// The store answers as the memory store does: the same records, references +// and content after the same calls, and an error for the same calls. +func TestBehavesAsTheMemoryStore(t *testing.T) { + ctx := context.Background() + disk := openStore(t, t.TempDir()) + memory := printqueue.NewMemoryStore() + + one := record(t, 1, "default", "kitchen") + two := record(t, 2, "default") + two.Source, two.Ref, two.Sequence, two.Unique = "ntfy:home", "m1", "alerts/s1", true + clash := record(t, 3, "default") + clash.Deliveries[0].Seq = 10 + four := record(t, 4, "default") + four.Source, four.Ref, four.Unique = "ntfy:home", "m2", true + + sending := one.Deliveries[1] + sending.Attempts, sending.StartedAt, sending.SentAt = 1, at(1, 1), at(1, 2) + failed := two.Deliveries[0] + failed.State, failed.Error, failed.Attempts, failed.FinishedAt = printqueue.StoredFailed, "giving up", 4, at(2, 3) + done := one.Deliveries[0] + done.State, done.Attempts, done.FinishedAt = printqueue.StoredDone, 1, at(3, 4) + + steps := []struct { + name string + call func(printqueue.Store) error + }{ + {"add one", func(s printqueue.Store) error { return s.Add(ctx, one, []byte(`{"a":1}`), false) }}, + {"add two without content", func(s printqueue.Store) error { return s.Add(ctx, two, nil, true) }}, + {"add one again", func(s printqueue.Store) error { return s.Add(ctx, one, []byte(`{}`), false) }}, + {"add a job whose delivery is stored", func(s printqueue.Store) error { return s.Add(ctx, clash, []byte(`{}`), false) }}, + {"sending", func(s printqueue.Store) error { return s.Sending(ctx, sending) }}, + {"sending an unknown delivery", func(s printqueue.Store) error { return s.Sending(ctx, printqueue.Delivery{Seq: 99}) }}, + {"failed", func(s printqueue.Store) error { return s.Finish(ctx, failed, printqueue.Prune{}, true) }}, + {"failed again", func(s printqueue.Store) error { return s.Finish(ctx, failed, printqueue.Prune{}, true) }}, + {"finish in a state that is not final", func(s printqueue.Store) error { return s.Finish(ctx, sending, printqueue.Prune{}, false) }}, + {"done, dropping two's content", func(s printqueue.Store) error { + return s.Finish(ctx, done, printqueue.Prune{Content: []uint64{2}}, false) + }}, + {"add four", func(s printqueue.Store) error { return s.Add(ctx, four, []byte(`{"b":2}`), true) }}, + {"load", func(s printqueue.Store) error { _, err := s.Load(ctx); return err }}, + {"sending an uncertain delivery", func(s printqueue.Store) error { return s.Sending(ctx, sending) }}, + } + for _, step := range steps { + diskErr, memoryErr := step.call(disk), step.call(memory) + if (diskErr == nil) != (memoryErr == nil) { + t.Errorf("%s: the store returned %v, the memory store %v", step.name, diskErr, memoryErr) + } + } + + got, want := withoutLoadTimes(load(t, disk)), withoutLoadTimes(load(t, memory)) + if !reflect.DeepEqual(got, want) { + t.Errorf("loaded\n%+v\nwant, as the memory store,\n%+v", got, want) + } + for seq := uint64(1); seq <= 4; seq++ { + diskJob, diskErr := disk.Job(ctx, seq) + memoryJob, memoryErr := memory.Job(ctx, seq) + if !bytes.Equal(diskJob, memoryJob) || !errors.Is(diskErr, memoryErr) { + t.Errorf("Job(%d) = %q, %v; the memory store's %q, %v", seq, diskJob, diskErr, memoryJob, memoryErr) + } + } +} + +// withoutLoadTimes clears the finish time that Load gives the deliveries it +// finds sending, which is the time of that Load. +func withoutLoadTimes(loaded printqueue.Loaded) printqueue.Loaded { + for i := range loaded.Records { + for j := range loaded.Records[i].Deliveries { + if d := &loaded.Records[i].Deliveries[j]; d.Error == printqueue.InterruptedSend { + d.FinishedAt = time.Time{} + } + } + } + return loaded +} + // Errors name the operation and sequence numbers, never what a job prints // or where it came from. func TestErrorsNeverQuoteTheJob(t *testing.T) {