feat(cronevents): adapt the events bus to scheduling.Sink

A scheduled run has no task, no chat turn and no workflow behind it, so its
emitted events are the only trace it leaves -- and the engine's Sink is the
emitter shape of a bus it deliberately does not import. Something has to turn
one into the other; this is that seam.

  - Sink(mode, bus) returns a sink over the bus for "bus", and nil for
    "none"/absent or a nil bus. Nil rather than a no-op sink keeps
    "emission is off" visible to whoever reads the composition, and it is
    the configuration the engine documents as valid: it still runs, it is
    just unobservable.
  - The published event carries the engine's own Kind/Detail/Data and no
    task-scoped identity. A cron run has none, and borrowing the emitting
    daemon's would attach it to an unrelated task's timeline.
  - An unrecognised mode is an error; the loader rejects it first, but a
    hand-built config must not silently disable observability.

TDD: the sink tests were written first and failed on assertions (Sink("bus")
returned nil; an unknown mode was accepted), not on compilation. The
end-to-end test drives a real engine on an injected clock and subscribes to
the bus, so the Emit -> Publish path is proven rather than assumed -- no
sleeps, no wall-clock deadlines.
This commit is contained in:
sam committed 2026-09-14 10:51:47 +00:00
1 parent 4d838b9fb1
commit a2cca6088e
3 files changed
+254

No files matched your search

