feat(memory): typed memory engine contract, registry, and registrar
Part of archie-core-1786637490069-11-e245c170 (memory engine contract and owning registry), under epic archie-core-1786637499161 (pluggable memory engine). Stands up internal/domain/memory as a conforming engine family per the strict plugin engine rule, mirroring internal/domain/curator's split exactly as that issue's notes specify: - contract.go: MemoryEngine (Lifecycle + Store + identity + Bind), with Store carrying the real domain operations the epic requires -- Write/Query/List/Forget -- not just Name/Version. Store is split out from MemoryEngine so the interface stays under golangci-lint's interfacebloat threshold the same way curator's embedded Lifecycle does: an embedded interface counts as one slot, not its expanded method count. - registrar.go: narrow typed host access (EventSink, Clock). No capability-gated fields yet -- unlike curator's Tools/Skills, no memory-specific host service exists to gate on today, so Registry.Bind passes the host straight through rather than filtering. - registry.go: Register/Get/Names/Start/Health/Stop with the same duplicate/nil/panic/failure-isolation guarantees as curator's registry, ctx-bounded Stop, reverse-order shutdown. This is the contract only -- no engine implements it yet, and internal/memory's existing ad-hoc MemoryProvider/Manager (pre-migration) is untouched, per the issue's explicit "do not extend in place" note.
This commit is contained in:
1 parent
14cb5c6888
commit
4a85725a69
5 files changed
+865
No files matched your search
@@ -0,0 +1,156 @@
|
||||
// Package memory is the memory engine family: a pluggable backend for
|
||||
// durable observations about a session or identity, so an external memory
|
||||
// service (Honcho, or a future alternative) can be bolted on without
|
||||
// touching the agent loop. See epic archie-core-1786637499161-356-e424e40d.
|
||||
//
|
||||
// The family follows the strict plugin engine rule: a typed contract
|
||||
// (MemoryEngine) with real domain operations (write, query, list, forget —
|
||||
// not just Name/Version), an owning registry (Registry) with
|
||||
// start/health/stop and shutdown ordering, and narrow typed host access
|
||||
// (Registrar) — an engine never receives the daemon or an untyped hook map.
|
||||
//
|
||||
// This package defines the contract only. internal/memory's existing
|
||||
// MemoryProvider and Manager predate the domain migration and are the
|
||||
// current runtime path; they are not extended in place (see
|
||||
// archie-core-1786637490069-11-e245c170's notes) and are superseded by this
|
||||
// family as engines land against it.
|
||||
package memory
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
)
|
||||
|
||||
// HealthStatus is an engine's point-in-time health.
|
||||
type HealthStatus string
|
||||
|
||||
const (
|
||||
HealthHealthy HealthStatus = "healthy"
|
||||
HealthDegraded HealthStatus = "degraded"
|
||||
HealthUnhealthy HealthStatus = "unhealthy"
|
||||
)
|
||||
|
||||
// Health is a point-in-time engine health report.
|
||||
type Health struct {
|
||||
Status HealthStatus
|
||||
Message string
|
||||
}
|
||||
|
||||
// Manifest is an engine's declared shape. RequiresNetwork marks an engine
|
||||
// that calls an external service, so a caller can size timeouts and
|
||||
// failure-isolation expectations accordingly: a non-default engine's
|
||||
// failure must degrade to a reported error, never take down a turn.
|
||||
type Manifest struct {
|
||||
RequiresNetwork bool
|
||||
}
|
||||
|
||||
// Validate checks the declared shape. It is called by the registry at
|
||||
// registration; present for symmetry with the curator family and as the
|
||||
// seam for future required fields, even though no field is required yet.
|
||||
func (m Manifest) Validate() error { return nil }
|
||||
|
||||
// Lifecycle is the start/health/stop contract every engine implements. The
|
||||
// registry drives it with shutdown ordering and failure isolation; an
|
||||
// engine's Health must never panic the daemon.
|
||||
type Lifecycle interface {
|
||||
Start(ctx context.Context) error
|
||||
Health(ctx context.Context) Health
|
||||
Stop(ctx context.Context) error
|
||||
}
|
||||
|
||||
// Store is the real domain operations every memory backend implements —
|
||||
// what the epic requires beyond identity metadata. Split out from
|
||||
// MemoryEngine so the two concerns (storage vs. identity/lifecycle) stay
|
||||
// separately named and independently testable.
|
||||
type Store interface {
|
||||
// Write records one observation and returns the stored Record,
|
||||
// including the identifier Forget later needs.
|
||||
Write(ctx context.Context, obs Observation) (Record, error)
|
||||
// Query returns records relevant to q, most relevant or most recent
|
||||
// first — ordering is engine-defined and not part of this contract.
|
||||
Query(ctx context.Context, q Query) ([]Record, error)
|
||||
// List returns every record for identity, for inspection and
|
||||
// deletion flows rather than relevance-ranked recall.
|
||||
List(ctx context.Context, identity string) ([]Record, error)
|
||||
// Forget permanently removes one record. Forgetting an id that does
|
||||
// not exist is not an error: the end state (id absent) already holds.
|
||||
Forget(ctx context.Context, id string) error
|
||||
}
|
||||
|
||||
// MemoryEngine is the typed contract every memory backend implements.
|
||||
// Name/Version are identity, Manifest declares the shape, Store carries
|
||||
// the real domain operations, Bind receives narrow host access, and
|
||||
// Lifecycle carries start/health/stop.
|
||||
type MemoryEngine interface {
|
||||
Lifecycle
|
||||
Store
|
||||
Name() string
|
||||
Version() string
|
||||
Manifest() Manifest
|
||||
// Bind attaches the engine's narrow host access. The registry calls
|
||||
// Bind exactly once, at registration.
|
||||
Bind(host Registrar)
|
||||
}
|
||||
|
||||
// Observation is one fact to remember, submitted for writing.
|
||||
type Observation struct {
|
||||
// Identity is whose memory this is about (a session id, a user id —
|
||||
// engine-defined, but always required so Query/List/Forget have a
|
||||
// scope to operate within).
|
||||
Identity string
|
||||
// Kind is a freeform category ("preference", "fact", "correction").
|
||||
Kind string
|
||||
// Content is the observation itself.
|
||||
Content string
|
||||
// At is when the observation was made. Zero means the engine should
|
||||
// stamp it with the current time.
|
||||
At time.Time
|
||||
// Metadata carries engine-agnostic key/value context alongside the
|
||||
// observation (e.g. source, confidence).
|
||||
Metadata map[string]string
|
||||
}
|
||||
|
||||
// Validate checks the fields every engine needs regardless of backend:
|
||||
// Identity scopes every other operation, and Content is the whole point
|
||||
// of writing.
|
||||
func (o Observation) Validate() error {
|
||||
if o.Identity == "" {
|
||||
return errors.New("memory observation: identity must not be empty")
|
||||
}
|
||||
if o.Content == "" {
|
||||
return errors.New("memory observation: content must not be empty")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Query asks an engine to recall observations relevant to Text within
|
||||
// Identity's scope.
|
||||
type Query struct {
|
||||
Identity string
|
||||
Text string
|
||||
// Limit bounds the number of records returned. Zero lets the engine
|
||||
// choose a default; there is no way to request "unlimited" — List
|
||||
// exists for that.
|
||||
Limit int
|
||||
}
|
||||
|
||||
// Validate checks the field every engine needs to scope a query: Identity.
|
||||
// Text may be empty (some engines support a scope-only recall), so it is
|
||||
// not required here.
|
||||
func (q Query) Validate() error {
|
||||
if q.Identity == "" {
|
||||
return errors.New("memory query: identity must not be empty")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Record is one stored observation as returned by Write, Query, or List.
|
||||
type Record struct {
|
||||
ID string
|
||||
Identity string
|
||||
Kind string
|
||||
Content string
|
||||
At time.Time
|
||||
Metadata map[string]string
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package memory
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestObservationValidateRequiresIdentityAndContent(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
obs Observation
|
||||
wantErr bool
|
||||
}{
|
||||
{"empty identity", Observation{Content: "x"}, true},
|
||||
{"empty content", Observation{Identity: "u1"}, true},
|
||||
{"both empty", Observation{}, true},
|
||||
{"valid", Observation{Identity: "u1", Content: "x"}, false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
err := tt.obs.Validate()
|
||||
if (err != nil) != tt.wantErr {
|
||||
t.Fatalf("Validate() = %v, wantErr %v", err, tt.wantErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestQueryValidateRequiresIdentity(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
if err := (Query{}).Validate(); err == nil {
|
||||
t.Fatal("Validate() = nil for empty identity, want error")
|
||||
}
|
||||
if err := (Query{Identity: "u1"}).Validate(); err != nil {
|
||||
t.Fatalf("Validate() = %v for identity-only query, want nil (Text may be empty)", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestManifestValidateAcceptsZeroValue(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
if err := (Manifest{}).Validate(); err != nil {
|
||||
t.Fatalf("Validate() = %v, want nil: no field is required yet", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package memory
|
||||
|
||||
import "time"
|
||||
|
||||
// Registrar is the narrow typed host access an engine receives at
|
||||
// registration. Fields are typed contracts declared here — this package
|
||||
// never names who implements them, and the daemon itself is never part of
|
||||
// it.
|
||||
type Registrar struct {
|
||||
// Events publishes engine activity (writes, forgets, failures) for
|
||||
// observability. Implementations must be non-blocking and bounded (drop
|
||||
// on overflow), matching the curator family's EventSink contract, so an
|
||||
// engine can never apply backpressure to a chat turn or the daemon.
|
||||
// Always bound.
|
||||
Events EventSink
|
||||
// Clock is injectable time. Always bound; nil at construction is
|
||||
// replaced with the system clock.
|
||||
Clock Clock
|
||||
}
|
||||
|
||||
// EventSink publishes engine activity. Mirrors curator.EventSink: emission
|
||||
// side only, non-blocking and bounded.
|
||||
type EventSink interface {
|
||||
Emit(kind, detail string, data map[string]any)
|
||||
}
|
||||
|
||||
// Clock is injectable time: Now for timestamps.
|
||||
type Clock interface {
|
||||
Now() time.Time
|
||||
}
|
||||
|
||||
type systemClock struct{}
|
||||
|
||||
func (systemClock) Now() time.Time { return time.Now() }
|
||||
@@ -0,0 +1,235 @@
|
||||
package memory
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"slices"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// Registry errors.
|
||||
var (
|
||||
// ErrDuplicate is returned when an engine name is already registered.
|
||||
ErrDuplicate = errors.New("duplicate memory engine")
|
||||
// ErrStarted is returned when registration or lifecycle is attempted
|
||||
// after the registry has started.
|
||||
ErrStarted = errors.New("memory registry already started")
|
||||
)
|
||||
|
||||
type registryState uint8
|
||||
|
||||
const (
|
||||
stateIdle registryState = iota
|
||||
stateRunning
|
||||
stateStopped
|
||||
)
|
||||
|
||||
type engineStatus struct {
|
||||
started bool
|
||||
startErr error
|
||||
}
|
||||
|
||||
// Registry is the memory family owner: it controls registration and
|
||||
// discovery, lifecycle (start/health/stop), shutdown ordering, and failure
|
||||
// isolation. An engine failure — a rejected registration, a failing Start, a
|
||||
// blocking Stop, even a panicking Bind — affects only that engine and is
|
||||
// reported, never fatal to the daemon or to other engines.
|
||||
type Registry struct {
|
||||
mu sync.Mutex
|
||||
host Registrar
|
||||
engines map[string]MemoryEngine
|
||||
status map[string]engineStatus
|
||||
order []string
|
||||
state registryState
|
||||
}
|
||||
|
||||
// NewRegistry builds the family registry. A nil Clock is replaced with the
|
||||
// system clock.
|
||||
func NewRegistry(host Registrar) *Registry {
|
||||
if host.Clock == nil {
|
||||
host.Clock = systemClock{}
|
||||
}
|
||||
return &Registry{
|
||||
host: host,
|
||||
engines: make(map[string]MemoryEngine),
|
||||
status: make(map[string]engineStatus),
|
||||
}
|
||||
}
|
||||
|
||||
// Register validates the engine's declared shape and adds it, binding the
|
||||
// engine to the registrar. Registration fails on nil engines, invalid
|
||||
// manifests, duplicate names, or a panicking Bind — and a failure affects
|
||||
// only that engine.
|
||||
func (r *Registry) Register(e MemoryEngine) error {
|
||||
if isNilEngine(e) {
|
||||
return errors.New("memory: nil engine")
|
||||
}
|
||||
if err := e.Manifest().Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
if r.state != stateIdle {
|
||||
return ErrStarted
|
||||
}
|
||||
if _, dup := r.engines[e.Name()]; dup {
|
||||
return fmt.Errorf("%w: %s", ErrDuplicate, e.Name())
|
||||
}
|
||||
if err := bindSafely(e, r.host); err != nil {
|
||||
return err
|
||||
}
|
||||
r.engines[e.Name()] = e
|
||||
r.order = append(r.order, e.Name())
|
||||
return nil
|
||||
}
|
||||
|
||||
// bindSafely isolates a panicking Bind: an engine that panics while
|
||||
// receiving its host access is refused without taking the registry down.
|
||||
func bindSafely(e MemoryEngine, host Registrar) (err error) {
|
||||
defer func() {
|
||||
if p := recover(); p != nil {
|
||||
err = fmt.Errorf("memory engine %s: bind panic: %v", e.Name(), p)
|
||||
}
|
||||
}()
|
||||
e.Bind(host)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Get returns the registered engine by name.
|
||||
func (r *Registry) Get(name string) (MemoryEngine, bool) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
e, ok := r.engines[name]
|
||||
return e, ok
|
||||
}
|
||||
|
||||
// Names returns the registered engine names in sorted order.
|
||||
func (r *Registry) Names() []string {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
names := make([]string, 0, len(r.engines))
|
||||
for name := range r.engines {
|
||||
names = append(names, name)
|
||||
}
|
||||
slices.Sort(names)
|
||||
return names
|
||||
}
|
||||
|
||||
// Start starts every registered engine in registration order. An engine
|
||||
// whose Start fails (error or panic) is marked unhealthy and skipped; the
|
||||
// rest start regardless, and all failures are joined into the returned
|
||||
// error. This is the family's failure-isolation boundary for lifecycle.
|
||||
func (r *Registry) Start(ctx context.Context) error {
|
||||
r.mu.Lock()
|
||||
if r.state != stateIdle {
|
||||
r.mu.Unlock()
|
||||
return ErrStarted
|
||||
}
|
||||
r.state = stateRunning
|
||||
order := slices.Clone(r.order)
|
||||
r.mu.Unlock()
|
||||
|
||||
var errs []error
|
||||
for _, name := range order {
|
||||
e := r.engines[name]
|
||||
err := startSafely(ctx, e)
|
||||
r.mu.Lock()
|
||||
if err != nil {
|
||||
r.status[name] = engineStatus{startErr: err}
|
||||
errs = append(errs, fmt.Errorf("memory engine %s: %w", name, err))
|
||||
} else {
|
||||
r.status[name] = engineStatus{started: true}
|
||||
}
|
||||
r.mu.Unlock()
|
||||
}
|
||||
return errors.Join(errs...)
|
||||
}
|
||||
|
||||
func startSafely(ctx context.Context, e MemoryEngine) (err error) {
|
||||
defer func() {
|
||||
if p := recover(); p != nil {
|
||||
err = fmt.Errorf("start panic: %v", p)
|
||||
}
|
||||
}()
|
||||
return e.Start(ctx)
|
||||
}
|
||||
|
||||
// Health reports every registered engine's health. An engine whose Start
|
||||
// failed is reported unhealthy with the failure; otherwise the engine's own
|
||||
// Health is used. A panicking Health is reported unhealthy, not propagated.
|
||||
func (r *Registry) Health(ctx context.Context) map[string]Health {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
out := make(map[string]Health, len(r.engines))
|
||||
for name, e := range r.engines {
|
||||
if st, ok := r.status[name]; ok && st.startErr != nil {
|
||||
out[name] = Health{Status: HealthUnhealthy, Message: st.startErr.Error()}
|
||||
continue
|
||||
}
|
||||
out[name] = healthSafely(ctx, e)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func healthSafely(ctx context.Context, e MemoryEngine) (h Health) {
|
||||
defer func() {
|
||||
if p := recover(); p != nil {
|
||||
h = Health{Status: HealthUnhealthy, Message: fmt.Sprintf("health panic: %v", p)}
|
||||
}
|
||||
}()
|
||||
return e.Health(ctx)
|
||||
}
|
||||
|
||||
// Stop stops every started engine in reverse registration order. Engines
|
||||
// whose Start failed are skipped; the call is bounded by ctx — an engine
|
||||
// that ignores cancellation cannot hang the daemon's shutdown beyond the
|
||||
// caller's deadline, and its error is joined into the result. Stopping a
|
||||
// registry that never started is a no-op.
|
||||
func (r *Registry) Stop(ctx context.Context) error {
|
||||
r.mu.Lock()
|
||||
if r.state == stateIdle || r.state == stateStopped {
|
||||
r.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
r.state = stateStopped
|
||||
order := slices.Clone(r.order)
|
||||
r.mu.Unlock()
|
||||
|
||||
var errs []error
|
||||
for _, name := range slices.Backward(order) {
|
||||
r.mu.Lock()
|
||||
st, ok := r.status[name]
|
||||
r.mu.Unlock()
|
||||
if !ok || !st.started {
|
||||
continue
|
||||
}
|
||||
e := r.engines[name]
|
||||
if err := stopSafely(ctx, e); err != nil {
|
||||
errs = append(errs, fmt.Errorf("memory engine %s: %w", name, err))
|
||||
}
|
||||
}
|
||||
return errors.Join(errs...)
|
||||
}
|
||||
|
||||
func stopSafely(ctx context.Context, e MemoryEngine) (err error) {
|
||||
defer func() {
|
||||
if p := recover(); p != nil {
|
||||
err = fmt.Errorf("stop panic: %v", p)
|
||||
}
|
||||
}()
|
||||
return e.Stop(ctx)
|
||||
}
|
||||
|
||||
func isNilEngine(e MemoryEngine) bool {
|
||||
v := reflect.ValueOf(e)
|
||||
switch v.Kind() {
|
||||
case reflect.Invalid:
|
||||
return true
|
||||
case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Pointer, reflect.Slice:
|
||||
return v.IsNil()
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,394 @@
|
||||
package memory
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"slices"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// --- fake engine -------------------------------------------------------------
|
||||
|
||||
type fakeEngine struct {
|
||||
name string
|
||||
manifest Manifest
|
||||
recorder *[]string // shared lifecycle log
|
||||
startErr error
|
||||
stopErr error
|
||||
stopBlock chan struct{}
|
||||
bindPanic bool
|
||||
view Registrar
|
||||
|
||||
records map[string]Record
|
||||
nextID int
|
||||
}
|
||||
|
||||
func newFake(name string, manifest Manifest) *fakeEngine {
|
||||
return &fakeEngine{name: name, manifest: manifest, records: map[string]Record{}}
|
||||
}
|
||||
|
||||
func (f *fakeEngine) record(e string) {
|
||||
if f.recorder != nil {
|
||||
*f.recorder = append(*f.recorder, e)
|
||||
}
|
||||
}
|
||||
|
||||
func (f *fakeEngine) Name() string { return f.name }
|
||||
func (f *fakeEngine) Version() string { return "test" }
|
||||
func (f *fakeEngine) Manifest() Manifest { return f.manifest }
|
||||
func (f *fakeEngine) Bind(host Registrar) {
|
||||
f.view = host
|
||||
f.record("bind:" + f.name)
|
||||
if f.bindPanic {
|
||||
panic("bind boom")
|
||||
}
|
||||
}
|
||||
|
||||
func (f *fakeEngine) Write(_ context.Context, obs Observation) (Record, error) {
|
||||
f.nextID++
|
||||
id := obs.Identity + "-" + time.Now().Format("150405.000000000") + "-" + string(rune('a'+f.nextID))
|
||||
rec := Record{ID: id, Identity: obs.Identity, Kind: obs.Kind, Content: obs.Content, At: obs.At, Metadata: obs.Metadata}
|
||||
f.records[id] = rec
|
||||
return rec, nil
|
||||
}
|
||||
|
||||
func (f *fakeEngine) Query(_ context.Context, q Query) ([]Record, error) {
|
||||
var out []Record
|
||||
for _, r := range f.records {
|
||||
if r.Identity == q.Identity {
|
||||
out = append(out, r)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (f *fakeEngine) List(ctx context.Context, identity string) ([]Record, error) {
|
||||
return f.Query(ctx, Query{Identity: identity})
|
||||
}
|
||||
|
||||
func (f *fakeEngine) Forget(_ context.Context, id string) error {
|
||||
delete(f.records, id)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeEngine) Start(context.Context) error {
|
||||
if f.startErr != nil {
|
||||
return f.startErr
|
||||
}
|
||||
f.record("start:" + f.name)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeEngine) Health(context.Context) Health { return Health{Status: HealthHealthy} }
|
||||
|
||||
func (f *fakeEngine) Stop(ctx context.Context) error {
|
||||
if f.stopBlock != nil {
|
||||
select {
|
||||
case <-f.stopBlock:
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
if f.stopErr != nil {
|
||||
return f.stopErr
|
||||
}
|
||||
f.record("stop:" + f.name)
|
||||
return nil
|
||||
}
|
||||
|
||||
// --- registry behavior --------------------------------------------------------
|
||||
|
||||
func TestRegistryRegisterAndDiscover(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
r := NewRegistry(Registrar{})
|
||||
a := newFake("a", Manifest{})
|
||||
b := newFake("b", Manifest{})
|
||||
if err := r.Register(a); err != nil {
|
||||
t.Fatalf("Register(a) = %v, want nil", err)
|
||||
}
|
||||
if err := r.Register(b); err != nil {
|
||||
t.Fatalf("Register(b) = %v, want nil", err)
|
||||
}
|
||||
|
||||
got, ok := r.Get("a")
|
||||
if !ok || got != a {
|
||||
t.Fatalf("Get(a) = (%v, %v), want (a, true)", got, ok)
|
||||
}
|
||||
if _, ok := r.Get("missing"); ok {
|
||||
t.Fatal("Get(missing) = true, want false")
|
||||
}
|
||||
if got := r.Names(); len(got) != 2 || got[0] != "a" || got[1] != "b" {
|
||||
t.Fatalf("Names() = %v, want [a b]", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistryRegisterDuplicateRejected(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
r := NewRegistry(Registrar{})
|
||||
if err := r.Register(newFake("a", Manifest{})); err != nil {
|
||||
t.Fatalf("Register(a) = %v, want nil", err)
|
||||
}
|
||||
err := r.Register(newFake("a", Manifest{}))
|
||||
if !errors.Is(err, ErrDuplicate) {
|
||||
t.Fatalf("Register(dup) = %v, want ErrDuplicate", err)
|
||||
}
|
||||
if got := r.Names(); len(got) != 1 {
|
||||
t.Fatalf("Names() = %v, want only the first registration", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistryRegisterNilEngineRejected(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
r := NewRegistry(Registrar{})
|
||||
if err := r.Register(nil); err == nil {
|
||||
t.Fatal("Register(nil) = nil, want error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistryRegisterTypedNilEngineRejected(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
r := NewRegistry(Registrar{})
|
||||
var e *fakeEngine
|
||||
if err := r.Register(e); err == nil {
|
||||
t.Fatal("Register(typed nil) = nil, want error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistryRegisterAfterStartRejected(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
r := NewRegistry(Registrar{})
|
||||
if err := r.Register(newFake("a", Manifest{})); err != nil {
|
||||
t.Fatalf("Register(a) = %v, want nil", err)
|
||||
}
|
||||
if err := r.Start(context.Background()); err != nil {
|
||||
t.Fatalf("Start() = %v, want nil", err)
|
||||
}
|
||||
err := r.Register(newFake("b", Manifest{}))
|
||||
if !errors.Is(err, ErrStarted) {
|
||||
t.Fatalf("Register after Start = %v, want ErrStarted", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistryBindAlwaysReceivesEventsAndClock(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
sink := &testSink{}
|
||||
clock := testClock{now: time.Unix(0, 0)}
|
||||
r := NewRegistry(Registrar{Events: sink, Clock: clock})
|
||||
e := newFake("a", Manifest{})
|
||||
if err := r.Register(e); err != nil {
|
||||
t.Fatalf("Register(a) = %v, want nil", err)
|
||||
}
|
||||
if e.view.Events == nil {
|
||||
t.Error("view.Events = nil; activity must always be attributable")
|
||||
}
|
||||
if e.view.Clock == nil {
|
||||
t.Error("view.Clock = nil; time is always available")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistryBindPanicIsolated(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
r := NewRegistry(Registrar{})
|
||||
panicky := newFake("panicky", Manifest{})
|
||||
panicky.bindPanic = true
|
||||
if err := r.Register(panicky); err == nil {
|
||||
t.Fatal("Register(panicking Bind) = nil, want error")
|
||||
}
|
||||
if got := r.Names(); len(got) != 0 {
|
||||
t.Fatalf("Names() = %v, want empty after a panicking Bind", got)
|
||||
}
|
||||
|
||||
// The registry survives and still accepts healthy engines.
|
||||
if err := r.Register(newFake("ok", Manifest{})); err != nil {
|
||||
t.Fatalf("Register(ok) after panicking Bind = %v, want nil", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistryStartStopOrdering(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
r := NewRegistry(Registrar{})
|
||||
var log []string
|
||||
a := newFake("a", Manifest{})
|
||||
a.recorder = &log
|
||||
b := newFake("b", Manifest{})
|
||||
b.recorder = &log
|
||||
c := newFake("c", Manifest{})
|
||||
c.recorder = &log
|
||||
for _, e := range []*fakeEngine{a, b, c} {
|
||||
if err := r.Register(e); err != nil {
|
||||
t.Fatalf("Register(%s) = %v, want nil", e.name, err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := r.Start(context.Background()); err != nil {
|
||||
t.Fatalf("Start() = %v, want nil", err)
|
||||
}
|
||||
if err := r.Stop(context.Background()); err != nil {
|
||||
t.Fatalf("Stop() = %v, want nil", err)
|
||||
}
|
||||
|
||||
want := []string{
|
||||
"bind:a", "bind:b", "bind:c",
|
||||
"start:a", "start:b", "start:c",
|
||||
"stop:c", "stop:b", "stop:a",
|
||||
}
|
||||
if got := log; !equalStrings(got, want) {
|
||||
t.Fatalf("lifecycle events = %v, want %v (start in registration order, stop reversed)", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistryStartIsolatesFailure(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
r := NewRegistry(Registrar{})
|
||||
var log []string
|
||||
a := newFake("a", Manifest{})
|
||||
a.recorder = &log
|
||||
bad := newFake("bad", Manifest{})
|
||||
bad.recorder = &log
|
||||
bad.startErr = errBoom
|
||||
c := newFake("c", Manifest{})
|
||||
c.recorder = &log
|
||||
for _, e := range []*fakeEngine{a, bad, c} {
|
||||
if err := r.Register(e); err != nil {
|
||||
t.Fatalf("Register(%s) = %v, want nil", e.name, err)
|
||||
}
|
||||
}
|
||||
|
||||
err := r.Start(context.Background())
|
||||
if !errors.Is(err, errBoom) {
|
||||
t.Fatalf("Start() error = %v, want the failing engine's error", err)
|
||||
}
|
||||
|
||||
if !logHas(log, "start:a") || !logHas(log, "start:c") {
|
||||
t.Fatalf("healthy engines did not start: %v", log)
|
||||
}
|
||||
if logHas(log, "start:bad") {
|
||||
t.Fatalf("failing engine started despite Start error: %v", log)
|
||||
}
|
||||
|
||||
health := r.Health(context.Background())
|
||||
if health["bad"].Status != HealthUnhealthy {
|
||||
t.Fatalf("Health(bad).Status = %v, want unhealthy", health["bad"].Status)
|
||||
}
|
||||
if health["a"].Status != HealthHealthy {
|
||||
t.Fatalf("Health(a).Status = %v, want healthy", health["a"].Status)
|
||||
}
|
||||
|
||||
if err := r.Stop(context.Background()); err != nil {
|
||||
t.Fatalf("Stop() = %v, want nil", err)
|
||||
}
|
||||
want := []string{"bind:a", "bind:bad", "bind:c", "start:a", "start:c", "stop:c", "stop:a"}
|
||||
if got := log; !equalStrings(got, want) {
|
||||
t.Fatalf("lifecycle events = %v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistryStopBoundedByContext(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
r := NewRegistry(Registrar{})
|
||||
blocked := newFake("blocked", Manifest{})
|
||||
blocked.stopBlock = make(chan struct{})
|
||||
if err := r.Register(blocked); err != nil {
|
||||
t.Fatalf("Register(blocked) = %v, want nil", err)
|
||||
}
|
||||
if err := r.Start(context.Background()); err != nil {
|
||||
t.Fatalf("Start() = %v, want nil", err)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
|
||||
defer cancel()
|
||||
start := time.Now()
|
||||
err := r.Stop(ctx)
|
||||
elapsed := time.Since(start)
|
||||
|
||||
if !errors.Is(err, context.DeadlineExceeded) {
|
||||
t.Fatalf("Stop() error = %v, want context.DeadlineExceeded", err)
|
||||
}
|
||||
if elapsed > 2*time.Second {
|
||||
t.Fatalf("Stop() took %v; a blocking engine must not hang shutdown", elapsed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistryStopBeforeStartIsNoop(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
r := NewRegistry(Registrar{})
|
||||
if err := r.Register(newFake("a", Manifest{})); err != nil {
|
||||
t.Fatalf("Register(a) = %v, want nil", err)
|
||||
}
|
||||
if err := r.Stop(context.Background()); err != nil {
|
||||
t.Fatalf("Stop() before Start = %v, want nil no-op", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistryStartTwiceRejected(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
r := NewRegistry(Registrar{})
|
||||
if err := r.Start(context.Background()); err != nil {
|
||||
t.Fatalf("Start() = %v, want nil", err)
|
||||
}
|
||||
if err := r.Start(context.Background()); !errors.Is(err, ErrStarted) {
|
||||
t.Fatalf("second Start() = %v, want ErrStarted", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistryHealthReportsEveryEngine(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
r := NewRegistry(Registrar{})
|
||||
if err := r.Register(newFake("a", Manifest{})); err != nil {
|
||||
t.Fatalf("Register(a) = %v, want nil", err)
|
||||
}
|
||||
health := r.Health(context.Background())
|
||||
if len(health) != 1 || health["a"].Status != HealthHealthy {
|
||||
t.Fatalf("Health() = %v, want one healthy entry for a", health)
|
||||
}
|
||||
}
|
||||
|
||||
// --- helpers -------------------------------------------------------------
|
||||
|
||||
type testSink struct {
|
||||
mu sync.Mutex
|
||||
kinds []string
|
||||
}
|
||||
|
||||
func (s *testSink) Emit(kind, _ string, _ map[string]any) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.kinds = append(s.kinds, kind)
|
||||
}
|
||||
|
||||
type testClock struct{ now time.Time }
|
||||
|
||||
func (c testClock) Now() time.Time { return c.now }
|
||||
|
||||
var errBoom = errors.New("boom")
|
||||
|
||||
func equalStrings(a, b []string) bool {
|
||||
if len(a) != len(b) {
|
||||
return false
|
||||
}
|
||||
for i := range a {
|
||||
if a[i] != b[i] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func logHas(log []string, want string) bool {
|
||||
return slices.Contains(log, want)
|
||||
}
|
||||
Reference in new issue
Block a user