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
|
||||
}
|
||||
@@ -0,0 +1,394 @@
|
||||
package printqueue_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"reflect"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"uberbringer/internal/pkg/printqueue"
|
||||
"uberbringer/internal/pkg/receipt"
|
||||
)
|
||||
|
||||
// commit is one write a testStore committed.
|
||||
type commit struct {
|
||||
op string // add, sending or finish
|
||||
seq uint64 // the job's for add, the delivery's otherwise
|
||||
state printqueue.StoredState
|
||||
synced bool
|
||||
}
|
||||
|
||||
// testStore wraps a Store. It records each commit and whether it was
|
||||
// synced, fails the next call of a method on demand, holds the calls of a
|
||||
// method while blocked, and can rewrite the content Job returns.
|
||||
type testStore struct {
|
||||
printqueue.Store
|
||||
|
||||
mu sync.Mutex
|
||||
commits []commit
|
||||
fail map[string]error
|
||||
block map[string]*gate
|
||||
content func([]byte) []byte
|
||||
}
|
||||
|
||||
// gate holds the calls of a blocked method: entered gets a value as each
|
||||
// call arrives, and open closes to let them through.
|
||||
type gate struct {
|
||||
entered chan struct{}
|
||||
open chan struct{}
|
||||
}
|
||||
|
||||
func newTestStore(s printqueue.Store) *testStore {
|
||||
return &testStore{Store: s, fail: make(map[string]error), block: make(map[string]*gate)}
|
||||
}
|
||||
|
||||
// failNext makes the next call of op (add, sending, finish, job, idle or
|
||||
// load) fail with err.
|
||||
func (s *testStore) failNext(op string, err error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.fail[op] = err
|
||||
}
|
||||
|
||||
// blockOn holds every call of op until release is called. entered gets a
|
||||
// value as each call arrives.
|
||||
func (s *testStore) blockOn(op string) (entered <-chan struct{}, release func()) {
|
||||
g := &gate{entered: make(chan struct{}, 10), open: make(chan struct{})}
|
||||
s.mu.Lock()
|
||||
s.block[op] = g
|
||||
s.mu.Unlock()
|
||||
return g.entered, sync.OnceFunc(func() {
|
||||
s.mu.Lock()
|
||||
delete(s.block, op)
|
||||
s.mu.Unlock()
|
||||
close(g.open)
|
||||
})
|
||||
}
|
||||
|
||||
// before waits while op is blocked, then returns the error its call is to
|
||||
// fail with, if any.
|
||||
func (s *testStore) before(op string) error {
|
||||
s.mu.Lock()
|
||||
err := s.fail[op]
|
||||
delete(s.fail, op)
|
||||
g := s.block[op]
|
||||
s.mu.Unlock()
|
||||
if g != nil {
|
||||
g.entered <- struct{}{}
|
||||
<-g.open
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *testStore) record(c commit) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.commits = append(s.commits, c)
|
||||
}
|
||||
|
||||
// Commits returns the commits so far, in order.
|
||||
func (s *testStore) Commits() []commit {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return slices.Clone(s.commits)
|
||||
}
|
||||
|
||||
func (s *testStore) Load(ctx context.Context) (printqueue.Loaded, error) {
|
||||
if err := s.before("load"); err != nil {
|
||||
return printqueue.Loaded{}, err
|
||||
}
|
||||
return s.Store.Load(ctx)
|
||||
}
|
||||
|
||||
func (s *testStore) Add(ctx context.Context, r printqueue.Record, job []byte, sync bool) error {
|
||||
if err := s.before("add"); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.Store.Add(ctx, r, job, sync); err != nil {
|
||||
return err
|
||||
}
|
||||
s.record(commit{op: "add", seq: r.Seq, state: printqueue.StoredQueued, synced: sync})
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *testStore) Sending(ctx context.Context, d printqueue.Delivery) error {
|
||||
if err := s.before("sending"); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.Store.Sending(ctx, d); err != nil {
|
||||
return err
|
||||
}
|
||||
s.record(commit{op: "sending", seq: d.Seq, state: printqueue.StoredSending, synced: true})
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *testStore) Finish(ctx context.Context, d printqueue.Delivery, p printqueue.Prune, sync bool) error {
|
||||
if err := s.before("finish"); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.Store.Finish(ctx, d, p, sync); err != nil {
|
||||
return err
|
||||
}
|
||||
s.record(commit{op: "finish", seq: d.Seq, state: d.State, synced: sync})
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *testStore) Job(ctx context.Context, seq uint64) ([]byte, error) {
|
||||
if err := s.before("job"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
data, err := s.Store.Job(ctx, seq)
|
||||
s.mu.Lock()
|
||||
rewrite := s.content
|
||||
s.mu.Unlock()
|
||||
if err == nil && rewrite != nil {
|
||||
data = rewrite(data)
|
||||
}
|
||||
return data, err
|
||||
}
|
||||
|
||||
func (s *testStore) Idle(ctx context.Context) error {
|
||||
if err := s.before("idle"); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.Store.Idle(ctx)
|
||||
}
|
||||
|
||||
// runQueue runs q in the background. stop cancels Run's context and
|
||||
// returns what Run returned; done is closed once Run has returned.
|
||||
func runQueue(t *testing.T, q *printqueue.Queue) (stop func() error, done <-chan struct{}) {
|
||||
t.Helper()
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
finished := make(chan struct{})
|
||||
var err error
|
||||
go func() {
|
||||
defer close(finished)
|
||||
err = q.Run(ctx)
|
||||
}()
|
||||
stop = func() error {
|
||||
cancel()
|
||||
<-finished
|
||||
return err
|
||||
}
|
||||
t.Cleanup(func() { _ = stop() })
|
||||
return stop, finished
|
||||
}
|
||||
|
||||
// waitClosed waits for done to close or to give a value.
|
||||
func waitClosed(t *testing.T, done <-chan struct{}, what string) {
|
||||
t.Helper()
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatalf("%s did not happen", what)
|
||||
}
|
||||
}
|
||||
|
||||
var errDisk = errors.New("disk I/O error")
|
||||
|
||||
// The sending mark and a failure are synced; the insert of a job from the
|
||||
// routes and its done are not. A failed dial writes no sending mark.
|
||||
func TestCommitsAndSyncs(t *testing.T) {
|
||||
store := newTestStore(printqueue.NewMemoryStore())
|
||||
sender := &fakeSender{failures: 1}
|
||||
q := newQueueOn(store, fakeRenderer{}, sender, discardLogger(), printqueue.Options{Retries: 1})
|
||||
startQueue(t, q)
|
||||
|
||||
first, _ := q.Submit(job("first"), printqueue.Meta{})
|
||||
waitForState(t, q, first.ID, printqueue.StateDone)
|
||||
sender.mu.Lock()
|
||||
sender.failures = 2
|
||||
sender.mu.Unlock()
|
||||
second, _ := q.Submit(job("second"), printqueue.Meta{})
|
||||
if st := waitForState(t, q, second.ID, printqueue.StateFailed); st.Attempts != 2 {
|
||||
t.Errorf("second job %+v, want 2 attempts", st)
|
||||
}
|
||||
|
||||
want := []commit{
|
||||
{op: "add", seq: 1, state: printqueue.StoredQueued},
|
||||
{op: "sending", seq: 1, state: printqueue.StoredSending, synced: true},
|
||||
{op: "finish", seq: 1, state: printqueue.StoredDone},
|
||||
{op: "add", seq: 2, state: printqueue.StoredQueued},
|
||||
{op: "finish", seq: 2, state: printqueue.StoredFailed, synced: true},
|
||||
}
|
||||
if got := store.Commits(); !slices.Equal(got, want) {
|
||||
t.Errorf("commits\n%+v\nwant\n%+v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// The job the worker renders is the job submitted, read back from the
|
||||
// store.
|
||||
func TestJobRoundTripsThroughTheStore(t *testing.T) {
|
||||
var submitted receipt.Job
|
||||
body := `{"elements": [{"type": "text", "text": "Grüße", "align": "center", "bold": true, "size": 2},
|
||||
{"type": "kv", "pairs": [{"key": "Total", "value": "£12.50", "bold": true}]},
|
||||
{"type": "qr", "data": "https://example.com", "size": 6},
|
||||
{"type": "box", "title": "T", "children": [{"type": "text", "text": "in a box"}]}], "copies": 2}`
|
||||
if err := json.Unmarshal([]byte(body), &submitted); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rendered := make(chan receipt.Job, 1)
|
||||
renderer := rendererFunc(func(job receipt.Job) ([]byte, error) {
|
||||
rendered <- job
|
||||
return []byte("x"), nil
|
||||
})
|
||||
q := newQueue(renderer, &fakeSender{}, printqueue.Options{})
|
||||
startQueue(t, q)
|
||||
if _, err := q.Submit(submitted, printqueue.Meta{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
select {
|
||||
case got := <-rendered:
|
||||
if !reflect.DeepEqual(got, submitted) {
|
||||
t.Errorf("rendered %+v\nwant %+v", got, submitted)
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("the job was not rendered")
|
||||
}
|
||||
}
|
||||
|
||||
// rendererFunc is a Renderer.
|
||||
type rendererFunc func(receipt.Job) ([]byte, error)
|
||||
|
||||
func (f rendererFunc) Render(_ context.Context, job receipt.Job) ([]byte, error) {
|
||||
return f(job)
|
||||
}
|
||||
|
||||
// While a commit is held, Status and Pending still answer.
|
||||
func TestStatusAnswersDuringACommit(t *testing.T) {
|
||||
store := newTestStore(printqueue.NewMemoryStore())
|
||||
sender := &fakeSender{}
|
||||
q := newQueueOn(store, fakeRenderer{}, sender, discardLogger(), printqueue.Options{})
|
||||
startQueue(t, q)
|
||||
|
||||
inFinish, releaseFinish := store.blockOn("finish")
|
||||
defer releaseFinish()
|
||||
first, _ := q.Submit(job("first"), printqueue.Meta{})
|
||||
waitClosed(t, inFinish, "the finish commit")
|
||||
|
||||
inAdd, releaseAdd := store.blockOn("add")
|
||||
defer releaseAdd()
|
||||
submitted := make(chan struct{})
|
||||
go func() {
|
||||
defer close(submitted)
|
||||
_, _ = q.Submit(job("second"), printqueue.Meta{})
|
||||
}()
|
||||
waitClosed(t, inAdd, "the second insert")
|
||||
|
||||
answered := make(chan struct{})
|
||||
go func() {
|
||||
defer close(answered)
|
||||
if st, err := q.Status(first.ID); err != nil || st.State != printqueue.StatePrinting {
|
||||
t.Errorf("status %+v, %v during the held finish", st, err)
|
||||
}
|
||||
_ = q.Pending()
|
||||
}()
|
||||
waitClosed(t, answered, "Status and Pending answering")
|
||||
releaseAdd()
|
||||
waitClosed(t, submitted, "the second Submit")
|
||||
releaseFinish()
|
||||
waitForState(t, q, first.ID, printqueue.StateDone)
|
||||
waitFor(t, func() bool { return q.Pending() == 0 && len(sender.Sent()) == 2 })
|
||||
}
|
||||
|
||||
// A stored job that no longer decodes fails, logged by ID and never with
|
||||
// its content.
|
||||
func TestUndecodableJobFails(t *testing.T) {
|
||||
var logs lockedBuffer
|
||||
store := newTestStore(printqueue.NewMemoryStore())
|
||||
store.content = func([]byte) []byte {
|
||||
return []byte(`{"elements": [{"type": "text", "text": "secret words"}], "renamed_field": 1}`)
|
||||
}
|
||||
sender := &fakeSender{}
|
||||
q := newQueueOn(store, fakeRenderer{}, sender, slog.New(slog.NewTextHandler(&logs, nil)), printqueue.Options{})
|
||||
startQueue(t, q)
|
||||
st, _ := q.Submit(job("secret words"), printqueue.Meta{Source: "print", Ref: "req_1"})
|
||||
failed := waitForState(t, q, st.ID, printqueue.StateFailed)
|
||||
if !strings.Contains(failed.Error, "no longer decodes") || len(sender.Sent()) != 0 {
|
||||
t.Errorf("status %+v, sent %v", failed, sender.Sent())
|
||||
}
|
||||
out := logs.String()
|
||||
if !strings.Contains(out, "job_id="+st.ID.String()) || !strings.Contains(out, "no longer decodes") {
|
||||
t.Errorf("log %q, want the failure with the job's ID", out)
|
||||
}
|
||||
if strings.Contains(out, "secret") || strings.Contains(out, "renamed_field") {
|
||||
t.Errorf("log %q quotes the stored job", out)
|
||||
}
|
||||
}
|
||||
|
||||
// Statuses beyond History go from the store with their deliveries in the
|
||||
// commit that finishes the job pushing them out, and a job's content goes
|
||||
// in the commit that finishes it.
|
||||
func TestHistoryPrunesTheStore(t *testing.T) {
|
||||
inner := printqueue.NewMemoryStore()
|
||||
q := newQueueOn(inner, fakeRenderer{}, &fakeSender{}, discardLogger(), printqueue.Options{History: 2})
|
||||
startQueue(t, q)
|
||||
var ids []printqueue.JobID
|
||||
for range 4 {
|
||||
st, _ := q.Submit(job("x"), printqueue.Meta{})
|
||||
ids = append(ids, st.ID)
|
||||
waitForState(t, q, st.ID, printqueue.StateDone)
|
||||
}
|
||||
loaded, err := inner.Load(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var kept []printqueue.JobID
|
||||
for _, r := range loaded.Records {
|
||||
kept = append(kept, r.ID)
|
||||
}
|
||||
if !slices.Equal(kept, ids[2:]) {
|
||||
t.Errorf("store keeps %v, want the last two, %v", kept, ids[2:])
|
||||
}
|
||||
for seq := uint64(1); seq <= 4; seq++ {
|
||||
if _, err := inner.Job(context.Background(), seq); !errors.Is(err, printqueue.ErrContentGone) {
|
||||
t.Errorf("content of job %d: %v, want ErrContentGone", seq, err)
|
||||
}
|
||||
}
|
||||
if r := loaded.Records[1]; r.Size != 0 {
|
||||
t.Errorf("job 4 keeps %d bytes of content", r.Size)
|
||||
}
|
||||
}
|
||||
|
||||
// A store error is returned: by Submit, which then queues nothing, and by
|
||||
// Run, after a sending mark that failed with nothing written.
|
||||
func TestStoreErrorsAreReturned(t *testing.T) {
|
||||
store := newTestStore(printqueue.NewMemoryStore())
|
||||
sender := &fakeSender{}
|
||||
q := newQueueOn(store, fakeRenderer{}, sender, discardLogger(), printqueue.Options{})
|
||||
store.failNext("add", errDisk)
|
||||
if _, err := q.Submit(job("x"), printqueue.Meta{}); !errors.Is(err, errDisk) || q.Pending() != 0 {
|
||||
t.Fatalf("Submit = %v with %d pending, want the store's error and nothing queued", err, q.Pending())
|
||||
}
|
||||
|
||||
store.failNext("sending", errDisk)
|
||||
if _, err := q.Submit(job("y"), printqueue.Meta{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
stop, done := runQueue(t, q)
|
||||
waitClosed(t, done, "Run's return")
|
||||
if err := stop(); !errors.Is(err, errDisk) {
|
||||
t.Errorf("Run = %v, want the store's error", err)
|
||||
}
|
||||
if sent := sender.Sent(); len(sent) != 0 {
|
||||
t.Errorf("sent %v after the mark failed", sent)
|
||||
}
|
||||
}
|
||||
|
||||
// waitFor polls cond until it holds.
|
||||
func waitFor(t *testing.T, cond func() bool) {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for !cond() {
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatal("condition not met")
|
||||
}
|
||||
time.Sleep(2 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
@@ -23,24 +23,37 @@ func (f fakeRenderer) Render(_ context.Context, job receipt.Job) ([]byte, error)
|
||||
return []byte(job.Elements[0].Text), nil
|
||||
}
|
||||
|
||||
// fakeSender fails the first failures sends, then records data.
|
||||
// fakeSender fails the first failures sends as a failed dial does, before
|
||||
// beforeWrite. Then it calls beforeWrite, fails the next writeFailures
|
||||
// sends as a failed write does, and records data.
|
||||
type fakeSender struct {
|
||||
mu sync.Mutex
|
||||
failures int
|
||||
sent []string
|
||||
block chan struct{} // if set, Send waits for it to close
|
||||
mu sync.Mutex
|
||||
failures int
|
||||
writeFailures int
|
||||
sent []string
|
||||
block chan struct{} // if set, Send waits for it to close
|
||||
}
|
||||
|
||||
func (f *fakeSender) Send(_ context.Context, data []byte, _ func() error) error {
|
||||
func (f *fakeSender) Send(_ context.Context, data []byte, beforeWrite func() error) error {
|
||||
if f.block != nil {
|
||||
<-f.block
|
||||
}
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
if f.failures > 0 {
|
||||
f.failures--
|
||||
f.mu.Unlock()
|
||||
return errors.New("printer offline")
|
||||
}
|
||||
f.mu.Unlock()
|
||||
if err := beforeWrite(); err != nil {
|
||||
return err
|
||||
}
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
if f.writeFailures > 0 {
|
||||
f.writeFailures--
|
||||
return errors.New("connection reset")
|
||||
}
|
||||
f.sent = append(f.sent, string(data))
|
||||
return nil
|
||||
}
|
||||
@@ -60,6 +73,12 @@ func discardLogger() *slog.Logger {
|
||||
}
|
||||
|
||||
func newQueue(r printqueue.Renderer, s printqueue.Sender, opts printqueue.Options) *printqueue.Queue {
|
||||
return newQueueOn(printqueue.NewMemoryStore(), r, s, discardLogger(), opts)
|
||||
}
|
||||
|
||||
// newQueueOn returns a queue on store, with test defaults for the options
|
||||
// left zero.
|
||||
func newQueueOn(store printqueue.Store, r printqueue.Renderer, s printqueue.Sender, logger *slog.Logger, opts printqueue.Options) *printqueue.Queue {
|
||||
if opts.Size == 0 {
|
||||
opts.Size = 10
|
||||
}
|
||||
@@ -69,7 +88,7 @@ func newQueue(r printqueue.Renderer, s printqueue.Sender, opts printqueue.Option
|
||||
if opts.RetryDelay == 0 {
|
||||
opts.RetryDelay = time.Millisecond
|
||||
}
|
||||
return printqueue.New(r, s, discardLogger(), opts)
|
||||
return printqueue.New(r, s, store, logger, opts)
|
||||
}
|
||||
|
||||
// startQueue runs q until the test ends. cancel cancels Run's context and
|
||||
@@ -153,7 +172,7 @@ func (b *lockedBuffer) String() string {
|
||||
func TestMetaInStatusAndLogs(t *testing.T) {
|
||||
var logs lockedBuffer
|
||||
// One failed send, so that the retry is logged too.
|
||||
q := printqueue.New(fakeRenderer{}, &fakeSender{failures: 1}, slog.New(slog.NewTextHandler(&logs, nil)),
|
||||
q := newQueueOn(printqueue.NewMemoryStore(), fakeRenderer{}, &fakeSender{failures: 1}, slog.New(slog.NewTextHandler(&logs, nil)),
|
||||
printqueue.Options{Size: 1, History: 1, Retries: 1, RetryDelay: time.Millisecond})
|
||||
startQueue(t, q)
|
||||
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
package printqueue
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// deliveryKind is a delivery's state as the status rule reads it.
|
||||
type deliveryKind struct {
|
||||
name string
|
||||
state StoredState
|
||||
taken bool
|
||||
}
|
||||
|
||||
var deliveryKinds = []deliveryKind{
|
||||
{"waiting", StoredQueued, false},
|
||||
{"taken", StoredQueued, true},
|
||||
{"sending", StoredSending, true},
|
||||
{"done", StoredDone, false},
|
||||
{"failed", StoredFailed, false},
|
||||
}
|
||||
|
||||
// A job's status follows from its deliveries': queued while every one
|
||||
// waits, printing while any is unfinished once one was taken or finished,
|
||||
// and once all have finished, failed over done. Every mix of one, two and
|
||||
// three deliveries is checked.
|
||||
func TestJobStateFromDeliveries(t *testing.T) {
|
||||
for n := 1; n <= 3; n++ {
|
||||
for _, mix := range mixes(n) {
|
||||
var ds []*delivery
|
||||
var names []string
|
||||
waiting, finished, failed := 0, 0, 0
|
||||
for _, k := range mix {
|
||||
ds = append(ds, &delivery{Delivery: Delivery{State: k.state}, taken: k.taken})
|
||||
names = append(names, k.name)
|
||||
switch k.name {
|
||||
case "waiting":
|
||||
waiting++
|
||||
case "done":
|
||||
finished++
|
||||
case "failed":
|
||||
finished++
|
||||
failed++
|
||||
}
|
||||
}
|
||||
want := StateDone
|
||||
switch {
|
||||
case waiting == n:
|
||||
want = StateQueued
|
||||
case finished < n:
|
||||
want = StatePrinting
|
||||
case failed > 0:
|
||||
want = StateFailed
|
||||
}
|
||||
if got := jobState(ds); got != want {
|
||||
t.Errorf("%s: %s, want %s", strings.Join(names, ", "), got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for _, tt := range []struct {
|
||||
mix []string
|
||||
want State
|
||||
}{
|
||||
{[]string{"waiting", "waiting"}, StateQueued},
|
||||
{[]string{"waiting", "done"}, StatePrinting},
|
||||
{[]string{"failed", "waiting", "sending"}, StatePrinting},
|
||||
{[]string{"done", "failed", "done"}, StateFailed},
|
||||
{[]string{"done", "done", "done"}, StateDone},
|
||||
} {
|
||||
var ds []*delivery
|
||||
for _, name := range tt.mix {
|
||||
k := kindNamed(name)
|
||||
ds = append(ds, &delivery{Delivery: Delivery{State: k.state}, taken: k.taken})
|
||||
}
|
||||
if got := jobState(ds); got != tt.want {
|
||||
t.Errorf("%v: %s, want %s", tt.mix, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// mixes returns every sequence of n delivery kinds.
|
||||
func mixes(n int) [][]deliveryKind {
|
||||
if n == 0 {
|
||||
return [][]deliveryKind{nil}
|
||||
}
|
||||
var out [][]deliveryKind
|
||||
for _, rest := range mixes(n - 1) {
|
||||
for _, k := range deliveryKinds {
|
||||
out = append(out, append(append([]deliveryKind(nil), rest...), k))
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func kindNamed(name string) deliveryKind {
|
||||
for _, k := range deliveryKinds {
|
||||
if k.name == name {
|
||||
return k
|
||||
}
|
||||
}
|
||||
panic(fmt.Sprintf("no delivery kind %q", name))
|
||||
}
|
||||
Reference in new issue
Block a user