@@ -0,0 +1,84 @@
package cronevents
import (
"context"
"testing"
"time"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/domain/scheduling"
"github.com/samcharles93/archie-core/internal/events"
)
// chanClock is a deterministic scheduling.Clock: one tick per value sent on
// ch, so the test drives the engine instead of waiting on wall-clock time.
// After returns the same channel every time, and the engine re-arms only when
// it is called again -- so nothing fires unless the test says so.
type chanClock struct{ ch chan time.Time }
func (c chanClock) Now() time.Time { return time.Time{} }
func (c chanClock) After(time.Duration) <-chan time.Time { return c.ch }
// staticSource reports the same due jobs on every tick.
type staticSource []scheduling.Job
func (s staticSource) Due(context.Context, time.Time) ([]scheduling.Job, error) { return s, nil }
type okRunner struct{}
func (okRunner) Run(context.Context, scheduling.Job) error { return nil }
// TestEngineSinkPublishesRealRunOnTheBus is the end-to-end proof of the
// adapter: the engine's own emission, over the bus, as an event the
// dashboard's timeline can read. It runs a real engine on a driven clock --
// no sleeps, no wall-clock deadlines -- so the only thing under test is the
// wiring between Emit and Publish.
func TestEngineSinkPublishesRealRunOnTheBus(t *testing.T) {
bus := events.NewBus()
t.Cleanup(bus.Close)
sub := bus.Subscribe(4)
sink, err := Sink(config.EventsSinkBus, bus)
if err != nil {
t.Fatalf("Sink(%q, bus) = %v, want nil", config.EventsSinkBus, err)
}
clock := chanClock{ch: make(chan time.Time, 1)}
engine, err := scheduling.NewEngine(
staticSource{{ID: "daily", Pool: scheduling.PoolParallel, Detail: "daily status summary"}},
okRunner{},
scheduling.EngineConfig{Interval: time.Minute, Clock: clock, Events: sink},
)
if err != nil {
t.Fatalf("NewEngine: %v", err)
}
if err := engine.Start(t.Context()); err != nil {
t.Fatalf("Start: %v", err)
}
t.Cleanup(func() {
// WithoutCancel: t.Context() is cancelled before this cleanup runs,
// and a cancelled ctx would only make Stop give up at once.
ctx, cancel := context.WithTimeout(context.WithoutCancel(t.Context()), 10*time.Second)
defer cancel()
if err := engine.Stop(ctx); err != nil {
t.Errorf("Stop: %v", err)
}
})
clock.ch <- time.Time{} // one tick
select {
case got := <-sub.C:
if got.Kind != scheduling.KindJobRun {
t.Errorf("Kind = %q, want %q", got.Kind, scheduling.KindJobRun)
}
if got.Detail != "daily status summary" {
t.Errorf("Detail = %q, want the engine's job detail", got.Detail)
}
if got.Data["job"] != "daily" {
t.Errorf("Data[job] = %v, want %q", got.Data["job"], "daily")
}
case <-time.After(10 * time.Second):
t.Fatal("no job_run event reached the bus: the engine's run is unobservable")
}
}
@@ -0,0 +1,68 @@
// Package cronevents is the observability half of archied's cron/scheduling
// capability: it adapts the daemon's in-process event bus to the ticker
// engine's narrow emission contract.
//
// The domain's engine (internal/domain/scheduling) declares what it needs --
// Emit(kind, detail, data) -- and names no bus, which is what lets its timing
// behaviour be tested without one. This package is the other side of that
// seam: the bus exists (internal/events), and something has to turn one shape
// into the other.
//
// The adapter is deliberately thin, and deliberately tolerant of a missing
// bus: a scheduled run has no task, no chat turn and no workflow behind it, so
// these events are the only trace it leaves, and the engine documents a nil
// sink as a valid configuration (it still runs, it is just unobservable).
// Which leaves the operator's choice -- publish or not -- and the daemon's
// ability to answer it, as the only two inputs.
package cronevents
import (
"fmt"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/domain/scheduling"
"github.com/samcharles93/archie-core/internal/events"
)
// Sink builds the scheduling.Sink for the configured [scheduling].events_sink
// mode, over the daemon's event bus.
//
// config.EventsSinkBus (and a non-nil bus) yields a sink that publishes each
// emitted event on the bus. "" and config.EventsSinkNone, or a nil bus,
// yield a nil sink -- the engine tolerates that by design, and returning nil
// rather than a no-op sink keeps "emission is off" visible to whoever reads
// the composition.
//
// An unrecognised mode is an error: the loader rejects such a value first, but
// a hand-built config must not silently disable observability either.
func Sink(mode string, bus *events.Bus) (scheduling.Sink, error) {
switch mode {
case "", config.EventsSinkNone:
return nil, nil
case config.EventsSinkBus:
if bus == nil {
return nil, nil
}
return busSink{bus: bus}, nil
default:
return nil, fmt.Errorf("cronevents: unknown events_sink %q (want %q or %q)",
mode, config.EventsSinkBus, config.EventsSinkNone)
}
}
// busSink publishes the engine's emission on the bus. The event carries the
// engine's own shape -- Kind, Detail and Data, exactly as emitted -- and no
// task-scoped identity, because a scheduled run has none: borrowing the
// emitting daemon's would attach a cron run's event to some unrelated task's
// timeline. Bus.Publish stamps the timestamp and fans out to bounded,
// dropping subscriber buffers, so a stalled dashboard connection cannot
// backpressure a scheduled run.
type busSink struct {
bus *events.Bus
}
func (s busSink) Emit(kind, detail string, data map[string]any) {
s.bus.Publish(events.Event{Kind: kind, Detail: detail, Data: data})
}
var _ scheduling.Sink = busSink{}
@@ -0,0 +1,102 @@
package cronevents
import (
"testing"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/domain/scheduling"
"github.com/samcharles93/archie-core/internal/events"
)
// TestSinkPublishesEmitAsJobEvent: the engine's emitted event is the only
// trace a scheduled run leaves (a job has no task, no chat turn and no
// workflow behind it), so the adapter has to carry Kind, Detail and Data
// across unchanged and must not borrow a task-scoped identity it does not
// have.
func TestSinkPublishesEmitAsJobEvent(t *testing.T) {
bus := events.NewBus()
t.Cleanup(bus.Close)
sub := bus.Subscribe(4)
sink, err := Sink(config.EventsSinkBus, bus)
if err != nil {
t.Fatalf("Sink(%q, bus) = %v, want nil", config.EventsSinkBus, err)
}
if sink == nil {
t.Fatalf("Sink(%q, bus) = nil, want a sink over the bus", config.EventsSinkBus)
}
// The shape the engine builds for a completed run
// (internal/domain/scheduling/ticker.go runJob).
sink.Emit(scheduling.KindJobRun, "nightly status", map[string]any{
"job": "nightly-status",
"pool": string(scheduling.PoolSequential),
"duration_ms": int64(12),
})
select {
case got := <-sub.C:
if got.Kind != scheduling.KindJobRun {
t.Errorf("Kind = %q, want %q", got.Kind, scheduling.KindJobRun)
}
if got.Detail != "nightly status" {
t.Errorf("Detail = %q, want unchanged \"nightly status\"", got.Detail)
}
if got.Data["job"] != "nightly-status" {
t.Errorf("Data[job] = %v, want unchanged \"nightly-status\"", got.Data["job"])
}
if got.Data["duration_ms"] != int64(12) {
t.Errorf("Data[duration_ms] = %v, want unchanged 12", got.Data["duration_ms"])
}
// The bus stamps publish time when the event carries none.
if got.At.IsZero() {
t.Error("At is zero: a timeline cannot place an event with no timestamp")
}
if got.TaskID != 0 || got.Repo != "" || got.Issue != 0 || got.Workflow != "" || got.Stage != "" {
t.Errorf("event carries task-scoped identity it has none of: %+v", got)
}
default:
t.Fatal("Emit published no event: the dashboard timeline would see nothing")
}
}
// TestSinkIsNilWhenEmissionIsOff: an absent or explicitly disabled sink must
// come back nil, which is the engine's documented "still runs, just
// unobservable" configuration.
func TestSinkIsNilWhenEmissionIsOff(t *testing.T) {
bus := events.NewBus()
t.Cleanup(bus.Close)
for _, mode := range []string{"", config.EventsSinkNone} {
sink, err := Sink(mode, bus)
if err != nil {
t.Errorf("Sink(%q, bus) = %v, want nil", mode, err)
continue
}
if sink != nil {
t.Errorf("Sink(%q, bus) = %#v, want a nil sink", mode, sink)
}
}
}
// TestSinkIsNilWithoutABus: a deployment that turned emission on still has
// nothing to publish to when the daemon has no bus, so the sink degrades to
// the engine's nil-sink tolerance rather than panicking on first emit.
func TestSinkIsNilWithoutABus(t *testing.T) {
sink, err := Sink(config.EventsSinkBus, nil)
if err != nil {
t.Fatalf("Sink(%q, nil bus) = %v, want nil", config.EventsSinkBus, err)
}
if sink != nil {
t.Errorf("Sink(%q, nil bus) = %#v, want a nil sink", config.EventsSinkBus, sink)
}
}
// TestSinkRejectsUnknownMode: unreachable through the loader, which rejects
// the value first -- but a hand-built config must not silently disable
// observability either.
func TestSinkRejectsUnknownMode(t *testing.T) {
if _, err := Sink("kafka", events.NewBus()); err == nil {
t.Fatal("Sink(\"kafka\") = nil error, want an unknown-mode failure")
}
}