Stop the print queue when its store fails
A store write that fails after start, such as on a full disk or a damaged page, must stop the daemon, and nothing is retried: a write that failed once seldom succeeds a moment later. The queue now stops on the first store error. Submit answers that error once and ErrClosed after, the job in hand writes nothing more to the store and keeps the state the store last recorded, so one not yet marked sending reads as queued again, and Run returns the error. A failure that an insert meets while shutdown waits for it is returned too. Every store error that stops the queue is marked ErrStoreFailed. serve logs it once at ERROR, reports it to Sentry once and stops the daemon. A request whose job could not be stored answers 500 internal_error without being logged or reported again, so the failure is reported once whoever submitted the job. docs/configuration.md lists it under Logs. With the memory store nothing fails, so the daemon behaves 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
14c5e86ab6
commit
7e6cda16f8
7 files changed
+349
-45
No files matched your search
@@ -227,8 +227,11 @@ Request bodies and the `Authorization` header are never sent to Sentry.
|
|||||||
- An unexpected failure is logged at ERROR and reported to Sentry once: a
|
- An unexpected failure is logged at ERROR and reported to Sentry once: a
|
||||||
request that fails or panics, a job that fails after its retries
|
request that fails or panics, a job that fails after its retries
|
||||||
(`job failed`), a module that builds an invalid receipt, a notification
|
(`job failed`), a module that builds an invalid receipt, a notification
|
||||||
card or digest that prints its plain fallback, and an ntfy state file
|
card or digest that prints its plain fallback, an ntfy state file that
|
||||||
that cannot be written.
|
cannot be written, and a job store that fails (`print queue stopped`),
|
||||||
|
which stops the daemon. A request whose job it could not store answers
|
||||||
|
`500` `internal_error`; the failure is logged and reported with the
|
||||||
|
stop, not again for the request.
|
||||||
- Refusals are never logged at ERROR and never go to Sentry. They are the
|
- Refusals are never logged at ERROR and never go to Sentry. They are the
|
||||||
4xx answers other than `module_failed`, the `queue_full` and
|
4xx answers other than `module_failed`, the `queue_full` and
|
||||||
`shutting_down` 503s, and 503s from `/healthz`.
|
`shutting_down` 503s, and 503s from `/healthz`.
|
||||||
@@ -137,7 +137,7 @@ func run(ctx context.Context, cfg *config.Config, build BuildInfo, out io.Writer
|
|||||||
"paper_dots", profile.DotsPerLine)
|
"paper_dots", profile.DotsPerLine)
|
||||||
|
|
||||||
group, groupCtx := errgroup.WithContext(ctx)
|
group, groupCtx := errgroup.WithContext(ctx)
|
||||||
group.Go(func() error { return queue.Run(groupCtx) })
|
group.Go(func() error { return runQueue(groupCtx, queue, logger) })
|
||||||
group.Go(func() error { return srv.Serve(groupCtx, ln) })
|
group.Go(func() error { return srv.Serve(groupCtx, ln) })
|
||||||
for _, sub := range subscribers {
|
for _, sub := range subscribers {
|
||||||
handler := &ntfyPrinter{name: sub.Status().Name, jobs: queue, env: env, logger: logger}
|
handler := &ntfyPrinter{name: sub.Status().Name, jobs: queue, env: env, logger: logger}
|
||||||
@@ -214,6 +214,19 @@ func initSentry(cfg config.SentryConfig, build BuildInfo, logger *slog.Logger) (
|
|||||||
return func() { sentry.Flush(sentryFlushTimeout) }, nil
|
return func() { sentry.Flush(sentryFlushTimeout) }, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// runQueue runs queue until ctx is cancelled. A job store error stops the
|
||||||
|
// queue, and with it the daemon: it is logged and reported to Sentry here,
|
||||||
|
// once, and returned.
|
||||||
|
func runQueue(ctx context.Context, queue *printqueue.Queue, logger *slog.Logger) error {
|
||||||
|
err := queue.Run(ctx)
|
||||||
|
if err != nil {
|
||||||
|
logger.Error("print queue stopped: the job store failed", "err", err)
|
||||||
|
sentry.CurrentHub().Clone().CaptureException(err)
|
||||||
|
return fmt.Errorf("print queue: %w", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
// closeStore releases the job store once the daemon has stopped.
|
// closeStore releases the job store once the daemon has stopped.
|
||||||
func closeStore(store printqueue.Store, logger *slog.Logger) {
|
func closeStore(store printqueue.Store, logger *slog.Logger) {
|
||||||
if err := store.Close(); err != nil {
|
if err := store.Close(); err != nil {
|
||||||
|
|||||||
@@ -4,8 +4,10 @@ import (
|
|||||||
"bytes"
|
"bytes"
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
|
"log/slog"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
@@ -16,6 +18,8 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"uberbringer/internal/pkg/config"
|
"uberbringer/internal/pkg/config"
|
||||||
|
"uberbringer/internal/pkg/printqueue"
|
||||||
|
"uberbringer/internal/pkg/receipt"
|
||||||
)
|
)
|
||||||
|
|
||||||
// fakePrinter records everything sent to it.
|
// fakePrinter records everything sent to it.
|
||||||
@@ -197,3 +201,34 @@ func waitFor(t *testing.T, cond func() bool) {
|
|||||||
}
|
}
|
||||||
t.Fatal("condition not met within 10s")
|
t.Fatal("condition not met within 10s")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// idleFailingStore is a memory store whose idle checkpoint fails.
|
||||||
|
type idleFailingStore struct{ *printqueue.MemoryStore }
|
||||||
|
|
||||||
|
func (idleFailingStore) Idle(context.Context) error { return errors.New("disk I/O error") }
|
||||||
|
|
||||||
|
// noRender and noSend stand in for the renderer and the printer of a
|
||||||
|
// queue that never prints.
|
||||||
|
type noRender struct{}
|
||||||
|
|
||||||
|
func (noRender) Render(context.Context, receipt.Job) ([]byte, error) { return nil, nil }
|
||||||
|
|
||||||
|
type noSend struct{}
|
||||||
|
|
||||||
|
func (noSend) Send(context.Context, []byte, func() error) error { return nil }
|
||||||
|
|
||||||
|
// A store error that stops the queue is logged once at ERROR and returned,
|
||||||
|
// so the daemon stops.
|
||||||
|
func TestRunQueueReportsAStoreFailureOnce(t *testing.T) {
|
||||||
|
var logs bytes.Buffer
|
||||||
|
logger := slog.New(slog.NewTextHandler(&logs, nil))
|
||||||
|
queue := printqueue.New(noRender{}, noSend{}, idleFailingStore{printqueue.NewMemoryStore()}, logger,
|
||||||
|
printqueue.Options{Size: 1})
|
||||||
|
err := runQueue(context.Background(), queue, logger)
|
||||||
|
if !errors.Is(err, printqueue.ErrStoreFailed) || !strings.Contains(err.Error(), "disk I/O error") {
|
||||||
|
t.Fatalf("runQueue = %v, want the store's error", err)
|
||||||
|
}
|
||||||
|
if n := strings.Count(logs.String(), "level=ERROR"); n != 1 || !strings.Contains(logs.String(), "print queue stopped") {
|
||||||
|
t.Errorf("log %q, want one ERROR line", logs.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -88,6 +88,10 @@ func (s *Server) submit(c fiber.Ctx, job receipt.Job, source string) error {
|
|||||||
return newAPIError(codeQueueFull)
|
return newAPIError(codeQueueFull)
|
||||||
case errors.Is(err, printqueue.ErrClosed):
|
case errors.Is(err, printqueue.ErrClosed):
|
||||||
return newAPIError(codeShuttingDown)
|
return newAPIError(codeShuttingDown)
|
||||||
|
case errors.Is(err, printqueue.ErrStoreFailed):
|
||||||
|
// The store error has stopped the queue, whose runner logs and
|
||||||
|
// reports it, once; the request only answers it.
|
||||||
|
return newAPIError(codeInternal)
|
||||||
case err != nil:
|
case err != nil:
|
||||||
return fmt.Errorf("submitting job: %w", err)
|
return fmt.Errorf("submitting job: %w", err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -582,6 +582,30 @@ func TestPrintQueueRefusals(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// A job the store could not take answers internal_error without being
|
||||||
|
// logged or reported here: the store error stopped the queue, whose
|
||||||
|
// runner reports it once.
|
||||||
|
func TestStoreFailureInSubmitIsLeftToTheQueue(t *testing.T) {
|
||||||
|
events := captureSentryEvents(t)
|
||||||
|
err := fmt.Errorf("%w: storing job: disk I/O error", printqueue.ErrStoreFailed)
|
||||||
|
s, logs := newLoggedServer(t, &fakeJobs{submitErr: err}, &fakePrinter{})
|
||||||
|
resp, body := send(t, s, printRequest(t, validJob, "Bearer "+validToken(t)))
|
||||||
|
expectError(t, resp, body, http.StatusInternalServerError, "internal_error")
|
||||||
|
if bytes.Contains(body, []byte("disk")) {
|
||||||
|
t.Errorf("body %s repeats the store's error", body)
|
||||||
|
}
|
||||||
|
lines := logs.lines(t)
|
||||||
|
if failures := errorLines(lines); len(failures) != 0 {
|
||||||
|
t.Errorf("error lines = %v, want none", failures)
|
||||||
|
}
|
||||||
|
if requests := linesAt(lines, slog.LevelWarn.String(), "request"); len(requests) != 1 {
|
||||||
|
t.Errorf("request lines = %v, want one warning", linesAt(lines, "", "request"))
|
||||||
|
}
|
||||||
|
if n := events.count(); n != 0 {
|
||||||
|
t.Errorf("%d Sentry events, want none", n)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestJobStatus(t *testing.T) {
|
func TestJobStatus(t *testing.T) {
|
||||||
id := newJobID(t)
|
id := newJobID(t)
|
||||||
jobs := &fakeJobs{statuses: map[printqueue.JobID]printqueue.Status{
|
jobs := &fakeJobs{statuses: map[printqueue.JobID]printqueue.Status{
|
||||||
|
|||||||
@@ -27,6 +27,10 @@ var (
|
|||||||
// ErrClosed is returned by Submit once the queue has shut down.
|
// ErrClosed is returned by Submit once the queue has shut down.
|
||||||
ErrClosed = errors.New("print queue is 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 is returned by Status for unknown or expired job IDs.
|
||||||
ErrNotFound = errors.New("job not found")
|
ErrNotFound = errors.New("job not found")
|
||||||
|
|
||||||
@@ -152,8 +156,8 @@ type delivery struct {
|
|||||||
//
|
//
|
||||||
// Every change to a job is committed to the store first and made in
|
// 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
|
// 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,
|
// error stops the queue: Submit then answers ErrClosed, and Run returns
|
||||||
// which then ends.
|
// the error.
|
||||||
type Queue struct {
|
type Queue struct {
|
||||||
renderer Renderer
|
renderer Renderer
|
||||||
sender Sender
|
sender Sender
|
||||||
@@ -176,8 +180,10 @@ type Queue struct {
|
|||||||
waiting []*delivery // in submission order
|
waiting []*delivery // in submission order
|
||||||
finished []*entry // oldest first, for history eviction
|
finished []*entry // oldest first, for history eviction
|
||||||
closed bool
|
closed bool
|
||||||
|
failure error // the store error that stopped the queue
|
||||||
|
|
||||||
// wake tells the worker that a delivery is waiting.
|
// wake tells the worker that a delivery is waiting or the queue
|
||||||
|
// stopped.
|
||||||
wake chan struct{}
|
wake chan struct{}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -208,8 +214,8 @@ func New(renderer Renderer, sender Sender, store Store, logger *slog.Logger, opt
|
|||||||
// Submit queues job, sent from where meta says. The job should already be
|
// Submit queues job, sent from where meta says. The job should already be
|
||||||
// validated so callers can report problems synchronously; it is validated
|
// validated so callers can report problems synchronously; it is validated
|
||||||
// again when rendered. The job is stored before Submit returns, whatever
|
// again when rendered. The job is stored before Submit returns, whatever
|
||||||
// happens to the caller meanwhile. A store error is returned, and the job
|
// happens to the caller meanwhile. A store error stops the queue and is
|
||||||
// is not queued.
|
// returned, marked as ErrStoreFailed.
|
||||||
func (q *Queue) Submit(job receipt.Job, meta Meta) (Status, error) {
|
func (q *Queue) Submit(job receipt.Job, meta Meta) (Status, error) {
|
||||||
id, err := typeid.New[JobID]()
|
id, err := typeid.New[JobID]()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -238,7 +244,7 @@ func (q *Queue) Submit(job receipt.Job, meta Meta) (Status, error) {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
if err := q.store.Add(context.Background(), rec, content, false); err != nil {
|
if err := q.store.Add(context.Background(), rec, content, false); err != nil {
|
||||||
return Status{}, fmt.Errorf("storing job %s: %w", id, err)
|
return Status{}, q.stop(fmt.Errorf("storing job %s: %w", id, err))
|
||||||
}
|
}
|
||||||
rec.Size = int64(len(content))
|
rec.Size = int64(len(content))
|
||||||
|
|
||||||
@@ -296,7 +302,7 @@ func (q *Queue) Pending() int {
|
|||||||
|
|
||||||
// Run prints jobs until ctx is cancelled. A job that is printing when ctx is
|
// 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
|
// cancelled is finished; jobs still waiting are marked failed. Run returns
|
||||||
// nil then, or a store error, which ends it.
|
// nil then, or the store error that stopped the queue.
|
||||||
func (q *Queue) Run(ctx context.Context) error {
|
func (q *Queue) Run(ctx context.Context) error {
|
||||||
for {
|
for {
|
||||||
d, err := q.next(ctx)
|
d, err := q.next(ctx)
|
||||||
@@ -307,18 +313,23 @@ func (q *Queue) Run(ctx context.Context) error {
|
|||||||
return q.shutdown(ctx)
|
return q.shutdown(ctx)
|
||||||
}
|
}
|
||||||
if err := q.process(ctx, d); err != nil {
|
if err := q.process(ctx, d); err != nil {
|
||||||
return err
|
return q.stop(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// next waits for a delivery and takes it. It returns nil once ctx is
|
// 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.
|
// 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) {
|
func (q *Queue) next(ctx context.Context) (*delivery, error) {
|
||||||
idle := false
|
idle := false
|
||||||
for {
|
for {
|
||||||
q.mu.Lock()
|
q.mu.Lock()
|
||||||
switch {
|
switch {
|
||||||
|
case q.failure != nil:
|
||||||
|
err := q.failure
|
||||||
|
q.mu.Unlock()
|
||||||
|
return nil, err
|
||||||
case ctx.Err() != nil:
|
case ctx.Err() != nil:
|
||||||
q.mu.Unlock()
|
q.mu.Unlock()
|
||||||
return nil, nil
|
return nil, nil
|
||||||
@@ -333,8 +344,11 @@ func (q *Queue) next(ctx context.Context) (*delivery, error) {
|
|||||||
q.mu.Unlock()
|
q.mu.Unlock()
|
||||||
if !idle {
|
if !idle {
|
||||||
idle = true
|
idle = true
|
||||||
|
if err := q.stopped(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
if err := q.store.Idle(context.WithoutCancel(ctx)); err != nil {
|
if err := q.store.Idle(context.WithoutCancel(ctx)); err != nil {
|
||||||
return nil, fmt.Errorf("job store while idle: %w", err)
|
return nil, q.stop(fmt.Errorf("job store while idle: %w", err))
|
||||||
}
|
}
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@@ -362,6 +376,7 @@ func (q *Queue) process(ctx context.Context, d *delivery) error {
|
|||||||
case errors.Is(err, ErrContentGone):
|
case errors.Is(err, ErrContentGone):
|
||||||
return q.fail(storeCtx, d, 0, err, logger)
|
return q.fail(storeCtx, d, 0, err, logger)
|
||||||
case err != nil:
|
case err != nil:
|
||||||
|
q.release(d)
|
||||||
return fmt.Errorf("reading job %s: %w", rec.ID, err)
|
return fmt.Errorf("reading job %s: %w", rec.ID, err)
|
||||||
}
|
}
|
||||||
job, err := receipt.DecodeJob(content)
|
job, err := receipt.DecodeJob(content)
|
||||||
@@ -371,10 +386,11 @@ func (q *Queue) process(ctx context.Context, d *delivery) error {
|
|||||||
|
|
||||||
logger.Info("printing job", "elements", len(job.Elements), "copies", max(job.Copies, 1))
|
logger.Info("printing job", "elements", len(job.Elements), "copies", max(job.Copies, 1))
|
||||||
attempts, err, storeErr := q.print(ctx, jobCtx, d, job, logger)
|
attempts, err, storeErr := q.print(ctx, jobCtx, d, job, logger)
|
||||||
|
if storeErr == nil {
|
||||||
|
storeErr = q.stopped()
|
||||||
|
}
|
||||||
if storeErr != nil {
|
if storeErr != nil {
|
||||||
q.mu.Lock()
|
q.release(d)
|
||||||
d.taken = false
|
|
||||||
q.mu.Unlock()
|
|
||||||
return storeErr
|
return storeErr
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -387,6 +403,29 @@ func (q *Queue) process(ctx context.Context, d *delivery) error {
|
|||||||
return nil
|
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{}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// fail records d as failed after attempts, logs it and reports it.
|
// 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 {
|
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 {
|
if err := q.finish(ctx, d, attempts, cause); err != nil {
|
||||||
@@ -414,6 +453,9 @@ func (q *Queue) print(runCtx, jobCtx context.Context, d *delivery, job receipt.J
|
|||||||
delay := q.options.RetryDelay
|
delay := q.options.RetryDelay
|
||||||
for attempt := 1; ; attempt++ {
|
for attempt := 1; ; attempt++ {
|
||||||
err := q.sender.Send(jobCtx, data, func() error {
|
err := q.sender.Send(jobCtx, data, func() error {
|
||||||
|
if storeErr = q.stopped(); storeErr != nil {
|
||||||
|
return storeErr
|
||||||
|
}
|
||||||
storeErr = q.sending(storeCtx, d, attempt)
|
storeErr = q.sending(storeCtx, d, attempt)
|
||||||
return storeErr
|
return storeErr
|
||||||
})
|
})
|
||||||
@@ -459,8 +501,13 @@ func (q *Queue) sending(ctx context.Context, d *delivery, attempt int) error {
|
|||||||
// finish records d as done after attempts, or as failed with cause, and
|
// 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
|
// 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
|
// is synced, since a failed job rolled back to queued would print after a
|
||||||
// restart.
|
// restart. Once a store error has stopped the queue it writes nothing and
|
||||||
|
// returns that error.
|
||||||
func (q *Queue) finish(ctx context.Context, d *delivery, attempts int, cause error) error {
|
func (q *Queue) finish(ctx context.Context, d *delivery, attempts int, cause error) error {
|
||||||
|
if err := q.stopped(); err != nil {
|
||||||
|
q.release(d)
|
||||||
|
return err
|
||||||
|
}
|
||||||
q.mu.Lock()
|
q.mu.Lock()
|
||||||
next := d.Delivery
|
next := d.Delivery
|
||||||
q.mu.Unlock()
|
q.mu.Unlock()
|
||||||
@@ -475,6 +522,7 @@ func (q *Queue) finish(ctx context.Context, d *delivery, attempts int, cause err
|
|||||||
q.mu.Unlock()
|
q.mu.Unlock()
|
||||||
|
|
||||||
if err := q.store.Finish(ctx, next, prune, next.State == StoredFailed); err != nil {
|
if err := q.store.Finish(ctx, next, prune, next.State == StoredFailed); err != nil {
|
||||||
|
q.release(d)
|
||||||
return fmt.Errorf("recording job %s as %s: %w", d.job.rec.ID, next.State, err)
|
return fmt.Errorf("recording job %s as %s: %w", d.job.rec.ID, next.State, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -533,6 +581,24 @@ func (q *Queue) retention(e *entry, finishing bool) (Prune, []*entry) {
|
|||||||
return p, drop
|
return p, drop
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 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.signal()
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
// signal wakes the worker, if it waits.
|
// signal wakes the worker, if it waits.
|
||||||
func (q *Queue) signal() {
|
func (q *Queue) signal() {
|
||||||
select {
|
select {
|
||||||
@@ -542,7 +608,8 @@ func (q *Queue) signal() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// shutdown stops accepting jobs and fails those still waiting. It returns
|
// shutdown stops accepting jobs and fails those still waiting. It returns
|
||||||
// a store error, if recording a failure met one.
|
// 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 {
|
func (q *Queue) shutdown(ctx context.Context) error {
|
||||||
q.submitMu.Lock()
|
q.submitMu.Lock()
|
||||||
q.mu.Lock()
|
q.mu.Lock()
|
||||||
@@ -555,10 +622,10 @@ func (q *Queue) shutdown(ctx context.Context) error {
|
|||||||
storeCtx := context.WithoutCancel(ctx)
|
storeCtx := context.WithoutCancel(ctx)
|
||||||
for _, d := range waiting {
|
for _, d := range waiting {
|
||||||
if err := q.finish(storeCtx, d, 0, errShuttingDown); err != nil {
|
if err := q.finish(storeCtx, d, 0, errShuttingDown); err != nil {
|
||||||
return err
|
return q.stop(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return nil
|
return q.stopped()
|
||||||
}
|
}
|
||||||
|
|
||||||
// status returns the job's status, derived from its deliveries. The
|
// status returns the job's status, derived from its deliveries. The
|
||||||
|
|||||||
@@ -260,6 +260,189 @@ func (f rendererFunc) Render(_ context.Context, job receipt.Job) ([]byte, error)
|
|||||||
return f(job)
|
return f(job)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// When Add fails, Submit returns the error, nothing is queued, the queue
|
||||||
|
// stops and Run returns the error; later jobs are refused as closed.
|
||||||
|
func TestStoreFailureOnAdd(t *testing.T) {
|
||||||
|
store := newTestStore(printqueue.NewMemoryStore())
|
||||||
|
sender := &fakeSender{}
|
||||||
|
q := newQueueOn(store, fakeRenderer{}, sender, discardLogger(), printqueue.Options{})
|
||||||
|
stop, done := runQueue(t, q)
|
||||||
|
|
||||||
|
store.failNext("add", errDisk)
|
||||||
|
if _, err := q.Submit(job("x"), printqueue.Meta{}); !errors.Is(err, errDisk) || !errors.Is(err, printqueue.ErrStoreFailed) {
|
||||||
|
t.Fatalf("Submit = %v, want the store's error marked ErrStoreFailed", err)
|
||||||
|
}
|
||||||
|
waitClosed(t, done, "Run's return")
|
||||||
|
if err := stop(); !errors.Is(err, errDisk) || !errors.Is(err, printqueue.ErrStoreFailed) {
|
||||||
|
t.Errorf("Run = %v, want the store's error marked ErrStoreFailed", err)
|
||||||
|
}
|
||||||
|
if q.Pending() != 0 || len(sender.Sent()) != 0 {
|
||||||
|
t.Errorf("pending %d, sent %v; want nothing", q.Pending(), sender.Sent())
|
||||||
|
}
|
||||||
|
if _, err := q.Submit(job("y"), printqueue.Meta{}); !errors.Is(err, printqueue.ErrClosed) {
|
||||||
|
t.Errorf("Submit after the failure = %v, want ErrClosed", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// When the sending mark fails, nothing is written, the job never reads
|
||||||
|
// failed and the queue stops.
|
||||||
|
func TestStoreFailureOnSending(t *testing.T) {
|
||||||
|
store := newTestStore(printqueue.NewMemoryStore())
|
||||||
|
sender := &fakeSender{}
|
||||||
|
q := newQueueOn(store, fakeRenderer{}, sender, discardLogger(), printqueue.Options{})
|
||||||
|
store.failNext("sending", errDisk)
|
||||||
|
st, err := q.Submit(job("x"), printqueue.Meta{})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
stop, done := runQueue(t, q)
|
||||||
|
waitClosed(t, done, "Run's return")
|
||||||
|
if err := stop(); !errors.Is(err, errDisk) || !errors.Is(err, printqueue.ErrStoreFailed) {
|
||||||
|
t.Errorf("Run = %v, want the store's error marked ErrStoreFailed", err)
|
||||||
|
}
|
||||||
|
if sent := sender.Sent(); len(sent) != 0 {
|
||||||
|
t.Errorf("sent %v after the mark failed", sent)
|
||||||
|
}
|
||||||
|
if got, _ := q.Status(st.ID); got.State != printqueue.StateQueued || got.Error != "" || got.StartedAt != nil {
|
||||||
|
t.Errorf("status %+v, want queued, as the store has it", got)
|
||||||
|
}
|
||||||
|
for _, c := range store.Commits() {
|
||||||
|
if c.op != "add" {
|
||||||
|
t.Errorf("commit %+v after the failed mark", c)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// When Finish fails, the job keeps the state the store last recorded and
|
||||||
|
// the queue stops.
|
||||||
|
func TestStoreFailureOnFinish(t *testing.T) {
|
||||||
|
store := newTestStore(printqueue.NewMemoryStore())
|
||||||
|
sender := &fakeSender{}
|
||||||
|
q := newQueueOn(store, fakeRenderer{}, sender, discardLogger(), printqueue.Options{})
|
||||||
|
store.failNext("finish", errDisk)
|
||||||
|
st, _ := q.Submit(job("x"), printqueue.Meta{})
|
||||||
|
second, _ := q.Submit(job("y"), printqueue.Meta{})
|
||||||
|
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 got, _ := q.Status(st.ID); got.State != printqueue.StatePrinting || got.FinishedAt != nil {
|
||||||
|
t.Errorf("status %+v, want printing, as the store has it", got)
|
||||||
|
}
|
||||||
|
if got, _ := q.Status(second.ID); got.State != printqueue.StateQueued {
|
||||||
|
t.Errorf("waiting job %+v, want it left queued", got)
|
||||||
|
}
|
||||||
|
if sent := sender.Sent(); !slices.Equal(sent, []string{"x"}) {
|
||||||
|
t.Errorf("sent %v, want only the first job", sent)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A failed read of a job's content or a failed Idle stops the queue too.
|
||||||
|
func TestStoreFailureOnReadOrIdle(t *testing.T) {
|
||||||
|
for _, op := range []string{"job", "idle"} {
|
||||||
|
t.Run(op, func(t *testing.T) {
|
||||||
|
store := newTestStore(printqueue.NewMemoryStore())
|
||||||
|
q := newQueueOn(store, fakeRenderer{}, &fakeSender{}, discardLogger(), printqueue.Options{})
|
||||||
|
store.failNext(op, errDisk)
|
||||||
|
var st printqueue.Status
|
||||||
|
if op == "job" {
|
||||||
|
var err error
|
||||||
|
if st, err = q.Submit(job("x"), 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 got, _ := q.Status(st.ID); op == "job" && (got.State != printqueue.StateQueued || got.StartedAt != nil) {
|
||||||
|
t.Errorf("status %+v, want queued, as the store has it", got)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Once a store error in Submit has stopped the queue, the job in hand
|
||||||
|
// writes nothing more to the store: it stays queued, as the store has it.
|
||||||
|
func TestStoreFailureLeavesTheJobInHandQueued(t *testing.T) {
|
||||||
|
store := newTestStore(printqueue.NewDurableMemoryStore())
|
||||||
|
started, release := make(chan struct{}, 1), make(chan struct{})
|
||||||
|
renderer := rendererFunc(func(j receipt.Job) ([]byte, error) {
|
||||||
|
started <- struct{}{}
|
||||||
|
<-release
|
||||||
|
return []byte(j.Elements[0].Text), nil
|
||||||
|
})
|
||||||
|
sender := &fakeSender{}
|
||||||
|
q := newQueueOn(store, renderer, sender, discardLogger(), printqueue.Options{})
|
||||||
|
first, _ := q.Submit(job("first"), printqueue.Meta{})
|
||||||
|
stop, done := runQueue(t, q)
|
||||||
|
waitClosed(t, started, "the rendering")
|
||||||
|
|
||||||
|
store.failNext("add", errDisk)
|
||||||
|
if _, err := q.Submit(job("second"), printqueue.Meta{}); !errors.Is(err, printqueue.ErrStoreFailed) {
|
||||||
|
t.Fatalf("Submit = %v, want the store's error marked ErrStoreFailed", err)
|
||||||
|
}
|
||||||
|
close(release)
|
||||||
|
waitClosed(t, done, "Run's return")
|
||||||
|
if err := stop(); !errors.Is(err, printqueue.ErrStoreFailed) {
|
||||||
|
t.Errorf("Run = %v, want the store's error marked ErrStoreFailed", err)
|
||||||
|
}
|
||||||
|
for _, c := range store.Commits() {
|
||||||
|
if c.op != "add" {
|
||||||
|
t.Errorf("commit %+v after the store failed", c)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if sent := sender.Sent(); len(sent) != 0 {
|
||||||
|
t.Errorf("sent %v after the store failed", sent)
|
||||||
|
}
|
||||||
|
if got, _ := q.Status(first.ID); got.State != printqueue.StateQueued || got.StartedAt != nil {
|
||||||
|
t.Errorf("job in hand %+v, want queued, as the store has it", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// An insert that fails while shutdown waits for it stops the queue, and
|
||||||
|
// Run returns its error, with the memory store and with a durable one.
|
||||||
|
func TestStoreFailureDuringShutdownIsReturned(t *testing.T) {
|
||||||
|
for _, tt := range []struct {
|
||||||
|
name string
|
||||||
|
store printqueue.Store
|
||||||
|
}{
|
||||||
|
{"memory store", printqueue.NewMemoryStore()},
|
||||||
|
{"durable store", printqueue.NewDurableMemoryStore()},
|
||||||
|
} {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
store := newTestStore(tt.store)
|
||||||
|
q := newQueueOn(store, fakeRenderer{}, &fakeSender{}, discardLogger(), printqueue.Options{})
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
defer cancel()
|
||||||
|
ran := make(chan error, 1)
|
||||||
|
go func() { ran <- q.Run(ctx) }()
|
||||||
|
|
||||||
|
inAdd, releaseAdd := store.blockOn("add")
|
||||||
|
defer releaseAdd()
|
||||||
|
store.failNext("add", errDisk)
|
||||||
|
submitted := make(chan error, 1)
|
||||||
|
go func() {
|
||||||
|
_, err := q.Submit(job("x"), printqueue.Meta{})
|
||||||
|
submitted <- err
|
||||||
|
}()
|
||||||
|
waitClosed(t, inAdd, "the insert")
|
||||||
|
cancel()
|
||||||
|
// The worker reaches shutdown, which waits for the insert.
|
||||||
|
time.Sleep(20 * time.Millisecond)
|
||||||
|
releaseAdd()
|
||||||
|
if err := <-submitted; !errors.Is(err, printqueue.ErrStoreFailed) {
|
||||||
|
t.Errorf("Submit = %v, want the store's error marked ErrStoreFailed", err)
|
||||||
|
}
|
||||||
|
if err := <-ran; !errors.Is(err, errDisk) || !errors.Is(err, printqueue.ErrStoreFailed) {
|
||||||
|
t.Errorf("Run = %v, want the store's error marked ErrStoreFailed", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// While a commit is held, Status and Pending still answer.
|
// While a commit is held, Status and Pending still answer.
|
||||||
func TestStatusAnswersDuringACommit(t *testing.T) {
|
func TestStatusAnswersDuringACommit(t *testing.T) {
|
||||||
store := newTestStore(printqueue.NewMemoryStore())
|
store := newTestStore(printqueue.NewMemoryStore())
|
||||||
@@ -356,31 +539,6 @@ func TestHistoryPrunesTheStore(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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.
|
// waitFor polls cond until it holds.
|
||||||
func waitFor(t *testing.T, cond func() bool) {
|
func waitFor(t *testing.T, cond func() bool) {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
|
|||||||
Reference in new issue
Block a user