Keep print jobs in the job store
The queue now keeps its jobs in a Store, the memory store for now, so that a store on disk can take its place. Submit stores the job as JSON before it answers, and the worker reads it back and decodes it when it takes it, so what prints is what was stored. Each job has one delivery, for the printer "default", and its status derives from its deliveries: queued while all wait, printing while any is unfinished, then failed over done once all have finished. Every change is committed to the store first and made in memory after, so a status never shows what the store lacks. Once the printer's connection is open and before the first byte, the worker records the attempt as sending; a failed dial records nothing. A failure is committed with a sync, since one rolled back to queued would print after a restart. A job's content goes in the commit that finishes it, as it went from memory before, and statuses past queue.history leave the store in the commit that finishes the job pushing them out. A job whose stored content no longer decodes fails without its content in the logs. A submit lock covers the capacity check, the insert and the append to the waiting list; the status lock is never held across a store call, so Status and Pending answer during a commit. A store error is returned, by Submit with nothing queued, or by Run, which ends; shutdown is as before. 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:
1 parent
dbfabd1613
commit
14c5e86ab6
5 files changed
+914
-104
No files matched your search
@@ -1,12 +1,14 @@
|
||||
// Package printqueue prints jobs one at a time, in submission order, and
|
||||
// keeps track of their status.
|
||||
// keeps track of their status. Jobs are kept in a Store.
|
||||
package printqueue
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"slices"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
@@ -29,6 +31,10 @@ var (
|
||||
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.
|
||||
@@ -123,34 +129,63 @@ type Meta struct {
|
||||
Ref string
|
||||
}
|
||||
|
||||
type queuedJob struct {
|
||||
id JobID
|
||||
job receipt.Job
|
||||
meta Meta
|
||||
// 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
|
||||
|
||||
// mu guards statuses, waiting, finished and closed.
|
||||
// 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
|
||||
statuses map[JobID]*Status
|
||||
waiting []queuedJob // in submission order
|
||||
finished []JobID // oldest first, for history eviction
|
||||
jobs map[JobID]*entry
|
||||
waiting []*delivery // in submission order
|
||||
finished []*entry // oldest first, for history eviction
|
||||
closed bool
|
||||
|
||||
// wake tells the worker that a job is waiting.
|
||||
// wake tells the worker that a delivery is waiting.
|
||||
wake chan struct{}
|
||||
}
|
||||
|
||||
// New returns a Queue. Call Run to start printing.
|
||||
func New(renderer Renderer, sender Sender, logger *slog.Logger, options Options) *Queue {
|
||||
if renderer == nil || sender == nil || logger == nil {
|
||||
panic("printqueue.New: renderer, sender and logger must not be nil")
|
||||
// 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")
|
||||
@@ -158,55 +193,101 @@ func New(renderer Renderer, sender Sender, logger *slog.Logger, options Options)
|
||||
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,
|
||||
statuses: make(map[JobID]*Status),
|
||||
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.
|
||||
// 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 Status{}, ErrClosed
|
||||
return ErrClosed
|
||||
case len(q.waiting) >= q.options.Size:
|
||||
return Status{}, ErrQueueFull
|
||||
return ErrQueueFull
|
||||
}
|
||||
q.waiting = append(q.waiting, queuedJob{id: id, job: job, meta: meta})
|
||||
status := &Status{ID: id, State: StateQueued, Source: meta.Source, CreatedAt: time.Now().UTC()}
|
||||
q.statuses[id] = status
|
||||
select {
|
||||
case q.wake <- struct{}{}:
|
||||
default:
|
||||
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})
|
||||
}
|
||||
return *status, nil
|
||||
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()
|
||||
status, ok := q.statuses[id]
|
||||
e, ok := q.jobs[id]
|
||||
if !ok {
|
||||
return Status{}, ErrNotFound
|
||||
}
|
||||
return *status, nil
|
||||
return e.status(), nil
|
||||
}
|
||||
|
||||
// Pending returns the number of jobs waiting to print.
|
||||
// Pending returns the number of deliveries waiting to print.
|
||||
func (q *Queue) Pending() int {
|
||||
q.mu.Lock()
|
||||
defer q.mu.Unlock()
|
||||
@@ -214,35 +295,49 @@ func (q *Queue) Pending() int {
|
||||
}
|
||||
|
||||
// Run prints jobs until ctx is cancelled. A job that is printing when ctx is
|
||||
// cancelled is finished; jobs still waiting are marked failed.
|
||||
// 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 {
|
||||
qj, ok := q.next(ctx)
|
||||
if !ok {
|
||||
q.shutdown()
|
||||
return nil
|
||||
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
|
||||
}
|
||||
q.process(ctx, qj)
|
||||
}
|
||||
}
|
||||
|
||||
// next waits for a job and takes it. It returns false once ctx is done:
|
||||
// no new job starts once shutdown has begun.
|
||||
func (q *Queue) next(ctx context.Context) (queuedJob, bool) {
|
||||
// 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 queuedJob{}, false
|
||||
return nil, nil
|
||||
case len(q.waiting) > 0:
|
||||
qj := q.waiting[0]
|
||||
q.waiting[0] = queuedJob{}
|
||||
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 qj, true
|
||||
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:
|
||||
@@ -250,94 +345,283 @@ func (q *Queue) next(ctx context.Context) (queuedJob, bool) {
|
||||
}
|
||||
}
|
||||
|
||||
func (q *Queue) process(ctx context.Context, qj queuedJob) {
|
||||
// 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)
|
||||
|
||||
q.update(qj.id, func(s *Status) {
|
||||
now := time.Now().UTC()
|
||||
s.State, s.StartedAt = StatePrinting, &now
|
||||
})
|
||||
logger := q.logger.With("job_id", qj.id.String(), "source", qj.meta.Source, "ref", qj.meta.Ref)
|
||||
logger.Info("printing job", "elements", len(qj.job.Elements), "copies", max(qj.job.Copies, 1))
|
||||
|
||||
attempts, err := q.print(ctx, jobCtx, qj.job, logger)
|
||||
q.finish(qj.id, attempts, err)
|
||||
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 {
|
||||
logger.Error("job failed", "attempts", attempts, "err", err)
|
||||
if q.options.OnFailure != nil {
|
||||
q.options.OnFailure(qj.id, err)
|
||||
}
|
||||
return
|
||||
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.
|
||||
// Retries stop early when runCtx is cancelled. logger carries the job's
|
||||
// fields.
|
||||
func (q *Queue) print(runCtx, jobCtx context.Context, job receipt.Job, logger *slog.Logger) (int, error) {
|
||||
// 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)
|
||||
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, nil)
|
||||
if err == nil {
|
||||
return attempt, nil
|
||||
}
|
||||
if attempt > q.options.Retries {
|
||||
return attempt, err
|
||||
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)
|
||||
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)
|
||||
return attempt, fmt.Errorf("giving up after %d attempts: %w", attempt, err), nil
|
||||
}
|
||||
delay *= 2
|
||||
}
|
||||
}
|
||||
|
||||
func (q *Queue) finish(id JobID, attempts int, err error) {
|
||||
q.update(id, func(s *Status) {
|
||||
now := time.Now().UTC()
|
||||
s.FinishedAt, s.Attempts = &now, attempts
|
||||
s.State = StateDone
|
||||
if err != nil {
|
||||
s.State, s.Error = StateFailed, err.Error()
|
||||
// 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
|
||||
}
|
||||
})
|
||||
q.mu.Lock()
|
||||
defer q.mu.Unlock()
|
||||
q.finished = append(q.finished, id)
|
||||
for len(q.finished) > q.options.History {
|
||||
delete(q.statuses, q.finished[0])
|
||||
q.finished = q.finished[1:]
|
||||
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:
|
||||
}
|
||||
}
|
||||
|
||||
func (q *Queue) update(id JobID, fn func(*Status)) {
|
||||
q.mu.Lock()
|
||||
defer q.mu.Unlock()
|
||||
if s, ok := q.statuses[id]; ok {
|
||||
fn(s)
|
||||
}
|
||||
}
|
||||
|
||||
// shutdown stops accepting jobs and fails those still waiting.
|
||||
func (q *Queue) shutdown() {
|
||||
// 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()
|
||||
for _, qj := range waiting {
|
||||
q.finish(qj.id, 0, errShuttingDown)
|
||||
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
|
||||
}
|
||||
Reference in new issue
Block a user