Leave unsent jobs queued when a durable store stops

A stop and a start are a restart too, so with a store that outlives the
process a stop now treats waiting jobs as a crash would: they stay
queued and print at the next start. The job in hand stays queued as
well while nothing of it has been sent: rendering and connecting end
with the daemon, and an attempt whose connection opens once the stop
has begun writes nothing. Only a write that has begun runs on, so the
stop takes at most printer.write_timeout and two commits. A job waiting
to retry after an attempt reached the printer fails, as before, and its
sent_at shows that bytes went out.

A store error that stops the queue now ends the job's context the same
way, so a rendering, a dial or a wait between retries stops at once
rather than running on to a job that can write nothing.

With the memory store, which the process forgets, a stop is unchanged:
the job in hand finishes, rendering included, and waiting jobs fail.

Part of stage 1c of docs/plans/job-store.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
57_WolveandClaude Opus 5.5 committed 2026-12-01 13:46:13 -06:00
1 parent 45b57ab196
commit 4ef6d21258
3 files changed
+480 -17

No files matched your search

+81 -17
View File
@@ -110,7 +110,9 @@ type Renderer interface {
// Sender delivers bytes to the printer. It calls beforeWrite, if not nil,
// once it can write and before the first byte, and writes nothing when
// beforeWrite fails.
// beforeWrite fails. Cancelling ctx stops the wait for the printer and
// the dial, but not a write that has begun; ctx's deadline still bounds
// it.
type Sender interface {
Send(ctx context.Context, data []byte, beforeWrite func() error) error
}
@@ -197,6 +199,11 @@ type Queue struct {
// wake tells the worker that a delivery is waiting or the queue
// stopped.
wake chan struct{}
// halted ends once a store error has stopped the queue, and with it
// the context of the job in hand.
halted context.Context
halt context.CancelFunc
}
// New returns a Queue that keeps its jobs in store. Call Run to start
@@ -212,6 +219,7 @@ func New(renderer Renderer, sender Sender, store Store, logger *slog.Logger, opt
options.RetryDelay = time.Second
}
options.History = max(options.History, 0)
halted, halt := context.WithCancel(context.Background())
return &Queue{
renderer: renderer,
sender: sender,
@@ -220,6 +228,8 @@ func New(renderer Renderer, sender Sender, store Store, logger *slog.Logger, opt
options: options,
jobs: make(map[JobID]*entry),
wake: make(chan struct{}, 1),
halted: halted,
halt: halt,
}
}
@@ -373,9 +383,13 @@ func (q *Queue) Restore(ctx context.Context) error {
return nil
}
// Run prints jobs until ctx is cancelled. A job that is printing when ctx is
// cancelled is finished; jobs still waiting are marked failed. Run returns
// nil then, or the store error that stopped the queue.
// Run prints jobs until ctx is cancelled, then returns nil, or the store
// error that stopped the queue. With the memory store, a job that is
// printing when ctx is cancelled is finished, and jobs still waiting are
// marked failed. With a durable store, a job finishes only if its write
// has begun, and every job that sent nothing stays queued for the next
// start; a job waiting to retry after an attempt reached the printer
// fails.
func (q *Queue) Run(ctx context.Context) error {
for {
d, err := q.next(ctx)
@@ -435,11 +449,22 @@ func (q *Queue) next(ctx context.Context) (*delivery, error) {
// process prints delivery d and records how that ended. It returns only a
// store error.
func (q *Queue) process(ctx context.Context, d *delivery) error {
// Detach from shutdown so a receipt that has started is not cut short,
// but keep a bound so a stuck printer cannot hold the worker forever.
// Store calls are detached too: a commit that has begun finishes.
jobCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), jobTimeout)
// With the memory store, the job is detached from shutdown so a
// receipt that has started is not cut short, rendering included, since
// the process forgets it anyway. With a durable store, rendering and
// connecting end with the daemon and the job stays queued for the
// next start; only a write that has begun runs on, since the sender
// ignores the context's cancellation once it writes. Either way a
// bound keeps a stuck printer from holding the worker forever, and a
// store error that stops the queue ends the job's context too. Store
// calls are detached: a commit that has begun finishes.
parent := context.WithoutCancel(ctx)
if q.store.Durable() {
parent = ctx
}
jobCtx, cancel := context.WithTimeout(parent, jobTimeout)
defer cancel()
defer context.AfterFunc(q.halted, cancel)()
storeCtx := context.WithoutCancel(ctx)
rec := d.job.rec
@@ -466,6 +491,10 @@ func (q *Queue) process(ctx context.Context, d *delivery) error {
q.release(d)
return storeErr
}
if err != nil && q.abandoned(ctx, d) {
logger.Info("job left queued: the daemon is stopping and nothing was sent")
return nil
}
if err != nil {
return q.fail(storeCtx, d, attempts, err, logger)
}
@@ -499,6 +528,20 @@ func (q *Queue) releaseLocked(d *delivery) {
}
}
// abandoned reports whether d, which did not print, stays queued: with a
// durable store, once ctx is done, if no attempt reached the printer.
// Nothing is written then, and d reads as queued again, as the store has
// it.
func (q *Queue) abandoned(ctx context.Context, d *delivery) bool {
q.mu.Lock()
defer q.mu.Unlock()
if !q.store.Durable() || ctx.Err() == nil || !d.SentAt.IsZero() {
return false
}
q.releaseLocked(d)
return true
}
// fail records d as failed after attempts, logs it and reports it.
func (q *Queue) fail(ctx context.Context, d *delivery, attempts int, cause error, logger *slog.Logger) error {
if err := q.finish(ctx, d, attempts, cause); err != nil {
@@ -513,39 +556,55 @@ func (q *Queue) fail(ctx context.Context, d *delivery, attempts int, cause error
// print renders job once and sends it, retrying failed sends with backoff.
// Each attempt records d as sending once the printer's connection is open
// and before the first byte. Retries stop early when runCtx is cancelled.
// It returns the attempts made and why the job failed, or the store error
// that stopped it, in which case nothing was written. logger carries the
// job's fields.
// and before the first byte; with a durable store, an attempt whose
// connection opens once runCtx is done writes nothing. Retries stop early
// when runCtx is cancelled. It returns the attempts made and why the job
// failed, or the store error that stopped it, in which case nothing was
// written. logger carries the job's fields.
func (q *Queue) print(runCtx, jobCtx context.Context, d *delivery, job receipt.Job, logger *slog.Logger) (attempts int, err, storeErr error) {
data, err := q.renderer.Render(jobCtx, job)
if err != nil {
return 0, fmt.Errorf("rendering: %w", err), nil
}
storeCtx := context.WithoutCancel(runCtx)
durable := q.store.Durable()
delay := q.options.RetryDelay
var last error
for attempt := 1; ; attempt++ {
stopping := false
err := q.sender.Send(jobCtx, data, func() error {
if storeErr = q.stopped(); storeErr != nil {
return storeErr
}
if durable && runCtx.Err() != nil {
stopping = true
return errShuttingDown
}
storeErr = q.sending(storeCtx, d, attempt)
return storeErr
})
switch {
case storeErr != nil:
return attempt, nil, storeErr
case stopping && last == nil:
return attempt - 1, errShuttingDown, nil
case stopping:
return attempt - 1, fmt.Errorf("server shutting down after %d attempts: %w", attempt-1, last), nil
case err == nil:
return attempt, nil, nil
case attempt > q.options.Retries:
return attempt, err, nil
}
last = err
logger.Warn("send failed, retrying", "attempt", attempt, "retry_in", delay, "err", err)
select {
case <-time.After(delay):
case <-runCtx.Done():
return attempt, fmt.Errorf("server shutting down after %d attempts: %w", attempt, err), nil
case <-jobCtx.Done():
if runCtx.Err() != nil {
return attempt, fmt.Errorf("server shutting down after %d attempts: %w", attempt, err), nil
}
return attempt, fmt.Errorf("giving up after %d attempts: %w", attempt, err), nil
}
delay *= 2
@@ -668,6 +727,7 @@ func (q *Queue) stop(err error) error {
}
q.closed = true
q.mu.Unlock()
q.halt()
q.signal()
return err
}
@@ -680,15 +740,19 @@ func (q *Queue) signal() {
}
}
// shutdown stops accepting jobs and fails those still waiting. It returns
// the store error that stopped the queue, if one did: recording a failure
// can meet one, and so can a Submit whose insert shutdown waited for.
// shutdown stops accepting jobs. With a durable store, the jobs still
// waiting stay queued for the next start, as after a crash. With the
// memory store, which the process forgets, they fail. It returns the
// store error that stopped the queue, if one did: recording a failure can
// meet one, and so can a Submit whose insert shutdown waited for.
func (q *Queue) shutdown(ctx context.Context) error {
q.submitMu.Lock()
q.mu.Lock()
q.closed = true
waiting := q.waiting
q.waiting = nil
var waiting []*delivery
if !q.store.Durable() {
waiting, q.waiting = q.waiting, nil
}
q.mu.Unlock()
q.submitMu.Unlock()