A card from an ntfy subscription now carries its notification, "<topic>/<sequence ID>", in its Meta, and the queue stores it with the job. ntfy's sequence IDs are per topic and one subscription reads several topics, so the topic is part of the key; a message without a sequence_id is its own sequence. Digests and jobs from the routes carry none. Nothing reads it yet: it lets an ntfy message_delete find the waiting job of its notification, also after a restart, once cancelling comes. Part of stage 1c of docs/plans/job-store.md. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
893 lines
26 KiB
Go
893 lines
26 KiB
Go
// Package printqueue prints jobs one at a time, in submission order, and
|
|
// keeps track of their status. Jobs are kept in a Store.
|
|
package printqueue
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"log/slog"
|
|
"slices"
|
|
"sync"
|
|
"time"
|
|
|
|
"go.jetify.com/typeid"
|
|
|
|
"uberbringer/internal/pkg/receipt"
|
|
)
|
|
|
|
// jobTimeout bounds rendering and sending one job, including retries.
|
|
const jobTimeout = 2 * time.Minute
|
|
|
|
var (
|
|
// ErrQueueFull is returned by Submit when no more jobs can wait.
|
|
ErrQueueFull = errors.New("print queue is full")
|
|
|
|
// ErrClosed is returned by Submit once the queue has shut down.
|
|
ErrClosed = errors.New("print queue is shut down")
|
|
|
|
// ErrStoreFailed marks a store error that stopped the queue, as
|
|
// Submit and Run return it. Run's caller reports it, once.
|
|
ErrStoreFailed = errors.New("job store failed")
|
|
|
|
// ErrNotFound is returned by Status for unknown or expired job IDs.
|
|
ErrNotFound = errors.New("job not found")
|
|
|
|
errShuttingDown = errors.New("server shutting down before the job was printed")
|
|
|
|
// errUndecodable fails a stored job that no longer decodes. It never
|
|
// quotes the job.
|
|
errUndecodable = errors.New("the stored job no longer decodes")
|
|
)
|
|
|
|
// jobPrefix gives job IDs their "job_" prefix.
|
|
type jobPrefix struct{}
|
|
|
|
// Prefix implements typeid.PrefixType.
|
|
func (jobPrefix) Prefix() string { return "job" }
|
|
|
|
// JobID identifies a print job, e.g. "job_01h455vb4pex5vsknk084sn02q". It is
|
|
// a TypeID: a UUIDv7, so IDs sort by creation time.
|
|
type JobID struct {
|
|
typeid.TypeID[jobPrefix]
|
|
}
|
|
|
|
// ParseJobID parses s as a JobID.
|
|
func ParseJobID(s string) (JobID, error) {
|
|
return typeid.Parse[JobID](s)
|
|
}
|
|
|
|
// State is a job's position in its lifecycle.
|
|
type State string
|
|
|
|
// Job states.
|
|
const (
|
|
StateQueued State = "queued"
|
|
StatePrinting State = "printing"
|
|
StateDone State = "done"
|
|
StateFailed State = "failed"
|
|
|
|
// StateUncertain is a job that was being sent when the daemon stopped,
|
|
// so it may have printed. It is never sent again.
|
|
StateUncertain State = "uncertain"
|
|
)
|
|
|
|
// Status describes a job.
|
|
type Status struct {
|
|
// ID identifies the job.
|
|
ID JobID `json:"id"`
|
|
// State is where the job is in its lifecycle. uncertain is a job that
|
|
// was being sent to the printer when the daemon stopped: it may have
|
|
// printed, and it is never sent again.
|
|
State State `json:"status" jsonschema:"enum=queued,enum=printing,enum=done,enum=failed,enum=uncertain"`
|
|
// Source says where the job came from: print for POST /api/v1/print,
|
|
// module:<name> for a module route, e.g. module:ntfy, or
|
|
// ntfy:<subscription> for an ntfy subscription in the config.
|
|
Source string `json:"source,omitempty"`
|
|
// Error says why a failed job failed, or that an uncertain one may
|
|
// have printed.
|
|
Error string `json:"error,omitempty"`
|
|
// Attempts is how many times the job was sent to the printer.
|
|
Attempts int `json:"attempts,omitempty"`
|
|
// CreatedAt is when the job was queued.
|
|
CreatedAt time.Time `json:"created_at"`
|
|
// StartedAt is when the worker took the job.
|
|
StartedAt *time.Time `json:"started_at,omitempty"`
|
|
// SentAt is when the first attempt was about to write to the printer.
|
|
// A failed job with sent_at reached the printer, and part of it may have
|
|
// printed; one without it never reached the printer.
|
|
SentAt *time.Time `json:"sent_at,omitempty"`
|
|
// FinishedAt is when the job was done or failed, or when a start found
|
|
// it uncertain.
|
|
FinishedAt *time.Time `json:"finished_at,omitempty"`
|
|
}
|
|
|
|
// Renderer turns a job into printer bytes.
|
|
type Renderer interface {
|
|
Render(ctx context.Context, job receipt.Job) ([]byte, error)
|
|
}
|
|
|
|
// 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. 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
|
|
}
|
|
|
|
// Options configures a Queue.
|
|
type Options struct {
|
|
// Size is how many jobs may wait.
|
|
Size int
|
|
|
|
// 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
|
|
RetryDelay time.Duration
|
|
|
|
// OnFailure, if set, is called for every job that fails, e.g. to report
|
|
// it to an error tracker.
|
|
OnFailure func(id JobID, err error)
|
|
}
|
|
|
|
// Meta says where a job came from. It is kept with the job's status and
|
|
// logged with it; it never holds what the job prints.
|
|
type Meta struct {
|
|
// Source is the kind of client that sent the job, e.g. print,
|
|
// module:ntfy or ntfy:home.
|
|
Source string
|
|
|
|
// Ref identifies the job at its source, e.g. the ID of the request
|
|
// that sent it, or of the ntfy message.
|
|
Ref string
|
|
|
|
// Sequence is the ntfy notification a card came from,
|
|
// "<topic>/<sequence>"; empty for other jobs. It is stored with the
|
|
// job.
|
|
Sequence string
|
|
}
|
|
|
|
// entry is a job the queue keeps.
|
|
type entry struct {
|
|
// rec is the job as stored, its deliveries apart.
|
|
rec Record
|
|
deliveries []*delivery
|
|
|
|
// finished is set once every delivery has finished; the entry is then
|
|
// on Queue.finished.
|
|
finished bool
|
|
}
|
|
|
|
// delivery is a job's delivery as the queue sees it: as stored, and
|
|
// whether the worker has taken it.
|
|
type delivery struct {
|
|
Delivery
|
|
job *entry
|
|
taken bool
|
|
}
|
|
|
|
// Queue runs print jobs on a single worker. It is safe for concurrent use.
|
|
//
|
|
// Every change to a job is committed to the store first and made in
|
|
// memory after, so a status never shows what the store lacks. A store
|
|
// error stops the queue: Submit then answers ErrClosed, and Run returns
|
|
// the error.
|
|
type Queue struct {
|
|
renderer Renderer
|
|
sender Sender
|
|
store Store
|
|
logger *slog.Logger
|
|
options Options
|
|
|
|
// submitMu serialises Submit, Restore and the start of shutdown: the
|
|
// sequence numbers, the capacity check, the store's Add and the append
|
|
// to the waiting list. It is taken before mu.
|
|
submitMu sync.Mutex
|
|
nextJob uint64
|
|
nextDelivery uint64
|
|
|
|
// mu guards the fields below. It is never held across a call to the
|
|
// store, the renderer or the sender, so Status and Pending never wait
|
|
// for a commit.
|
|
mu sync.Mutex
|
|
jobs map[JobID]*entry
|
|
waiting []*delivery // in submission order
|
|
finished []*entry // oldest first, for history eviction
|
|
closed bool
|
|
failure error // the store error that stopped the queue
|
|
|
|
// 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
|
|
// printing.
|
|
func New(renderer Renderer, sender Sender, store Store, logger *slog.Logger, options Options) *Queue {
|
|
if renderer == nil || sender == nil || store == nil || logger == nil {
|
|
panic("printqueue.New: renderer, sender, store and logger must not be nil")
|
|
}
|
|
if options.Size <= 0 {
|
|
panic("printqueue.New: size must be positive")
|
|
}
|
|
if options.RetryDelay <= 0 {
|
|
options.RetryDelay = time.Second
|
|
}
|
|
options.History = max(options.History, 0)
|
|
halted, halt := context.WithCancel(context.Background())
|
|
return &Queue{
|
|
renderer: renderer,
|
|
sender: sender,
|
|
store: store,
|
|
logger: logger,
|
|
options: options,
|
|
jobs: make(map[JobID]*entry),
|
|
wake: make(chan struct{}, 1),
|
|
halted: halted,
|
|
halt: halt,
|
|
}
|
|
}
|
|
|
|
// Submit queues job, sent from where meta says. The job should already be
|
|
// validated so callers can report problems synchronously; it is validated
|
|
// again when rendered. The job is stored before Submit returns, whatever
|
|
// happens to the caller meanwhile. A store error stops the queue and is
|
|
// returned, marked as ErrStoreFailed.
|
|
func (q *Queue) Submit(job receipt.Job, meta Meta) (Status, error) {
|
|
id, err := typeid.New[JobID]()
|
|
if err != nil {
|
|
return Status{}, fmt.Errorf("generating job ID: %w", err)
|
|
}
|
|
content, err := json.Marshal(job)
|
|
if err != nil {
|
|
return Status{}, fmt.Errorf("encoding job %s: %w", id, err)
|
|
}
|
|
|
|
q.submitMu.Lock()
|
|
defer q.submitMu.Unlock()
|
|
if err := q.admit(); err != nil {
|
|
return Status{}, err
|
|
}
|
|
q.nextJob++
|
|
q.nextDelivery++
|
|
rec := Record{
|
|
Seq: q.nextJob,
|
|
ID: id,
|
|
Source: meta.Source,
|
|
Ref: meta.Ref,
|
|
Sequence: meta.Sequence,
|
|
CreatedAt: time.Now().UTC(),
|
|
Deliveries: []Delivery{
|
|
{Seq: q.nextDelivery, Printer: DefaultPrinter, State: StoredQueued},
|
|
},
|
|
}
|
|
if err := q.store.Add(context.Background(), rec, content, false); err != nil {
|
|
return Status{}, q.stop(fmt.Errorf("storing job %s: %w", id, err))
|
|
}
|
|
rec.Size = int64(len(content))
|
|
|
|
q.mu.Lock()
|
|
e := q.keep(rec)
|
|
q.waiting = append(q.waiting, e.deliveries...)
|
|
status := e.status()
|
|
q.mu.Unlock()
|
|
q.signal()
|
|
return status, nil
|
|
}
|
|
|
|
// admit refuses a new job once the queue is closed or full.
|
|
func (q *Queue) admit() error {
|
|
q.mu.Lock()
|
|
defer q.mu.Unlock()
|
|
switch {
|
|
case q.closed:
|
|
return ErrClosed
|
|
case len(q.waiting) >= q.options.Size:
|
|
return ErrQueueFull
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// keep makes r a job the queue keeps and returns it. The caller holds
|
|
// q.mu.
|
|
func (q *Queue) keep(r Record) *entry {
|
|
e := &entry{rec: r}
|
|
e.rec.Deliveries = nil
|
|
for _, d := range r.Deliveries {
|
|
e.deliveries = append(e.deliveries, &delivery{Delivery: d, job: e})
|
|
}
|
|
q.jobs[r.ID] = e
|
|
return e
|
|
}
|
|
|
|
// Status returns the status of job id.
|
|
func (q *Queue) Status(id JobID) (Status, error) {
|
|
q.mu.Lock()
|
|
defer q.mu.Unlock()
|
|
e, ok := q.jobs[id]
|
|
if !ok {
|
|
return Status{}, ErrNotFound
|
|
}
|
|
return e.status(), nil
|
|
}
|
|
|
|
// Pending returns the number of deliveries waiting to print.
|
|
func (q *Queue) Pending() int {
|
|
q.mu.Lock()
|
|
defer q.mu.Unlock()
|
|
return len(q.waiting)
|
|
}
|
|
|
|
// Restore loads the jobs the store keeps, before Run and before the first
|
|
// Submit. Their queued deliveries wait again, in submission order and
|
|
// ahead of any new job, even beyond Size, and their statuses answer at
|
|
// once. Each delivery the load turned uncertain is logged at WARN by its
|
|
// job's ID, source and reference; it is never sent again.
|
|
func (q *Queue) Restore(ctx context.Context) error {
|
|
q.submitMu.Lock()
|
|
defer q.submitMu.Unlock()
|
|
q.mu.Lock()
|
|
started := len(q.jobs) > 0 || q.nextJob > 0
|
|
q.mu.Unlock()
|
|
if started {
|
|
return errors.New("restoring the print queue: jobs were already queued")
|
|
}
|
|
loaded, err := q.store.Load(ctx)
|
|
if err != nil {
|
|
return fmt.Errorf("loading the job store: %w", err)
|
|
}
|
|
uncertain := make(map[uint64]bool, len(loaded.Uncertain))
|
|
for _, seq := range loaded.Uncertain {
|
|
uncertain[seq] = true
|
|
}
|
|
|
|
type turned struct {
|
|
rec Record
|
|
printer string
|
|
}
|
|
var warn []turned
|
|
q.mu.Lock()
|
|
for _, r := range loaded.Records {
|
|
q.nextJob = max(q.nextJob, r.Seq)
|
|
e := q.keep(r)
|
|
e.finished = true
|
|
for _, d := range e.deliveries {
|
|
q.nextDelivery = max(q.nextDelivery, d.Seq)
|
|
e.finished = e.finished && d.State.Finished()
|
|
if d.State == StoredQueued {
|
|
q.waiting = append(q.waiting, d)
|
|
}
|
|
if uncertain[d.Seq] {
|
|
warn = append(warn, turned{rec: e.rec, printer: d.Printer})
|
|
}
|
|
}
|
|
if e.finished {
|
|
q.finished = append(q.finished, e)
|
|
}
|
|
}
|
|
waiting := len(q.waiting)
|
|
q.mu.Unlock()
|
|
|
|
for _, w := range warn {
|
|
q.logger.Warn("job was being sent when the daemon stopped; it may have printed and is not sent again",
|
|
"job_id", w.rec.ID.String(), "printer", w.printer, "source", w.rec.Source, "ref", w.rec.Ref)
|
|
}
|
|
if len(loaded.Records) > 0 {
|
|
q.logger.Info("print queue restored", "jobs", len(loaded.Records), "waiting", waiting, "uncertain", len(warn))
|
|
}
|
|
q.signal()
|
|
return nil
|
|
}
|
|
|
|
// 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)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if d == nil {
|
|
return q.shutdown(ctx)
|
|
}
|
|
if err := q.process(ctx, d); err != nil {
|
|
return q.stop(err)
|
|
}
|
|
}
|
|
}
|
|
|
|
// next waits for a delivery and takes it. It returns nil once ctx is
|
|
// done, and the store error that stopped the queue, if one did. The store
|
|
// is told when there is nothing to do.
|
|
func (q *Queue) next(ctx context.Context) (*delivery, error) {
|
|
idle := false
|
|
for {
|
|
q.mu.Lock()
|
|
switch {
|
|
case q.failure != nil:
|
|
err := q.failure
|
|
q.mu.Unlock()
|
|
return nil, err
|
|
case ctx.Err() != nil:
|
|
q.mu.Unlock()
|
|
return nil, nil
|
|
case len(q.waiting) > 0:
|
|
d := q.waiting[0]
|
|
q.waiting[0] = nil
|
|
q.waiting = q.waiting[1:]
|
|
d.taken, d.StartedAt = true, time.Now().UTC()
|
|
q.mu.Unlock()
|
|
return d, nil
|
|
}
|
|
q.mu.Unlock()
|
|
if !idle {
|
|
idle = true
|
|
if err := q.stopped(); err != nil {
|
|
return nil, err
|
|
}
|
|
if err := q.store.Idle(context.WithoutCancel(ctx)); err != nil {
|
|
return nil, q.stop(fmt.Errorf("job store while idle: %w", err))
|
|
}
|
|
continue
|
|
}
|
|
select {
|
|
case <-ctx.Done():
|
|
case <-q.wake:
|
|
}
|
|
}
|
|
}
|
|
|
|
// 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 {
|
|
// 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
|
|
logger := q.logger.With("job_id", rec.ID.String(), "source", rec.Source, "ref", rec.Ref)
|
|
content, err := q.store.Job(storeCtx, rec.Seq)
|
|
switch {
|
|
case errors.Is(err, ErrContentGone):
|
|
return q.fail(storeCtx, d, 0, err, logger)
|
|
case err != nil:
|
|
q.release(d)
|
|
return fmt.Errorf("reading job %s: %w", rec.ID, err)
|
|
}
|
|
job, err := receipt.DecodeJob(content)
|
|
if err != nil {
|
|
return q.fail(storeCtx, d, 0, errUndecodable, logger)
|
|
}
|
|
|
|
logger.Info("printing job", "elements", len(job.Elements), "copies", max(job.Copies, 1))
|
|
attempts, err, storeErr := q.print(ctx, jobCtx, d, job, logger)
|
|
if storeErr == nil {
|
|
storeErr = q.stopped()
|
|
}
|
|
if storeErr != nil {
|
|
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)
|
|
}
|
|
if err := q.finish(storeCtx, d, attempts, nil); err != nil {
|
|
return err
|
|
}
|
|
logger.Info("job printed", "attempts", attempts)
|
|
return nil
|
|
}
|
|
|
|
// stopped returns the store error that stopped the queue, if one did.
|
|
func (q *Queue) stopped() error {
|
|
q.mu.Lock()
|
|
defer q.mu.Unlock()
|
|
return q.failure
|
|
}
|
|
|
|
// release gives back d, which the worker took and did not finish, in the
|
|
// state the store has: one never marked sending reads as queued again.
|
|
func (q *Queue) release(d *delivery) {
|
|
q.mu.Lock()
|
|
defer q.mu.Unlock()
|
|
q.releaseLocked(d)
|
|
}
|
|
|
|
// releaseLocked is release for a caller that holds q.mu.
|
|
func (q *Queue) releaseLocked(d *delivery) {
|
|
d.taken = false
|
|
if d.State == StoredQueued {
|
|
d.StartedAt = time.Time{}
|
|
}
|
|
}
|
|
|
|
// 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 {
|
|
return err
|
|
}
|
|
logger.Error("job failed", "attempts", attempts, "err", cause)
|
|
if q.options.OnFailure != nil {
|
|
q.options.OnFailure(d.job.rec.ID, cause)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// 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; 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
|
|
}
|
|
}
|
|
|
|
// sending records attempt n of d as about to write to the printer. The
|
|
// first attempt that gets this far sets SentAt.
|
|
func (q *Queue) sending(ctx context.Context, d *delivery, attempt int) error {
|
|
q.mu.Lock()
|
|
next := d.Delivery
|
|
q.mu.Unlock()
|
|
next.State, next.Attempts = StoredSending, attempt
|
|
if next.SentAt.IsZero() {
|
|
next.SentAt = time.Now().UTC()
|
|
}
|
|
if err := q.store.Sending(ctx, next); err != nil {
|
|
return fmt.Errorf("recording job %s as sending: %w", d.job.rec.ID, err)
|
|
}
|
|
q.mu.Lock()
|
|
d.Delivery = next
|
|
q.mu.Unlock()
|
|
return nil
|
|
}
|
|
|
|
// finish records d as done after attempts, or as failed with cause, and
|
|
// drops in the same commit the jobs that retention lets go of. A failure
|
|
// is synced, since a failed job rolled back to queued would print after a
|
|
// restart. Once a store error has stopped the queue it writes nothing and
|
|
// returns that error.
|
|
func (q *Queue) finish(ctx context.Context, d *delivery, attempts int, cause error) error {
|
|
if err := q.stopped(); err != nil {
|
|
q.release(d)
|
|
return err
|
|
}
|
|
q.mu.Lock()
|
|
next := d.Delivery
|
|
q.mu.Unlock()
|
|
next.State, next.Attempts, next.FinishedAt = StoredDone, attempts, time.Now().UTC()
|
|
if cause != nil {
|
|
next.State, next.Error = StoredFailed, cause.Error()
|
|
}
|
|
|
|
q.mu.Lock()
|
|
finishing := d.job.finishedWith(d, next)
|
|
r := q.retention(d, next, finishing)
|
|
q.mu.Unlock()
|
|
|
|
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)
|
|
}
|
|
|
|
q.mu.Lock()
|
|
defer q.mu.Unlock()
|
|
d.Delivery, d.taken = next, false
|
|
if finishing {
|
|
d.job.finished = true
|
|
q.finished = append(q.finished, d.job)
|
|
}
|
|
for _, e := range r.statuses {
|
|
delete(q.jobs, e.rec.ID)
|
|
}
|
|
q.finished = q.finished[len(r.statuses):]
|
|
for _, e := range r.content {
|
|
e.rec.Size = 0
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// finishedWith reports whether e is finished once d is in state next.
|
|
func (e *entry) finishedWith(d *delivery, next Delivery) bool {
|
|
for _, other := range e.deliveries {
|
|
state := other.State
|
|
if other == d {
|
|
state = next.State
|
|
}
|
|
if !state.Finished() {
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
// 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)], d.job)
|
|
}
|
|
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 e.rec.Size > 0 {
|
|
r.rows.Content = append(r.rows.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 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
|
|
// then on, the job in hand writes nothing more to the store and stays as
|
|
// the store has it, and Run returns err. It returns err, marked as
|
|
// ErrStoreFailed.
|
|
func (q *Queue) stop(err error) error {
|
|
if !errors.Is(err, ErrStoreFailed) {
|
|
err = fmt.Errorf("%w: %w", ErrStoreFailed, err)
|
|
}
|
|
q.mu.Lock()
|
|
if q.failure == nil {
|
|
q.failure = err
|
|
}
|
|
q.closed = true
|
|
q.mu.Unlock()
|
|
q.halt()
|
|
q.signal()
|
|
return err
|
|
}
|
|
|
|
// signal wakes the worker, if it waits.
|
|
func (q *Queue) signal() {
|
|
select {
|
|
case q.wake <- struct{}{}:
|
|
default:
|
|
}
|
|
}
|
|
|
|
// 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
|
|
var waiting []*delivery
|
|
if !q.store.Durable() {
|
|
waiting, q.waiting = q.waiting, nil
|
|
}
|
|
q.mu.Unlock()
|
|
q.submitMu.Unlock()
|
|
|
|
storeCtx := context.WithoutCancel(ctx)
|
|
for _, d := range waiting {
|
|
if err := q.finish(storeCtx, d, 0, errShuttingDown); err != nil {
|
|
return q.stop(err)
|
|
}
|
|
}
|
|
return q.stopped()
|
|
}
|
|
|
|
// status returns the job's status, derived from its deliveries: their
|
|
// attempts summed, their earliest start and first send, and their latest
|
|
// finish once all have finished. The error is an uncertain delivery's,
|
|
// else a failed one's. The caller holds the queue's mu.
|
|
func (e *entry) status() Status {
|
|
st := Status{
|
|
ID: e.rec.ID,
|
|
State: jobState(e.deliveries),
|
|
Source: e.rec.Source,
|
|
CreatedAt: e.rec.CreatedAt,
|
|
}
|
|
var started, sent, finished time.Time
|
|
for _, d := range e.deliveries {
|
|
st.Attempts += d.Attempts
|
|
if d.Error != "" && (st.Error == "" || d.State == StoredUncertain) {
|
|
st.Error = d.Error
|
|
}
|
|
started = earliest(started, d.StartedAt)
|
|
sent = earliest(sent, d.SentAt)
|
|
if d.FinishedAt.After(finished) {
|
|
finished = d.FinishedAt
|
|
}
|
|
}
|
|
st.StartedAt, st.SentAt = timePtr(started), timePtr(sent)
|
|
if e.finished {
|
|
st.FinishedAt = timePtr(finished)
|
|
}
|
|
return st
|
|
}
|
|
|
|
// jobState derives a job's state from its deliveries': queued while every
|
|
// one waits, untaken; printing while any is unfinished once one is taken
|
|
// or finished; once every one has finished, uncertain if any is, since a
|
|
// receipt may have printed, then failed if any failed, and done
|
|
// otherwise.
|
|
func jobState(ds []*delivery) State {
|
|
var waiting, finished, failed, uncertain int
|
|
for _, d := range ds {
|
|
switch {
|
|
case d.State == StoredQueued && !d.taken:
|
|
waiting++
|
|
case d.State.Finished():
|
|
finished++
|
|
switch d.State {
|
|
case StoredFailed:
|
|
failed++
|
|
case StoredUncertain:
|
|
uncertain++
|
|
}
|
|
}
|
|
}
|
|
switch {
|
|
case waiting == len(ds):
|
|
return StateQueued
|
|
case finished < len(ds):
|
|
return StatePrinting
|
|
case uncertain > 0:
|
|
return StateUncertain
|
|
case failed > 0:
|
|
return StateFailed
|
|
}
|
|
return StateDone
|
|
}
|
|
|
|
// earliest returns the earlier of a and b, ignoring a zero time.
|
|
func earliest(a, b time.Time) time.Time {
|
|
if a.IsZero() || (!b.IsZero() && b.Before(a)) {
|
|
return b
|
|
}
|
|
return a
|
|
}
|
|
|
|
// timePtr returns &t, or nil for the zero time.
|
|
func timePtr(t time.Time) *time.Time {
|
|
if t.IsZero() {
|
|
return nil
|
|
}
|
|
return &t
|
|
}
|