Breaking: a job reads done only once the printer has confirmed that it ran it, and holds the printer's connection until then. A job written in full that the printer does not confirm within printer.write_timeout now reads uncertain and is not sent again; before, it read done. Before each job, nothing is sent until the printer answers that it can print, so with its cover open or no paper a job is retried and fails, with no sent_at, as when the printer is unreachable, where before it read done. Receipts that take longer than write_timeout to print need a larger one. With confirmation the daemon also turns the printer's automatic status off (GS a 0) before each job and before its confirmation, so another client that relies on automatic status from the same printer stops getting it. printer.confirm = false keeps the old meaning of done and sends none of this. The third paper check of the job store showed why: with the TM-T88IV's cover open, Windows took all of a 128 KB receipt into its send buffer, so the job read done; the daemon stopped, and once the cover closed only the first third printed, without its cut. The printer was then left inside the image command, waiting for the rest, until it was switched off and on. The daemon now turns on the printer client's confirmation. The queue treats an unconfirmed send as written but unknown: it records the delivery uncertain, with an error that says the printer did not confirm it and that it may have printed in full, in part or not at all, logs it at WARN with the printer, and neither retries it nor reports it as a failure. Its commit is not synced: lost, it rolls back to sending, which the next start turns uncertain too. A printer that is not ready gives a plain error before the sending mark, which the queue retries as a failed dial. The new key printer.confirm, on by default, turns confirmation off for a printer that does not answer GS r with bits 4 and 7 clear, or does not answer DLE EOT on receipt; only the TM-T88IV is checked. The key's comments in config.go and the example config say what it sends and needs. docs/api.md warns that raw bytes which make the printer answer can be taken for the confirmation, and says that /healthz answers 503 timeout while a job holds the connection. It and design.md say that each job waits about 200 ms for answers still owed, for DLE EOT 1 to say that the printer is online, and for no answer to come late. design.md says why each connection opens with DLE EOT 1, GS a 0 and GS r 1, and names what stays open: a raw job holding a command answered with bits 4 and 7 clear, such as GS r, GS I, ESC v or ESC u 0, with printing after it, and an answer taken for the ready answer that is not it, one still queued when the fence arrived or one owed from before a late DLE EOT answer that stood in for the fence, followed by a pause of more than 100 ms while the printer reads online, as might happen during the TM-m50II's feed and cut at cover close. It relies on the printer answering DLE EOT on receipt and running GS a 0 in order, unverified beyond the TM-T88IV until stage 4a's raw-byte probe, and now says a send that fails part-way can print a whole receipt twice. The unit and install.md give the stop timeout with and without state.dir: without it the job being sent runs on from its rendering, image fetches included, up to the job's 2-minute cap, so such hosts keep systemd's default or set state.dir. configuration.md says the online check can add 2 s to write_timeout. The printers plan says what Send now does before a job, and its table of what a failed send can mean gains the ready wait and the confirmation. The tests' fake printers answer DLE EOT 1 and GS r 1 as an online printer with paper does; a test runs the daemon against one that answers that it is ready but never confirms the job. On paper, a receipt read done 884 ms after it was written, when the printer answered, and a receipt whose daemon was killed while it waited, with the cover open, read uncertain after the restart and printed once, cut short. With GS a 0 and DLE EOT 1, a receipt printed once with nothing extra and read done 888 ms after it was written; after a power cycle, with /healthz polled every 250 ms, one sent with the cover open waited 15.7 s with nothing sent and printed once, cut once, when the cover closed. With the fence, a receipt printed once with nothing extra and read done 921 ms after it was written. Part of stage 1d of docs/plans/job-store.md. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
985 lines
30 KiB
Go
985 lines
30 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,
|
|
// or one the printer did not confirm, 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. done is a job the printer
|
|
// confirmed it ran, or with printer.confirm off, one written to it in
|
|
// full. uncertain is a job that was being sent to the
|
|
// printer when the daemon stopped, or that the printer did not confirm:
|
|
// it may have printed in full, in part or not at all, 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, failed or found 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. An error with an Unconfirmed method that reports true means every
|
|
// byte was written but the printer did not confirm the job: it may have
|
|
// printed in full, in part or not at all, and it is not sent again.
|
|
type Sender interface {
|
|
Send(ctx context.Context, data []byte, beforeWrite func() error) error
|
|
}
|
|
|
|
// unconfirmedSend is the end of the error of a job the printer did not
|
|
// confirm.
|
|
const unconfirmedSend = "it may have printed in full, in part or not at all, and it is not sent again"
|
|
|
|
// unconfirmed reports whether err says a job was written in full but not
|
|
// confirmed by the printer.
|
|
func unconfirmed(err error) bool {
|
|
var u interface{ Unconfirmed() bool }
|
|
return errors.As(err, &u) && u.Unconfirmed()
|
|
}
|
|
|
|
// 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
|
|
|
|
// Unique marks Ref as unique at Source, as an ntfy message's ID is: a
|
|
// job whose source and reference the queue already holds is not
|
|
// queued again. A unique job is stored with a sync. A client's request
|
|
// ID is never unique, since a client may reuse one.
|
|
Unique bool
|
|
}
|
|
|
|
// refKey is a unique job's source and reference.
|
|
type refKey struct {
|
|
source, ref 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
|
|
|
|
// refs are the kept references of unique jobs, KeptRefs per source,
|
|
// apart from the statuses; refOrder lists each source's oldest first.
|
|
refs map[refKey]JobID
|
|
refOrder map[string][]string
|
|
|
|
// 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),
|
|
refs: make(map[refKey]JobID),
|
|
refOrder: make(map[string][]string),
|
|
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. A unique job whose source and
|
|
// reference the queue already holds is not queued: Submit returns the
|
|
// earlier job's status, or only its ID and source once its status is gone.
|
|
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)
|
|
}
|
|
unique := meta.Unique && meta.Ref != ""
|
|
|
|
q.submitMu.Lock()
|
|
defer q.submitMu.Unlock()
|
|
earlier, repeated, err := q.admit(meta, unique)
|
|
if err != nil {
|
|
return Status{}, err
|
|
}
|
|
if repeated {
|
|
q.logger.Info("job already queued from this source and reference; not queued again",
|
|
"job_id", earlier.ID.String(), "source", meta.Source, "ref", meta.Ref)
|
|
return earlier, nil
|
|
}
|
|
q.nextJob++
|
|
q.nextDelivery++
|
|
rec := Record{
|
|
Seq: q.nextJob,
|
|
ID: id,
|
|
Source: meta.Source,
|
|
Ref: meta.Ref,
|
|
Sequence: meta.Sequence,
|
|
Unique: unique,
|
|
CreatedAt: time.Now().UTC(),
|
|
Deliveries: []Delivery{
|
|
{Seq: q.nextDelivery, Printer: DefaultPrinter, State: StoredQueued},
|
|
},
|
|
}
|
|
if err := q.store.Add(context.Background(), rec, content, unique); 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)
|
|
if unique {
|
|
q.keepRef(meta.Source, meta.Ref, id)
|
|
}
|
|
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. For a unique
|
|
// job whose source and reference it holds, it returns the earlier job's
|
|
// status instead, and true.
|
|
func (q *Queue) admit(meta Meta, unique bool) (Status, bool, error) {
|
|
q.mu.Lock()
|
|
defer q.mu.Unlock()
|
|
if q.closed {
|
|
return Status{}, false, ErrClosed
|
|
}
|
|
if id, ok := q.refs[refKey{meta.Source, meta.Ref}]; unique && ok {
|
|
if e, ok := q.jobs[id]; ok {
|
|
return e.status(), true, nil
|
|
}
|
|
return Status{ID: id, Source: meta.Source}, true, nil
|
|
}
|
|
if len(q.waiting) >= q.options.Size {
|
|
return Status{}, false, ErrQueueFull
|
|
}
|
|
return Status{}, false, nil
|
|
}
|
|
|
|
// Holds reports whether the queue holds a unique job of source and ref,
|
|
// among the references it keeps.
|
|
func (q *Queue) Holds(source, ref string) bool {
|
|
q.mu.Lock()
|
|
defer q.mu.Unlock()
|
|
_, ok := q.refs[refKey{source, ref}]
|
|
return ok
|
|
}
|
|
|
|
// keepRef records the reference of a unique job, and forgets the oldest of
|
|
// its source beyond KeptRefs. The caller holds q.mu.
|
|
func (q *Queue) keepRef(source, ref string, id JobID) {
|
|
q.refs[refKey{source, ref}] = id
|
|
order := append(q.refOrder[source], ref)
|
|
if len(order) > KeptRefs {
|
|
delete(q.refs, refKey{source, order[0]})
|
|
order = slices.Delete(order, 0, 1)
|
|
}
|
|
q.refOrder[source] = order
|
|
}
|
|
|
|
// 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. The kept
|
|
// references of unique jobs come back too, for the duplicate check.
|
|
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)
|
|
}
|
|
}
|
|
for _, r := range loaded.Refs {
|
|
q.keepRef(r.Source, r.Ref, r.ID)
|
|
}
|
|
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 unconfirmed(err) {
|
|
if err := q.finish(storeCtx, d, StoredUncertain, attempts, err); err != nil {
|
|
return err
|
|
}
|
|
logger.Warn("job may not have printed in full: the printer did not confirm it; it is not sent again",
|
|
"printer", d.Printer, "attempts", attempts, "err", err)
|
|
return nil
|
|
}
|
|
if err != nil {
|
|
return q.fail(storeCtx, d, attempts, err, logger)
|
|
}
|
|
if err := q.finish(storeCtx, d, StoredDone, 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, StoredFailed, 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 unconfirmed(err) || 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 in state, a final one, after attempts: done, failed
|
|
// with cause, or uncertain, unconfirmed with cause. It 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, state StoredState, 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 = state, attempts, time.Now().UTC()
|
|
switch {
|
|
case state == StoredUncertain && cause != nil:
|
|
next.Error = cause.Error() + "; " + unconfirmedSend
|
|
case cause != nil:
|
|
next.Error = 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, StoredFailed, 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
|
|
}
|