feat(crondelivery): add chat, workflow and routing cron runners
The ticker engine had no work to dispatch. Add the delivery half as a new
infrastructure package with three scheduling.Runner implementations:
- ChatCourier sends a job's payload text to its target chat.
- WorkflowTask submits a job as a unit of work.
- Router dispatches on the job's kind and is the single runner the engine
is given, so the engine stays unaware that more than one delivery exists.
Nothing here talks to a channel, a broker or a forge. The outbound send is
an injected Courier function and work intake is a narrow TaskSubmitter
interface, so which transport carries a message stays the deployment's
decision rather than the cron's, and the package is testable without a
network.
An unrecognised kind is refused at the gate, not failed: it emits
KindJobError with phase "dispatch" in the engine's own data shape and
returns nil, so a misconfigured job is visible without being reported as a
job that tried and broke. A nil sink still refuses, just unobservably.
Every runner returns the context error on a cancelled run and produces no
side effect, so the engine's bounded shutdown drains rather than waiting
out the per-run timeout.
Tests exercise a real cronstore on a temp path, including the epic's
headline daily-status scenario end to end from a persisted due job through
the router to the delivered message.
This commit is contained in:
1 parent
7b13751783
commit
82b28cd7f4
6 files changed
+1215
No files matched your search
@@ -0,0 +1,86 @@
|
||||
// Package crondelivery is the delivery half of archied's cron/scheduling
|
||||
// capability: it turns a due job into an effect.
|
||||
//
|
||||
// The domain's ticker engine (internal/domain/scheduling) decides *when* a job
|
||||
// runs and hands over a scheduling.Job — identity and dispatch policy, nothing
|
||||
// more. This package owns what happens next, and it is the only place that
|
||||
// knows a job store exists. The engine sees one Runner (the Router); the
|
||||
// deliveries it dispatches to are a mapping this package holds.
|
||||
//
|
||||
// Three surfaces:
|
||||
//
|
||||
// - ChatCourier sends a job's payload text to a chat.
|
||||
// - WorkflowTask submits a job as a unit of work.
|
||||
// - Router picks between them per job kind, and is the single Runner the
|
||||
// engine is given.
|
||||
//
|
||||
// No implementation here talks to a channel, a broker or a forge. Each takes
|
||||
// the effect it needs as an injected function or narrow interface, so which
|
||||
// chat transport carries a message — and which intake path receives a task —
|
||||
// stays the deployment's decision (the wiring slice composes the real ones),
|
||||
// not the cron's. That is also what keeps this package testable without a
|
||||
// network.
|
||||
package crondelivery
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/scheduling"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/cronstore"
|
||||
)
|
||||
|
||||
// SpecLookup resolves a job id to its persisted spec.
|
||||
//
|
||||
// It is declared here (consumer-owned) rather than imported from cronstore as
|
||||
// a concrete type so this package depends on the one method it uses.
|
||||
// *cronstore.Store satisfies it as written, so a deployment passes the store
|
||||
// straight in.
|
||||
type SpecLookup interface {
|
||||
// Get returns the job and whether it was found; the error is reserved
|
||||
// for I/O failures, matching cronstore.Store.Get.
|
||||
Get(ctx context.Context, id string) (cronstore.JobSpec, bool, error)
|
||||
}
|
||||
|
||||
// Courier sends one chat message. It is the whole outbound surface this
|
||||
// package needs, and it is injected: the concrete channel client lives in the
|
||||
// deployment, so an operator switching transports changes nothing here. That
|
||||
// is how "the channel choice stays the operator's, not the cron's" is enforced
|
||||
// — by construction, there is no channel to choose from here.
|
||||
//
|
||||
// An implementation must honour ctx: the engine bounds every run with a
|
||||
// timeout and cancels on shutdown, and a courier that blocks through
|
||||
// cancellation keeps the run in flight past the engine's own deadline.
|
||||
type Courier func(ctx context.Context, chatID, text string) error
|
||||
|
||||
// TaskSubmitter submits one unit of work to the work-intake path.
|
||||
//
|
||||
// identity is the submitting job's id; title and body are the job's detail and
|
||||
// payload. It is narrow on purpose: the concrete publisher builds the
|
||||
// work-intake envelope, because the envelope carries owner/repo/number fields
|
||||
// only the deployment can know. This package carries no forge vocabulary.
|
||||
type TaskSubmitter interface {
|
||||
Submit(ctx context.Context, identity, title, body string) error
|
||||
}
|
||||
|
||||
// errSpecMissing reports a job the store does not know about. It is a run
|
||||
// failure rather than a dispatch refusal: the source reported this job due, so
|
||||
// failing to hydrate it is a real inconsistency, not a misconfiguration.
|
||||
var errSpecMissing = errors.New("crondelivery: job spec not found")
|
||||
|
||||
// hydrate loads the job's persisted spec, wrapping both a store error and the
|
||||
// not-found case so a caller can match on one sentinel.
|
||||
func hydrate(ctx context.Context, specs SpecLookup, job scheduling.Job) (cronstore.JobSpec, error) {
|
||||
spec, ok, err := specs.Get(ctx, job.ID)
|
||||
if err != nil {
|
||||
return cronstore.JobSpec{}, fmt.Errorf("crondelivery: load job %q: %w", job.ID, err)
|
||||
}
|
||||
if !ok {
|
||||
return cronstore.JobSpec{}, fmt.Errorf("%w: id %q", errSpecMissing, job.ID)
|
||||
}
|
||||
return spec, nil
|
||||
}
|
||||
|
||||
// compile-time check: the store is the lookup a deployment hands in unchanged.
|
||||
var _ SpecLookup = (*cronstore.Store)(nil)
|
||||
@@ -0,0 +1,291 @@
|
||||
// Shared fixtures for the crondelivery tests. The fakes here come in two
|
||||
// flavours, and the distinction is load-bearing: the "naive" ones ignore ctx
|
||||
// entirely, so a cancellation test built on them proves the RUNNER's own guard
|
||||
// is what suppresses the side effect, rather than the fake's good manners.
|
||||
package crondelivery
|
||||
|
||||
import (
|
||||
"context"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/scheduling"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/cronstore"
|
||||
)
|
||||
|
||||
// --- fakes --------------------------------------------------------------------
|
||||
|
||||
// naiveCourier records every call unconditionally and ignores ctx entirely. It
|
||||
// models the worst realistic transport — one that would send after shutdown —
|
||||
// so a test using it proves the RUNNER's own cancellation guard is what
|
||||
// prevents the side effect, not the fake's good manners.
|
||||
type naiveCourier struct {
|
||||
mu sync.Mutex
|
||||
calls int
|
||||
chats []string
|
||||
texts []string
|
||||
}
|
||||
|
||||
func (n *naiveCourier) send(_ context.Context, chatID, text string) error {
|
||||
n.mu.Lock()
|
||||
defer n.mu.Unlock()
|
||||
n.calls++
|
||||
n.chats = append(n.chats, chatID)
|
||||
n.texts = append(n.texts, text)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (n *naiveCourier) snapshot() (chats, texts []string, calls int) {
|
||||
n.mu.Lock()
|
||||
defer n.mu.Unlock()
|
||||
return append([]string(nil), n.chats...), append([]string(nil), n.texts...), n.calls
|
||||
}
|
||||
|
||||
// naiveSubmitter mirrors naiveCourier for the workflow path.
|
||||
type naiveSubmitter struct {
|
||||
mu sync.Mutex
|
||||
calls int
|
||||
ids []string
|
||||
}
|
||||
|
||||
func (n *naiveSubmitter) Submit(_ context.Context, identity, _, _ string) error {
|
||||
n.mu.Lock()
|
||||
defer n.mu.Unlock()
|
||||
n.calls++
|
||||
n.ids = append(n.ids, identity)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (n *naiveSubmitter) count() int {
|
||||
n.mu.Lock()
|
||||
defer n.mu.Unlock()
|
||||
return n.calls
|
||||
}
|
||||
|
||||
// naiveRunner counts calls and ignores ctx, like naiveCourier. It is what the
|
||||
// router's cancellation case forwards to, so the router's own guard is the only
|
||||
// thing that can stop the dispatch.
|
||||
type naiveRunner struct {
|
||||
mu sync.Mutex
|
||||
calls int
|
||||
}
|
||||
|
||||
func (n *naiveRunner) Run(_ context.Context, _ scheduling.Job) error {
|
||||
n.mu.Lock()
|
||||
defer n.mu.Unlock()
|
||||
n.calls++
|
||||
return nil
|
||||
}
|
||||
|
||||
func (n *naiveRunner) count() int {
|
||||
n.mu.Lock()
|
||||
defer n.mu.Unlock()
|
||||
return n.calls
|
||||
}
|
||||
|
||||
// fakeLookup serves specs from a map and ignores ctx entirely, like
|
||||
// naiveCourier.
|
||||
//
|
||||
// The cancellation tests need it because the real store is itself
|
||||
// cancellation-aware: *cronstore.Store.Get returns ctx.Err() before it reads,
|
||||
// so with a real store the runner's own guard is masked — hydrate fails and the
|
||||
// run returns the context error whether or not the runner checked. A lookup
|
||||
// that ignores ctx removes that mask, leaving the runner's guard as the only
|
||||
// thing that can prevent the side effect.
|
||||
type fakeLookup struct {
|
||||
specs map[string]cronstore.JobSpec
|
||||
}
|
||||
|
||||
func (f *fakeLookup) Get(_ context.Context, id string) (cronstore.JobSpec, bool, error) {
|
||||
spec, ok := f.specs[id]
|
||||
return spec, ok, nil
|
||||
}
|
||||
|
||||
// fakeCourier records what was sent and can be made to fail or to block until
|
||||
// cancelled.
|
||||
type fakeCourier struct {
|
||||
mu sync.Mutex
|
||||
chats []string
|
||||
texts []string
|
||||
calls int
|
||||
err error
|
||||
entered chan struct{} // closed when send is entered; nil means no signal
|
||||
blockOn chan struct{} // when non-nil, send waits on it (or ctx) before returning
|
||||
}
|
||||
|
||||
func (f *fakeCourier) send(ctx context.Context, chatID, text string) error {
|
||||
f.mu.Lock()
|
||||
f.calls++
|
||||
f.chats = append(f.chats, chatID)
|
||||
f.texts = append(f.texts, text)
|
||||
entered, block := f.entered, f.blockOn
|
||||
err := f.err
|
||||
f.mu.Unlock()
|
||||
if entered != nil {
|
||||
select {
|
||||
case <-entered:
|
||||
default:
|
||||
close(entered)
|
||||
}
|
||||
}
|
||||
if block != nil {
|
||||
select {
|
||||
case <-block:
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (f *fakeCourier) snapshot() (chats, texts []string, calls int) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
return append([]string(nil), f.chats...), append([]string(nil), f.texts...), f.calls
|
||||
}
|
||||
|
||||
// fakeSubmitter records submitted work.
|
||||
type fakeSubmitter struct {
|
||||
mu sync.Mutex
|
||||
identities []string
|
||||
titles []string
|
||||
bodies []string
|
||||
calls int
|
||||
err error
|
||||
entered chan struct{}
|
||||
block chan struct{}
|
||||
}
|
||||
|
||||
func (f *fakeSubmitter) Submit(ctx context.Context, identity, title, body string) error {
|
||||
f.mu.Lock()
|
||||
f.calls++
|
||||
f.identities = append(f.identities, identity)
|
||||
f.titles = append(f.titles, title)
|
||||
f.bodies = append(f.bodies, body)
|
||||
entered, block := f.entered, f.block
|
||||
err := f.err
|
||||
f.mu.Unlock()
|
||||
if entered != nil {
|
||||
select {
|
||||
case <-entered:
|
||||
default:
|
||||
close(entered)
|
||||
}
|
||||
}
|
||||
if block != nil {
|
||||
select {
|
||||
case <-block:
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (f *fakeSubmitter) snapshot() (ids, titles, bodies []string, calls int) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
return append([]string(nil), f.identities...),
|
||||
append([]string(nil), f.titles...),
|
||||
append([]string(nil), f.bodies...),
|
||||
f.calls
|
||||
}
|
||||
|
||||
// recordingSink captures emitted events.
|
||||
type recordingSink struct {
|
||||
mu sync.Mutex
|
||||
events []recordedEvent
|
||||
}
|
||||
|
||||
type recordedEvent struct {
|
||||
kind string
|
||||
detail string
|
||||
data map[string]any
|
||||
}
|
||||
|
||||
func (s *recordingSink) Emit(kind, detail string, data map[string]any) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.events = append(s.events, recordedEvent{kind: kind, detail: detail, data: data})
|
||||
}
|
||||
|
||||
func (s *recordingSink) all() []recordedEvent {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return append([]recordedEvent(nil), s.events...)
|
||||
}
|
||||
|
||||
// countingRunner is a stand-in runner used to prove the router did or did not
|
||||
// reach a kind's runner.
|
||||
type countingRunner struct {
|
||||
mu sync.Mutex
|
||||
calls int
|
||||
ids []string
|
||||
}
|
||||
|
||||
func (c *countingRunner) Run(_ context.Context, job scheduling.Job) error {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
c.calls++
|
||||
c.ids = append(c.ids, job.ID)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *countingRunner) count() int {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
return c.calls
|
||||
}
|
||||
|
||||
// --- helpers ------------------------------------------------------------------
|
||||
|
||||
// newStore opens a real cronstore on a temp path and closes it on cleanup.
|
||||
func newStore(t *testing.T) *cronstore.Store {
|
||||
t.Helper()
|
||||
s, err := cronstore.Open(filepath.Join(t.TempDir(), "jobs.json"))
|
||||
if err != nil {
|
||||
t.Fatalf("cronstore.Open: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = s.Close() })
|
||||
return s
|
||||
}
|
||||
|
||||
// createJob persists a spec through the real store and returns the scheduling
|
||||
// job the engine would hand a runner for it.
|
||||
func createJob(t *testing.T, s *cronstore.Store, spec cronstore.JobSpec) scheduling.Job {
|
||||
t.Helper()
|
||||
if spec.NextRun.IsZero() {
|
||||
// Due now: the engine only ever hands a runner a job its source
|
||||
// reported due, so the fixture must be in that state.
|
||||
spec.NextRun = time.Now().UTC().Add(-time.Minute)
|
||||
}
|
||||
if err := s.Create(t.Context(), spec); err != nil {
|
||||
t.Fatalf("cronstore.Create(%q): %v", spec.ID, err)
|
||||
}
|
||||
return scheduling.Job{ID: spec.ID, Pool: scheduling.Pool(spec.Pool), Detail: spec.Detail}
|
||||
}
|
||||
|
||||
// chatSpec is a minimal chat job.
|
||||
func chatSpec(id, chatID, text string) cronstore.JobSpec {
|
||||
return cronstore.JobSpec{
|
||||
ID: id,
|
||||
Detail: "test job " + id,
|
||||
Kind: cronstore.KindChat,
|
||||
Schedule: cronstore.Schedule{Kind: cronstore.ScheduleInterval, Interval: time.Hour},
|
||||
Target: cronstore.Target{ChatID: chatID},
|
||||
Payload: cronstore.Payload{Text: text},
|
||||
}
|
||||
}
|
||||
|
||||
// workflowSpec is a minimal workflow job.
|
||||
func workflowSpec(id, detail, body string) cronstore.JobSpec {
|
||||
return cronstore.JobSpec{
|
||||
ID: id,
|
||||
Detail: detail,
|
||||
Kind: cronstore.KindWorkflow,
|
||||
Schedule: cronstore.Schedule{Kind: cronstore.ScheduleInterval, Interval: time.Hour},
|
||||
Payload: cronstore.Payload{Text: body},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package crondelivery
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/scheduling"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/cronstore"
|
||||
)
|
||||
|
||||
// phaseDispatch names the step that failed on a KindJobError the Router emits.
|
||||
//
|
||||
// It is restated as a literal rather than referenced, because the engine's
|
||||
// equivalent constant is unexported (internal/domain/scheduling's
|
||||
// phaseDispatch). "dispatch" is a wire value on the event stream and this
|
||||
// package must match it, so it is pinned here by value.
|
||||
const phaseDispatch = "dispatch"
|
||||
|
||||
// Router is the single Runner the engine is given. It resolves a due job's
|
||||
// kind from its persisted spec and hands the job to that kind's runner,
|
||||
// keeping the engine unaware that more than one delivery exists.
|
||||
//
|
||||
// An unknown kind is refused, not failed. It is reported on the event stream
|
||||
// as KindJobError with phase "dispatch" — naming the gate, so an operator can
|
||||
// distinguish a misconfigured job from a broken one — and Run returns nil.
|
||||
// Returning an error instead would have the engine emit it as a failed *run*
|
||||
// (phase "run"), conflating the two, and would leave the job looking like it
|
||||
// tried and broke on every tick.
|
||||
type Router struct {
|
||||
specs SpecLookup
|
||||
runners map[string]scheduling.Runner
|
||||
sink scheduling.Sink
|
||||
}
|
||||
|
||||
// NewRouter builds the router over a spec lookup, its kind-to-runner mapping,
|
||||
// and the sink its dispatch refusals are reported on. A nil sink disables
|
||||
// emission — the router still refuses, it is just unobservable, the same
|
||||
// tolerance the engine has for its own nil sink.
|
||||
//
|
||||
// An empty kind resolves to cronstore.KindChat, so a deployment only needs a
|
||||
// mapping for the kinds it actually uses.
|
||||
func NewRouter(specs SpecLookup, runners map[string]scheduling.Runner, sink scheduling.Sink) (*Router, error) {
|
||||
if specs == nil {
|
||||
return nil, errors.New("crondelivery: spec lookup must not be nil")
|
||||
}
|
||||
if len(runners) == 0 {
|
||||
return nil, errors.New("crondelivery: at least one runner is required")
|
||||
}
|
||||
return &Router{specs: specs, runners: runners, sink: sink}, nil
|
||||
}
|
||||
|
||||
// Run implements scheduling.Runner: hydrate, resolve the kind, dispatch.
|
||||
func (r *Router) Run(ctx context.Context, job scheduling.Job) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
spec, err := hydrate(ctx, r.specs, job)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
kind := spec.Kind
|
||||
if kind == "" {
|
||||
kind = cronstore.KindChat
|
||||
}
|
||||
runner, ok := r.runners[kind]
|
||||
if !ok {
|
||||
r.refuse(job, kind)
|
||||
return nil
|
||||
}
|
||||
return runner.Run(ctx, job)
|
||||
}
|
||||
|
||||
// refuse reports a job whose kind has no runner. The data map matches the
|
||||
// engine's own error shape — {"job", "pool", "phase", "err"} — so one consumer
|
||||
// renders a dispatch refusal and a failed run without a special case, and the
|
||||
// detail is the job's human-readable label, exactly as the engine sets it.
|
||||
func (r *Router) refuse(job scheduling.Job, kind string) {
|
||||
if r.sink == nil {
|
||||
return
|
||||
}
|
||||
r.sink.Emit(events.KindJobError, job.Detail, map[string]any{
|
||||
"job": job.ID,
|
||||
"pool": string(job.Pool),
|
||||
"phase": phaseDispatch,
|
||||
// The kind is in the message, not a bare "unknown job": the
|
||||
// operator's next step is to add a runner mapping for it.
|
||||
"err": fmt.Sprintf("crondelivery: no runner registered for job kind %q",
|
||||
strings.TrimSpace(kind)),
|
||||
})
|
||||
}
|
||||
|
||||
var _ scheduling.Runner = (*Router)(nil)
|
||||
@@ -0,0 +1,363 @@
|
||||
package crondelivery
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/scheduling"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/cronstore"
|
||||
)
|
||||
|
||||
// --- Router -------------------------------------------------------------------
|
||||
|
||||
// routerFixture builds a router over a real store with counting stand-ins for
|
||||
// the per-kind runners, so a test can assert the router reached one and not
|
||||
// the other.
|
||||
func routerFixture(t *testing.T, kind string) (*Router, *countingRunner, *countingRunner, *recordingSink) {
|
||||
t.Helper()
|
||||
s := newStore(t)
|
||||
createJob(t, s, cronstore.JobSpec{
|
||||
ID: "routed",
|
||||
Detail: "routed job",
|
||||
Kind: kind,
|
||||
Schedule: cronstore.Schedule{Kind: cronstore.ScheduleInterval, Interval: time.Hour},
|
||||
})
|
||||
chat, workflow := &countingRunner{}, &countingRunner{}
|
||||
sink := &recordingSink{}
|
||||
r, err := NewRouter(s, map[string]scheduling.Runner{
|
||||
cronstore.KindChat: chat,
|
||||
cronstore.KindWorkflow: workflow,
|
||||
}, sink)
|
||||
if err != nil {
|
||||
t.Fatalf("NewRouter: %v", err)
|
||||
}
|
||||
return r, chat, workflow, sink
|
||||
}
|
||||
|
||||
func TestRouterDispatchesByKind(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
kind string
|
||||
wantChat int
|
||||
wantWorkflow int
|
||||
}{
|
||||
{"chat kind reaches the chat runner", cronstore.KindChat, 1, 0},
|
||||
{"workflow kind reaches the workflow runner", cronstore.KindWorkflow, 0, 1},
|
||||
{"empty kind defaults to the chat runner", "", 1, 0},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
r, chat, workflow, _ := routerFixture(t, tc.kind)
|
||||
job := scheduling.Job{ID: "routed"}
|
||||
|
||||
if err := r.Run(t.Context(), job); err != nil {
|
||||
t.Fatalf("Run: %v", err)
|
||||
}
|
||||
if got := chat.count(); got != tc.wantChat {
|
||||
t.Errorf("chat runner ran %d times, want %d", got, tc.wantChat)
|
||||
}
|
||||
if got := workflow.count(); got != tc.wantWorkflow {
|
||||
t.Errorf("workflow runner ran %d times, want %d", got, tc.wantWorkflow)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestRouterUnknownKindIsRefusedAtTheGate is the acceptance criterion: an
|
||||
// unrecognised kind is reported as KindJobError with phase "dispatch", reaches
|
||||
// no runner, and returns nil — a no-op refused at the gate, not a failed run
|
||||
// (which would suppress every later tick of the job).
|
||||
func TestRouterUnknownKindIsRefusedAtTheGate(t *testing.T) {
|
||||
r, chat, workflow, sink := routerFixture(t, "teleport")
|
||||
job := scheduling.Job{ID: "routed", Pool: scheduling.PoolParallel, Detail: "routed job"}
|
||||
|
||||
if err := r.Run(t.Context(), job); err != nil {
|
||||
t.Fatalf("Run on an unknown kind = %v, want nil (a refusal is not a failure)", err)
|
||||
}
|
||||
if got := chat.count(); got != 0 {
|
||||
t.Errorf("chat runner ran %d times for an unknown kind, want 0", got)
|
||||
}
|
||||
if got := workflow.count(); got != 0 {
|
||||
t.Errorf("workflow runner ran %d times for an unknown kind, want 0", got)
|
||||
}
|
||||
|
||||
emitted := sink.all()
|
||||
if len(emitted) != 1 {
|
||||
t.Fatalf("emitted %d events, want 1: %+v", len(emitted), emitted)
|
||||
}
|
||||
got := emitted[0]
|
||||
if got.kind != events.KindJobError {
|
||||
t.Errorf("event kind = %q, want %q", got.kind, events.KindJobError)
|
||||
}
|
||||
// The data map matches the engine's own error shape, so one consumer
|
||||
// can render both without a special case for the router.
|
||||
for _, key := range []string{"job", "pool", "phase", "err"} {
|
||||
if _, ok := got.data[key]; !ok {
|
||||
t.Errorf("event data is missing key %q: %+v", key, got.data)
|
||||
}
|
||||
}
|
||||
if got.data["phase"] != "dispatch" {
|
||||
t.Errorf("phase = %v, want %q", got.data["phase"], "dispatch")
|
||||
}
|
||||
if got.data["job"] != "routed" {
|
||||
t.Errorf("job = %v, want %q", got.data["job"], "routed")
|
||||
}
|
||||
if got.data["pool"] != "parallel" {
|
||||
t.Errorf("pool = %v, want %q", got.data["pool"], "parallel")
|
||||
}
|
||||
if got.data["err"] == "" || got.data["err"] == nil {
|
||||
t.Errorf("err = %v, want a message naming the unknown kind", got.data["err"])
|
||||
}
|
||||
}
|
||||
|
||||
// TestRouterNilSinkDoesNotPanicOnUnknownKind mirrors the engine's own
|
||||
// tolerance: a nil sink disables emission without disabling the refusal.
|
||||
func TestRouterNilSinkDoesNotPanicOnUnknownKind(t *testing.T) {
|
||||
s := newStore(t)
|
||||
createJob(t, s, cronstore.JobSpec{
|
||||
ID: "routed",
|
||||
Kind: "teleport",
|
||||
Schedule: cronstore.Schedule{Kind: cronstore.ScheduleInterval, Interval: time.Hour},
|
||||
})
|
||||
chat, workflow := &countingRunner{}, &countingRunner{}
|
||||
r, err := NewRouter(s, map[string]scheduling.Runner{
|
||||
cronstore.KindChat: chat,
|
||||
cronstore.KindWorkflow: workflow,
|
||||
}, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("NewRouter: %v", err)
|
||||
}
|
||||
|
||||
if err := r.Run(t.Context(), scheduling.Job{ID: "routed"}); err != nil {
|
||||
t.Fatalf("Run with a nil sink = %v, want nil", err)
|
||||
}
|
||||
if chat.count() != 0 || workflow.count() != 0 {
|
||||
t.Errorf("a runner was reached for an unknown kind: chat=%d workflow=%d",
|
||||
chat.count(), workflow.count())
|
||||
}
|
||||
}
|
||||
|
||||
func TestRouterMissingSpecReturnsError(t *testing.T) {
|
||||
s := newStore(t)
|
||||
r, err := NewRouter(s, map[string]scheduling.Runner{
|
||||
cronstore.KindChat: &countingRunner{},
|
||||
}, &recordingSink{})
|
||||
if err != nil {
|
||||
t.Fatalf("NewRouter: %v", err)
|
||||
}
|
||||
err = r.Run(t.Context(), scheduling.Job{ID: "never-created"})
|
||||
if err == nil {
|
||||
t.Fatal("Run with a missing spec returned nil, want an error")
|
||||
}
|
||||
if !errors.Is(err, errSpecMissing) {
|
||||
t.Errorf("Run = %v, want it to wrap %v", err, errSpecMissing)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRouterPassesTheEngineJobThrough pins that the router hands the runner
|
||||
// the job the engine built, not a re-derived one: identity and pool are the
|
||||
// engine's, and the runner's event attribution depends on them surviving.
|
||||
func TestRouterPassesTheEngineJobThrough(t *testing.T) {
|
||||
r, chat, _, _ := routerFixture(t, cronstore.KindChat)
|
||||
job := scheduling.Job{ID: "routed", Pool: scheduling.PoolSequential, Detail: "detail from engine"}
|
||||
|
||||
if err := r.Run(t.Context(), job); err != nil {
|
||||
t.Fatalf("Run: %v", err)
|
||||
}
|
||||
chat.mu.Lock()
|
||||
defer chat.mu.Unlock()
|
||||
if len(chat.ids) != 1 || chat.ids[0] != "routed" {
|
||||
t.Errorf("runner saw job ids %v, want [routed]", chat.ids)
|
||||
}
|
||||
}
|
||||
|
||||
// --- AC3: every runner honours cancellation ----------------------------------
|
||||
|
||||
// TestEveryRunnerHonoursCancellation covers the acceptance criterion as one
|
||||
// property over all three runners rather than three separate tests: the engine
|
||||
// hands every run a bounded context and cancels it on shutdown, so a runner
|
||||
// that ignores cancellation holds the engine past its own deadline.
|
||||
//
|
||||
// The downstream effects used here deliberately IGNORE ctx. A fake that
|
||||
// honours cancellation would make this pass whether or not the runner checks,
|
||||
// which is the failure mode the criterion exists to prevent.
|
||||
func TestEveryRunnerHonoursCancellation(t *testing.T) {
|
||||
lookup := &fakeLookup{specs: map[string]cronstore.JobSpec{
|
||||
"chat-job": chatSpec("chat-job", "ops-room", "hello"),
|
||||
"wf-job": workflowSpec("wf-job", "workflow job", "body"),
|
||||
}}
|
||||
|
||||
courier := &naiveCourier{}
|
||||
submitter := &naiveSubmitter{}
|
||||
chat, err := NewChatCourier(lookup, courier.send)
|
||||
if err != nil {
|
||||
t.Fatalf("NewChatCourier: %v", err)
|
||||
}
|
||||
workflow, err := NewWorkflowTask(lookup, submitter)
|
||||
if err != nil {
|
||||
t.Fatalf("NewWorkflowTask: %v", err)
|
||||
}
|
||||
// The router forwards to a ctx-ignoring runner, so this case pins the
|
||||
// router's own guard: a cancelled run must not reach the dispatch.
|
||||
forwarded := &naiveRunner{}
|
||||
router, err := NewRouter(lookup, map[string]scheduling.Runner{
|
||||
cronstore.KindChat: forwarded,
|
||||
cronstore.KindWorkflow: workflow,
|
||||
}, &recordingSink{})
|
||||
if err != nil {
|
||||
t.Fatalf("NewRouter: %v", err)
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
runner scheduling.Runner
|
||||
job scheduling.Job
|
||||
sideEffects func() int
|
||||
}{
|
||||
{"ChatCourier", chat, scheduling.Job{ID: "chat-job"}, func() int {
|
||||
_, _, calls := courier.snapshot()
|
||||
return calls
|
||||
}},
|
||||
{"WorkflowTask", workflow, scheduling.Job{ID: "wf-job"}, submitter.count},
|
||||
{"Router", router, scheduling.Job{ID: "chat-job"}, forwarded.count},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
cancelled, cancel := context.WithCancel(t.Context())
|
||||
cancel()
|
||||
if err := tc.runner.Run(cancelled, tc.job); !errors.Is(err, context.Canceled) {
|
||||
t.Errorf("Run on a cancelled ctx = %v, want context.Canceled", err)
|
||||
}
|
||||
if got := tc.sideEffects(); got != 0 {
|
||||
t.Errorf("a cancelled run produced %d side effect(s), want 0", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// --- AC4: the headline scenario, end to end -----------------------------------
|
||||
|
||||
// dailyStatusSummary is the hard-coded template AC4 calls for. The blueprints
|
||||
// slice replaces it with parameterisation; until then the composed message is
|
||||
// this constant, and the test asserts the delivered text against it.
|
||||
const dailyStatusSummary = "Daily status summary: all workers healthy, no tasks parked."
|
||||
|
||||
// TestDailyStatusSummaryEndToEnd is the epic's headline scenario exercised
|
||||
// through the whole chain a deployment uses: a real job persisted in a real
|
||||
// cronstore is reported due by the store's own JobSource, handed to the router
|
||||
// the engine is given, dispatched to the chat runner, and delivered as the
|
||||
// composed message.
|
||||
func TestDailyStatusSummaryEndToEnd(t *testing.T) {
|
||||
s := newStore(t)
|
||||
const chatID = "ops-room"
|
||||
|
||||
spec := cronstore.JobSpec{
|
||||
ID: "daily-status",
|
||||
Detail: "daily status summary",
|
||||
Kind: cronstore.KindChat,
|
||||
Schedule: cronstore.Schedule{Kind: cronstore.ScheduleInterval, Interval: 24 * time.Hour},
|
||||
Target: cronstore.Target{ChatID: chatID},
|
||||
Payload: cronstore.Payload{Text: dailyStatusSummary},
|
||||
// Due now: create it with a next_run in the past, the state a
|
||||
// long-idle daemon wakes up to.
|
||||
NextRun: time.Now().UTC().Add(-time.Minute),
|
||||
}
|
||||
if err := s.Create(t.Context(), spec); err != nil {
|
||||
t.Fatalf("cronstore.Create: %v", err)
|
||||
}
|
||||
|
||||
// The engine's source: the store itself, answering what is due.
|
||||
due, err := s.Due(t.Context(), time.Now().UTC())
|
||||
if err != nil {
|
||||
t.Fatalf("Due: %v", err)
|
||||
}
|
||||
if len(due) != 1 {
|
||||
t.Fatalf("Due returned %d jobs, want 1: %+v", len(due), due)
|
||||
}
|
||||
|
||||
courier := &fakeCourier{}
|
||||
courierRunner, err := NewChatCourier(s, courier.send)
|
||||
if err != nil {
|
||||
t.Fatalf("NewChatCourier: %v", err)
|
||||
}
|
||||
router, err := NewRouter(s, map[string]scheduling.Runner{
|
||||
cronstore.KindChat: courierRunner,
|
||||
}, &recordingSink{})
|
||||
if err != nil {
|
||||
t.Fatalf("NewRouter: %v", err)
|
||||
}
|
||||
|
||||
// The engine hands the router the job its source reported.
|
||||
if err := router.Run(t.Context(), due[0]); err != nil {
|
||||
t.Fatalf("router.Run: %v", err)
|
||||
}
|
||||
|
||||
chats, texts, calls := courier.snapshot()
|
||||
if calls != 1 {
|
||||
t.Fatalf("courier called %d times, want 1", calls)
|
||||
}
|
||||
if chats[0] != chatID {
|
||||
t.Errorf("delivered to %q, want %q", chats[0], chatID)
|
||||
}
|
||||
if texts[0] != dailyStatusSummary {
|
||||
t.Errorf("delivered %q, want the composed summary %q", texts[0], dailyStatusSummary)
|
||||
}
|
||||
}
|
||||
|
||||
// --- constructors -------------------------------------------------------------
|
||||
|
||||
func TestConstructorsRejectNilDependencies(t *testing.T) {
|
||||
s := newStore(t)
|
||||
courier := &fakeCourier{}
|
||||
tests := []struct {
|
||||
name string
|
||||
run func() error
|
||||
}{
|
||||
{"ChatCourier without a spec lookup", func() error {
|
||||
_, err := NewChatCourier(nil, courier.send)
|
||||
return err
|
||||
}},
|
||||
{"ChatCourier without a courier", func() error {
|
||||
_, err := NewChatCourier(s, nil)
|
||||
return err
|
||||
}},
|
||||
{"WorkflowTask without a spec lookup", func() error {
|
||||
_, err := NewWorkflowTask(nil, &fakeSubmitter{})
|
||||
return err
|
||||
}},
|
||||
{"WorkflowTask without a submitter", func() error {
|
||||
_, err := NewWorkflowTask(s, nil)
|
||||
return err
|
||||
}},
|
||||
{"Router without a spec lookup", func() error {
|
||||
_, err := NewRouter(nil, map[string]scheduling.Runner{
|
||||
cronstore.KindChat: &countingRunner{},
|
||||
}, nil)
|
||||
return err
|
||||
}},
|
||||
{"Router without any runner", func() error {
|
||||
_, err := NewRouter(s, nil, nil)
|
||||
return err
|
||||
}},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if err := tc.run(); err == nil {
|
||||
t.Error("constructor returned nil error, want a refusal")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestImplementsSchedulingRunner is the compile-time contract check the engine
|
||||
// depends on.
|
||||
func TestImplementsSchedulingRunner(t *testing.T) {
|
||||
var (
|
||||
_ scheduling.Runner = (*ChatCourier)(nil)
|
||||
_ scheduling.Runner = (*WorkflowTask)(nil)
|
||||
_ scheduling.Runner = (*Router)(nil)
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package crondelivery
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/scheduling"
|
||||
)
|
||||
|
||||
// ChatCourier delivers a job's payload text to a chat. It is the runner behind
|
||||
// the "chat" kind and the epic's headline case: a daily status summary, which
|
||||
// the blueprints slice will parameterise.
|
||||
type ChatCourier struct {
|
||||
specs SpecLookup
|
||||
courier Courier
|
||||
}
|
||||
|
||||
// NewChatCourier builds the chat runner over a spec lookup and the courier the
|
||||
// deployment supplies.
|
||||
func NewChatCourier(specs SpecLookup, courier Courier) (*ChatCourier, error) {
|
||||
if specs == nil {
|
||||
return nil, errors.New("crondelivery: spec lookup must not be nil")
|
||||
}
|
||||
if courier == nil {
|
||||
return nil, errors.New("crondelivery: courier must not be nil")
|
||||
}
|
||||
return &ChatCourier{specs: specs, courier: courier}, nil
|
||||
}
|
||||
|
||||
// Run hydrates the job's spec and sends its payload text to its target chat.
|
||||
//
|
||||
// The pre-check matters as much as the error wrap: a cancelled run must produce
|
||||
// no side effect, because the engine cancels on shutdown and a message sent
|
||||
// after that is one nobody asked for. The courier's own ctx handling covers
|
||||
// cancellation that arrives mid-send.
|
||||
func (c *ChatCourier) Run(ctx context.Context, job scheduling.Job) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
spec, err := hydrate(ctx, c.specs, job)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := c.courier(ctx, spec.Target.ChatID, spec.Payload.Text); err != nil {
|
||||
return fmt.Errorf("crondelivery: deliver job %q to %q: %w", job.ID, spec.Target.ChatID, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// WorkflowTask submits a job as a unit of work. It is the runner behind the
|
||||
// "workflow" kind, so a scheduled job reaches the same task lifecycle —
|
||||
// scheduling, retries, gates, PR opening — that every other intake path feeds.
|
||||
type WorkflowTask struct {
|
||||
specs SpecLookup
|
||||
submitter TaskSubmitter
|
||||
}
|
||||
|
||||
// NewWorkflowTask builds the workflow runner over a spec lookup and the
|
||||
// submitter the deployment supplies.
|
||||
func NewWorkflowTask(specs SpecLookup, submitter TaskSubmitter) (*WorkflowTask, error) {
|
||||
if specs == nil {
|
||||
return nil, errors.New("crondelivery: spec lookup must not be nil")
|
||||
}
|
||||
if submitter == nil {
|
||||
return nil, errors.New("crondelivery: task submitter must not be nil")
|
||||
}
|
||||
return &WorkflowTask{specs: specs, submitter: submitter}, nil
|
||||
}
|
||||
|
||||
// Run hydrates the job's spec and submits it as work.
|
||||
//
|
||||
// The title falls back to the job id when Detail is empty: a submitted task is
|
||||
// how a human finds the job that created it, and an untitled one is
|
||||
// unfindable.
|
||||
func (w *WorkflowTask) Run(ctx context.Context, job scheduling.Job) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
spec, err := hydrate(ctx, w.specs, job)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
title := strings.TrimSpace(spec.Detail)
|
||||
if title == "" {
|
||||
title = job.ID
|
||||
}
|
||||
if err := w.submitter.Submit(ctx, job.ID, title, spec.Payload.Text); err != nil {
|
||||
return fmt.Errorf("crondelivery: submit job %q: %w", job.ID, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// compile-time checks: the two deliveries are the engine's contract.
|
||||
var (
|
||||
_ scheduling.Runner = (*ChatCourier)(nil)
|
||||
_ scheduling.Runner = (*WorkflowTask)(nil)
|
||||
)
|
||||
@@ -0,0 +1,280 @@
|
||||
package crondelivery
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/scheduling"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/cronstore"
|
||||
)
|
||||
|
||||
// --- ChatCourier --------------------------------------------------------------
|
||||
|
||||
func TestChatCourierSendsPayloadToTargetChat(t *testing.T) {
|
||||
s := newStore(t)
|
||||
courier := &fakeCourier{}
|
||||
runner, err := NewChatCourier(s, courier.send)
|
||||
if err != nil {
|
||||
t.Fatalf("NewChatCourier: %v", err)
|
||||
}
|
||||
job := createJob(t, s, chatSpec("standup", "ops-room", "morning"))
|
||||
|
||||
if err := runner.Run(t.Context(), job); err != nil {
|
||||
t.Fatalf("Run: %v", err)
|
||||
}
|
||||
chats, texts, calls := courier.snapshot()
|
||||
if calls != 1 {
|
||||
t.Fatalf("courier called %d times, want 1", calls)
|
||||
}
|
||||
if chats[0] != "ops-room" {
|
||||
t.Errorf("chat id = %q, want %q", chats[0], "ops-room")
|
||||
}
|
||||
if texts[0] != "morning" {
|
||||
t.Errorf("text = %q, want %q", texts[0], "morning")
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatCourierPropagatesCourierError(t *testing.T) {
|
||||
s := newStore(t)
|
||||
wantErr := errors.New("channel refused")
|
||||
courier := &fakeCourier{err: wantErr}
|
||||
runner, err := NewChatCourier(s, courier.send)
|
||||
if err != nil {
|
||||
t.Fatalf("NewChatCourier: %v", err)
|
||||
}
|
||||
job := createJob(t, s, chatSpec("boom", "ops-room", "morning"))
|
||||
|
||||
err = runner.Run(t.Context(), job)
|
||||
if !errors.Is(err, wantErr) {
|
||||
t.Errorf("Run = %v, want it to wrap %v", err, wantErr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatCourierMissingSpecReturnsError(t *testing.T) {
|
||||
s := newStore(t)
|
||||
courier := &fakeCourier{}
|
||||
runner, err := NewChatCourier(s, courier.send)
|
||||
if err != nil {
|
||||
t.Fatalf("NewChatCourier: %v", err)
|
||||
}
|
||||
|
||||
// The engine reported this id due; the store does not have it. That is
|
||||
// a real inconsistency, so it must surface rather than be swallowed.
|
||||
err = runner.Run(t.Context(), scheduling.Job{ID: "never-created"})
|
||||
if err == nil {
|
||||
t.Fatal("Run with a missing spec returned nil, want an error")
|
||||
}
|
||||
if _, _, calls := courier.snapshot(); calls != 0 {
|
||||
t.Errorf("courier was called %d times for a missing spec, want 0", calls)
|
||||
}
|
||||
}
|
||||
|
||||
// TestChatCourierHonoursCancellation is the bounded-shutdown property the
|
||||
// engine relies on: it cancels a run on Stop, and a runner that blocks through
|
||||
// cancellation keeps the run in flight past the engine's own deadline.
|
||||
//
|
||||
// Two cases, because they exercise different code paths: a run started with an
|
||||
// already-cancelled context must produce no side effect at all, and a run
|
||||
// cancelled while the courier is mid-send must return the context error so the
|
||||
// engine's shutdown completes rather than waiting for a full timeout.
|
||||
func TestChatCourierHonoursCancellation(t *testing.T) {
|
||||
t.Run("cancelled before the run sends nothing", func(t *testing.T) {
|
||||
// Both the lookup and the courier ignore ctx, so only the
|
||||
// runner's own guard can stop the send.
|
||||
lookup := &fakeLookup{specs: map[string]cronstore.JobSpec{
|
||||
"cancel-me": chatSpec("cancel-me", "ops-room", "morning"),
|
||||
}}
|
||||
courier := &naiveCourier{}
|
||||
runner, err := NewChatCourier(lookup, courier.send)
|
||||
if err != nil {
|
||||
t.Fatalf("NewChatCourier: %v", err)
|
||||
}
|
||||
|
||||
cancelled, cancel := context.WithCancel(t.Context())
|
||||
cancel()
|
||||
err = runner.Run(cancelled, scheduling.Job{ID: "cancel-me"})
|
||||
if !errors.Is(err, context.Canceled) {
|
||||
t.Errorf("Run on a cancelled ctx = %v, want context.Canceled", err)
|
||||
}
|
||||
if _, _, calls := courier.snapshot(); calls != 0 {
|
||||
t.Errorf("courier was called %d times on a cancelled ctx, want 0", calls)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("cancelled mid-send returns the context error", func(t *testing.T) {
|
||||
s := newStore(t)
|
||||
entered := make(chan struct{})
|
||||
never := make(chan struct{})
|
||||
defer close(never) // never released; only cancellation can unblock
|
||||
courier := &fakeCourier{entered: entered, blockOn: never}
|
||||
runner, err := NewChatCourier(s, courier.send)
|
||||
if err != nil {
|
||||
t.Fatalf("NewChatCourier: %v", err)
|
||||
}
|
||||
job := createJob(t, s, chatSpec("cancel-mid", "ops-room", "morning"))
|
||||
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- runner.Run(ctx, job) }()
|
||||
|
||||
select {
|
||||
case <-entered:
|
||||
case <-time.After(5 * time.Second):
|
||||
cancel()
|
||||
t.Fatal("courier was never entered; Run did not reach the send")
|
||||
}
|
||||
cancel()
|
||||
|
||||
select {
|
||||
case err := <-done:
|
||||
if !errors.Is(err, context.Canceled) {
|
||||
t.Errorf("Run cancelled mid-send = %v, want context.Canceled", err)
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("Run did not return after cancellation; it ignored ctx.Done()")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// --- WorkflowTask -------------------------------------------------------------
|
||||
|
||||
func TestWorkflowTaskSubmitsIdentityTitleAndBody(t *testing.T) {
|
||||
s := newStore(t)
|
||||
sub := &fakeSubmitter{}
|
||||
runner, err := NewWorkflowTask(s, sub)
|
||||
if err != nil {
|
||||
t.Fatalf("NewWorkflowTask: %v", err)
|
||||
}
|
||||
job := createJob(t, s, workflowSpec("nightly", "nightly maintenance", "run the sweep"))
|
||||
|
||||
if err := runner.Run(t.Context(), job); err != nil {
|
||||
t.Fatalf("Run: %v", err)
|
||||
}
|
||||
ids, titles, bodies, calls := sub.snapshot()
|
||||
if calls != 1 {
|
||||
t.Fatalf("submitter called %d times, want 1", calls)
|
||||
}
|
||||
if ids[0] != "nightly" {
|
||||
t.Errorf("identity = %q, want the job id %q", ids[0], "nightly")
|
||||
}
|
||||
if titles[0] != "nightly maintenance" {
|
||||
t.Errorf("title = %q, want %q", titles[0], "nightly maintenance")
|
||||
}
|
||||
if bodies[0] != "run the sweep" {
|
||||
t.Errorf("body = %q, want %q", bodies[0], "run the sweep")
|
||||
}
|
||||
}
|
||||
|
||||
// TestWorkflowTaskFallsBackToJobIDForTitle pins the documented fallback: a job
|
||||
// with no Detail still submits under a nameable title rather than an empty one.
|
||||
func TestWorkflowTaskFallsBackToJobIDForTitle(t *testing.T) {
|
||||
s := newStore(t)
|
||||
sub := &fakeSubmitter{}
|
||||
runner, err := NewWorkflowTask(s, sub)
|
||||
if err != nil {
|
||||
t.Fatalf("NewWorkflowTask: %v", err)
|
||||
}
|
||||
spec := workflowSpec("untitled", "", "body")
|
||||
job := createJob(t, s, spec)
|
||||
|
||||
if err := runner.Run(t.Context(), job); err != nil {
|
||||
t.Fatalf("Run: %v", err)
|
||||
}
|
||||
_, titles, _, _ := sub.snapshot()
|
||||
if titles[0] != "untitled" {
|
||||
t.Errorf("title = %q, want the job id %q when Detail is empty", titles[0], "untitled")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkflowTaskMissingSpecReturnsError(t *testing.T) {
|
||||
s := newStore(t)
|
||||
sub := &fakeSubmitter{}
|
||||
runner, err := NewWorkflowTask(s, sub)
|
||||
if err != nil {
|
||||
t.Fatalf("NewWorkflowTask: %v", err)
|
||||
}
|
||||
err = runner.Run(t.Context(), scheduling.Job{ID: "never-created"})
|
||||
if err == nil {
|
||||
t.Fatal("Run with a missing spec returned nil, want an error")
|
||||
}
|
||||
if _, _, _, calls := sub.snapshot(); calls != 0 {
|
||||
t.Errorf("submitter was called %d times for a missing spec, want 0", calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkflowTaskPropagatesSubmitError(t *testing.T) {
|
||||
s := newStore(t)
|
||||
wantErr := errors.New("intake unavailable")
|
||||
sub := &fakeSubmitter{err: wantErr}
|
||||
runner, err := NewWorkflowTask(s, sub)
|
||||
if err != nil {
|
||||
t.Fatalf("NewWorkflowTask: %v", err)
|
||||
}
|
||||
job := createJob(t, s, workflowSpec("nightly", "nightly maintenance", "run"))
|
||||
|
||||
err = runner.Run(t.Context(), job)
|
||||
if !errors.Is(err, wantErr) {
|
||||
t.Errorf("Run = %v, want it to wrap %v", err, wantErr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkflowTaskHonoursCancellation(t *testing.T) {
|
||||
t.Run("cancelled before the run submits nothing", func(t *testing.T) {
|
||||
// Both the lookup and the submitter ignore ctx, so only the
|
||||
// runner's own guard can stop the submit.
|
||||
lookup := &fakeLookup{specs: map[string]cronstore.JobSpec{
|
||||
"cancel-me": workflowSpec("cancel-me", "cancel me", "body"),
|
||||
}}
|
||||
sub := &naiveSubmitter{}
|
||||
runner, err := NewWorkflowTask(lookup, sub)
|
||||
if err != nil {
|
||||
t.Fatalf("NewWorkflowTask: %v", err)
|
||||
}
|
||||
|
||||
cancelled, cancel := context.WithCancel(t.Context())
|
||||
cancel()
|
||||
err = runner.Run(cancelled, scheduling.Job{ID: "cancel-me"})
|
||||
if !errors.Is(err, context.Canceled) {
|
||||
t.Errorf("Run on a cancelled ctx = %v, want context.Canceled", err)
|
||||
}
|
||||
if calls := sub.count(); calls != 0 {
|
||||
t.Errorf("submitter was called %d times on a cancelled ctx, want 0", calls)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("cancelled mid-submit returns the context error", func(t *testing.T) {
|
||||
s := newStore(t)
|
||||
entered := make(chan struct{})
|
||||
never := make(chan struct{})
|
||||
defer close(never)
|
||||
sub := &fakeSubmitter{entered: entered, block: never}
|
||||
runner, err := NewWorkflowTask(s, sub)
|
||||
if err != nil {
|
||||
t.Fatalf("NewWorkflowTask: %v", err)
|
||||
}
|
||||
job := createJob(t, s, workflowSpec("cancel-mid", "cancel me", "body"))
|
||||
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- runner.Run(ctx, job) }()
|
||||
|
||||
select {
|
||||
case <-entered:
|
||||
case <-time.After(5 * time.Second):
|
||||
cancel()
|
||||
t.Fatal("submitter was never entered; Run did not reach the submit")
|
||||
}
|
||||
cancel()
|
||||
|
||||
select {
|
||||
case err := <-done:
|
||||
if !errors.Is(err, context.Canceled) {
|
||||
t.Errorf("Run cancelled mid-submit = %v, want context.Canceled", err)
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("Run did not return after cancellation; it ignored ctx.Done()")
|
||||
}
|
||||
})
|
||||
}
|
||||
Reference in new issue
Block a user