// 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") // 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" ) // Status describes a job. type Status struct { // ID identifies the job. ID JobID `json:"id"` // State is where the job is in its lifecycle. State State `json:"status" jsonschema:"enum=queued,enum=printing,enum=done,enum=failed"` // Source says where the job came from: print for POST /api/v1/print, // module: for a module route, e.g. module:ntfy, or // ntfy: for an ntfy subscription in the config. Source string `json:"source,omitempty"` // Error says why a failed job failed. 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"` // FinishedAt is when the job was done or failed. 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. 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 // 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 } // 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 is returned: by Submit, which then queues nothing, or by Run, // which then ends. 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 // wake tells the worker that a delivery is waiting. wake chan struct{} } // 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) return &Queue{ renderer: renderer, sender: sender, store: store, logger: logger, options: options, jobs: make(map[JobID]*entry), wake: make(chan struct{}, 1), } } // 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 is returned, and the job // is not queued. 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, 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{}, 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) } // 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 a store error, which ends it. 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 err } } } // next waits for a delivery and takes it. It returns nil once ctx is // done. 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 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.store.Idle(context.WithoutCancel(ctx)); err != nil { return nil, 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 { // 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) defer 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: 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 { q.mu.Lock() d.taken = false q.mu.Unlock() return storeErr } 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 } // 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. 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) delay := q.options.RetryDelay for attempt := 1; ; attempt++ { err := q.sender.Send(jobCtx, data, func() error { storeErr = q.sending(storeCtx, d, attempt) return storeErr }) switch { case storeErr != nil: return attempt, nil, storeErr case err == nil: return attempt, nil, nil case attempt > q.options.Retries: return attempt, err, nil } 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(): 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. func (q *Queue) finish(ctx context.Context, d *delivery, attempts int, cause error) error { 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) prune, drop := q.retention(d.job, finishing) q.mu.Unlock() if err := q.store.Finish(ctx, next, prune, next.State == StoredFailed); err != nil { 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 d.job.rec.Size = 0 q.finished = append(q.finished, d.job) } for _, e := range drop { delete(q.jobs, e.rec.ID) } q.finished = q.finished[len(drop):] 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 } // 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) { finished := q.finished if finishing { finished = append(finished[:len(finished):len(finished)], e) } 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) } if old.rec.Size > 0 { p.Content = append(p.Content, old.rec.Seq) } } if finishing && len(drop) < len(finished) && e.rec.Size > 0 { p.Content = append(p.Content, e.rec.Seq) } return p, drop } // signal wakes the worker, if it waits. func (q *Queue) signal() { select { case q.wake <- struct{}{}: default: } } // shutdown stops accepting jobs and fails those still waiting. It returns // a store error, if recording a failure met one. func (q *Queue) shutdown(ctx context.Context) error { q.submitMu.Lock() q.mu.Lock() q.closed = true 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 err } } return nil } // status returns the job's status, derived from its deliveries. 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, finished time.Time for _, d := range e.deliveries { st.Attempts += d.Attempts if st.Error == "" { st.Error = d.Error } if !d.StartedAt.IsZero() && (started.IsZero() || d.StartedAt.Before(started)) { started = d.StartedAt } if d.FinishedAt.After(finished) { finished = d.FinishedAt } } st.StartedAt = timePtr(started) 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, failed if any failed, and // done otherwise. func jobState(ds []*delivery) State { var waiting, finished, failed int for _, d := range ds { switch { case d.State == StoredQueued && !d.taken: waiting++ case d.State.Finished(): finished++ if d.State == StoredFailed { failed++ } } } switch { case waiting == len(ds): return StateQueued case finished < len(ds): return StatePrinting case failed > 0: return StateFailed } return StateDone } // timePtr returns &t, or nil for the zero time. func timePtr(t time.Time) *time.Time { if t.IsZero() { return nil } return &t }