diff --git a/internal/domain/curator/contract.go b/internal/domain/curator/contract.go index 645f77e10..e4c0ad9d5 100644 --- a/internal/domain/curator/contract.go +++ b/internal/domain/curator/contract.go @@ -7,22 +7,21 @@ import ( "errors" "strings" "time" + + "github.com/samcharles93/archie-core/internal/domain/lifecycle" ) -// HealthStatus is a curator's point-in-time health. -type HealthStatus string +// HealthStatus is a point-in-time health status. +type HealthStatus = lifecycle.HealthStatus const ( - HealthHealthy HealthStatus = "healthy" - HealthDegraded HealthStatus = "degraded" - HealthUnhealthy HealthStatus = "unhealthy" + HealthHealthy = lifecycle.HealthHealthy + HealthDegraded = lifecycle.HealthDegraded + HealthUnhealthy = lifecycle.HealthUnhealthy ) -// Health is a point-in-time curator health report. -type Health struct { - Status HealthStatus - Message string -} +// Health is a point-in-time health report. +type Health = lifecycle.Health // Manifest is a curator's declared shape: what input wakes it, how often it // runs, which tools it may reach, and which memory engine it uses. The diff --git a/internal/domain/curator/registry.go b/internal/domain/curator/registry.go index 2e0c34301..cbddfcae5 100644 --- a/internal/domain/curator/registry.go +++ b/internal/domain/curator/registry.go @@ -1,50 +1,26 @@ package curator import ( - "context" "errors" - "fmt" - "reflect" - "slices" - "sync" "time" + + "github.com/samcharles93/archie-core/internal/domain/lifecycle" ) // Registry errors. var ( - // ErrDuplicate is returned when a curator name is already registered. - ErrDuplicate = errors.New("duplicate curator") - // ErrStarted is returned when registration or lifecycle is attempted - // after the registry has started. - ErrStarted = errors.New("curator registry already started") + ErrDuplicate = lifecycle.ErrDuplicate + ErrStarted = lifecycle.ErrStarted ) -type registryState uint8 - -const ( - stateIdle registryState = iota - stateRunning - stateStopped -) - -type curatorStatus struct { - started bool - startErr error -} - // Registry owns curator registration and lifecycle. A curator's failure // affects only that curator. type Registry struct { - mu sync.Mutex - host Registrar - curators map[string]CuratorEngine - status map[string]curatorStatus - order []string - state registryState + *lifecycle.Registry[CuratorEngine, Registrar] + host Registrar // activity tracks recent per-curator run history for observability. - // It has its own mutex and is safe to - // use independently of r.mu. + // It has its own mutex. activity *activityTracker } @@ -56,9 +32,8 @@ func NewRegistry(host Registrar) *Registry { host.Clock = systemClock{} } return &Registry{ + Registry: lifecycle.New[CuratorEngine, Registrar]("curator", host.Log), host: host, - curators: make(map[string]CuratorEngine), - status: make(map[string]curatorStatus), activity: newActivityTracker(), } } @@ -77,7 +52,7 @@ func (r *Registry) Activity(name string) (Activity, bool) { // Register validates the curator's manifest and binds it to a filtered host // view. Failures affect only that curator. func (r *Registry) Register(c CuratorEngine) error { - if isNilEngine(c) { + if lifecycle.IsNil(c) { return errors.New("curator: nil engine") } m := c.Manifest() @@ -87,21 +62,13 @@ func (r *Registry) Register(c CuratorEngine) error { if err := r.validateDeclared(m); err != nil { return err } + return r.Add(c, r.filter(m)) +} - r.mu.Lock() - defer r.mu.Unlock() - if r.state != stateIdle { - return ErrStarted - } - if _, dup := r.curators[c.Name()]; dup { - return fmt.Errorf("%w: %s", ErrDuplicate, c.Name()) - } - if err := bindSafely(c, r.filter(m)); err != nil { - return err - } - r.curators[c.Name()] = c - r.order = append(r.order, c.Name()) - return nil +// Host returns the raw registrar bundle the registry was built with. The +// daemon itself is never part of it. +func (r *Registry) Host() Registrar { + return r.host } // validateDeclared enforces "only the host services a curator's declared @@ -152,180 +119,9 @@ func agentic(m Manifest) bool { return len(m.Tools) > 0 || m.Skills || m.MemoryEngine != "" || m.Conversations } -// bindSafely isolates a panicking Bind: a curator that panics while -// receiving its host access is refused without taking the registry down. -func bindSafely(c CuratorEngine, host Registrar) (err error) { - defer func() { - if p := recover(); p != nil { - err = fmt.Errorf("curator %s: bind panic: %v", c.Name(), p) - } - }() - c.Bind(host) - return nil -} - -// Host returns the raw registrar bundle the registry was built with — the -// shared services (events, clock, model) the runtime and future surfaces -// use. It is narrow typed; the daemon itself is never part of it. -func (r *Registry) Host() Registrar { - r.mu.Lock() - defer r.mu.Unlock() - return r.host -} - -// Get returns the registered curator by name. -func (r *Registry) Get(name string) (CuratorEngine, bool) { - r.mu.Lock() - defer r.mu.Unlock() - c, ok := r.curators[name] - return c, ok -} - -// Names returns the registered curator names in sorted order. -func (r *Registry) Names() []string { - r.mu.Lock() - defer r.mu.Unlock() - names := make([]string, 0, len(r.curators)) - for name := range r.curators { - names = append(names, name) - } - slices.Sort(names) - return names -} - -// Start starts every registered curator in registration order. A curator -// 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 == stateRunning { - r.mu.Unlock() - return ErrStarted - } - r.state = stateRunning - order := slices.Clone(r.order) - r.mu.Unlock() - - var errs []error - for _, name := range order { - c := r.curators[name] - err := startSafely(ctx, c) - r.mu.Lock() - if err != nil { - r.status[name] = curatorStatus{startErr: err} - if r.host.Log != nil { - r.host.Log.Error("curator lifecycle failed", "curator", name, "phase", "start", "err", err) - } - errs = append(errs, fmt.Errorf("curator %s: %w", name, err)) - } else { - r.status[name] = curatorStatus{started: true} - } - r.mu.Unlock() - } - return errors.Join(errs...) -} - -func startSafely(ctx context.Context, c CuratorEngine) (err error) { - defer func() { - if p := recover(); p != nil { - err = fmt.Errorf("start panic: %v", p) - } - }() - return c.Start(ctx) -} - -// Health reports every registered curator's health. A curator whose Start -// failed is reported unhealthy with the failure; otherwise the curator'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.curators)) - for name, c := range r.curators { - if st, ok := r.status[name]; ok && st.startErr != nil { - out[name] = Health{Status: HealthUnhealthy, Message: st.startErr.Error()} - continue - } - out[name] = healthSafely(ctx, c) - } - return out -} - -func healthSafely(ctx context.Context, c CuratorEngine) (h Health) { - defer func() { - if p := recover(); p != nil { - h = Health{Status: HealthUnhealthy, Message: fmt.Sprintf("health panic: %v", p)} - } - }() - return c.Health(ctx) -} - -// Stop stops started curators in reverse order, bounded by ctx, and joins -// their errors. -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 - } - c := r.curators[name] - if err := stopSafely(ctx, c); err != nil { - if r.host.Log != nil { - r.host.Log.Error("curator lifecycle failed", "curator", name, "phase", "stop", "err", err) - } - errs = append(errs, fmt.Errorf("curator %s: %w", name, err)) - } - } - return errors.Join(errs...) -} - -func stopSafely(ctx context.Context, c CuratorEngine) (err error) { - defer func() { - if p := recover(); p != nil { - err = fmt.Errorf("stop panic: %v", p) - } - }() - return c.Stop(ctx) -} - -func isNilEngine(c CuratorEngine) bool { - v := reflect.ValueOf(c) - 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 -} - func (r *Registry) replaceDefinitions(candidate *Registry) { - r.mu.Lock() - defer r.mu.Unlock() - r.order = slices.DeleteFunc(r.order, func(name string) bool { - if _, custom := r.curators[name].(*DefinitionEngine); !custom { - return false - } - delete(r.curators, name) - delete(r.status, name) - return true - }) - for _, name := range candidate.order { - r.curators[name] = candidate.curators[name] - r.order = append(r.order, name) - } + r.Replace(func(c CuratorEngine) bool { + _, custom := c.(*DefinitionEngine) + return custom + }, candidate.Registry) } diff --git a/internal/domain/lifecycle/registry.go b/internal/domain/lifecycle/registry.go new file mode 100644 index 000000000..f166fe563 --- /dev/null +++ b/internal/domain/lifecycle/registry.go @@ -0,0 +1,251 @@ +// Package lifecycle is the registration and start/health/stop machinery +// shared by engine families such as curators and memory engines. +package lifecycle + +import ( + "context" + "errors" + "fmt" + "log/slog" + "reflect" + "slices" + "sync" +) + +// 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 +} + +// Registry errors. +var ( + // ErrDuplicate is returned when an engine name is already registered. + ErrDuplicate = errors.New("duplicate engine") + // ErrStarted is returned when registration or lifecycle is attempted + // after the registry has started. + ErrStarted = errors.New("registry already started") +) + +// Engine is a named, host-bound component with a lifecycle. +type Engine[H any] interface { + Name() string + Bind(host H) + Start(ctx context.Context) error + Health(ctx context.Context) Health + Stop(ctx context.Context) error +} + +type state uint8 + +const ( + stateIdle state = iota + stateRunning + stateStopped +) + +type status struct { + started bool + startErr error +} + +// Registry owns registration and lifecycle for one engine family. An +// engine's failure, including a panic, affects only that engine. +type Registry[E Engine[H], H any] struct { + kind string + log *slog.Logger + mu sync.Mutex + engines map[string]E + status map[string]status + order []string + state state +} + +// New builds an empty registry. kind prefixes errors and log lines; a nil +// log disables lifecycle logging. +func New[E Engine[H], H any](kind string, log *slog.Logger) *Registry[E, H] { + return &Registry[E, H]{ + kind: kind, + log: log, + engines: make(map[string]E), + status: make(map[string]status), + } +} + +// IsNil reports whether v is nil or an interface holding a nil value. +func IsNil(v any) bool { + rv := reflect.ValueOf(v) + switch rv.Kind() { + case reflect.Invalid: + return true + case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Pointer, reflect.Slice: + return rv.IsNil() + } + return false +} + +// Add binds e to host and registers it. A panicking Bind refuses the engine. +func (r *Registry[E, H]) Add(e E, host H) error { + r.mu.Lock() + defer r.mu.Unlock() + if r.state != stateIdle { + return fmt.Errorf("%s: %w", r.kind, ErrStarted) + } + name := e.Name() + if _, dup := r.engines[name]; dup { + return fmt.Errorf("%w: %s %s", ErrDuplicate, r.kind, name) + } + if err := guard(func() error { e.Bind(host); return nil }); err != nil { + return fmt.Errorf("%s %s: bind %w", r.kind, name, err) + } + r.engines[name] = e + r.order = append(r.order, name) + return nil +} + +// Get returns the registered engine by name. +func (r *Registry[E, H]) Get(name string) (E, 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[E, H]) 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 engine in registration order. An engine whose Start +// fails is marked unhealthy and skipped; the rest start regardless, and all +// failures are joined into the returned error. A stopped registry may be +// started again. +func (r *Registry[E, H]) Start(ctx context.Context) error { + r.mu.Lock() + if r.state == stateRunning { + r.mu.Unlock() + return fmt.Errorf("%s: %w", r.kind, ErrStarted) + } + r.state = stateRunning + order := slices.Clone(r.order) + r.mu.Unlock() + + var errs []error + for _, name := range order { + e, _ := r.Get(name) + err := guard(func() error { return e.Start(ctx) }) + r.mu.Lock() + if err != nil { + r.status[name] = status{startErr: err} + errs = append(errs, r.fail(name, "start", err)) + } else { + r.status[name] = status{started: true} + } + r.mu.Unlock() + } + return errors.Join(errs...) +} + +// Health reports every engine's health. An engine whose Start failed, or +// whose Health panics, is reported unhealthy. +func (r *Registry[E, H]) 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 := r.status[name]; st.startErr != nil { + out[name] = Health{Status: HealthUnhealthy, Message: st.startErr.Error()} + continue + } + out[name] = healthSafely(ctx, e) + } + return out +} + +// Stop stops started engines in reverse order, bounded by ctx, and joins +// their errors. +func (r *Registry[E, H]) Stop(ctx context.Context) error { + r.mu.Lock() + if r.state != stateRunning { + 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() + e, st := r.engines[name], r.status[name] + r.mu.Unlock() + if !st.started { + continue + } + if err := guard(func() error { return e.Stop(ctx) }); err != nil { + errs = append(errs, r.fail(name, "stop", err)) + } + } + return errors.Join(errs...) +} + +// Replace removes the engines drop selects and appends every engine from +// src, keeping src's order. Call it only while stopped. +func (r *Registry[E, H]) Replace(drop func(E) bool, src *Registry[E, H]) { + r.mu.Lock() + defer r.mu.Unlock() + r.order = slices.DeleteFunc(r.order, func(name string) bool { + if !drop(r.engines[name]) { + return false + } + delete(r.engines, name) + delete(r.status, name) + return true + }) + for _, name := range src.order { + r.engines[name] = src.engines[name] + r.order = append(r.order, name) + } +} + +func (r *Registry[E, H]) fail(name, phase string, err error) error { + if r.log != nil { + r.log.Error(r.kind+" lifecycle failed", "name", name, "phase", phase, "err", err) + } + return fmt.Errorf("%s %s: %w", r.kind, name, err) +} + +// guard runs fn, converting a panic into an error. +func guard(fn func() error) (err error) { + defer func() { + if p := recover(); p != nil { + err = fmt.Errorf("panic: %v", p) + } + }() + return fn() +} + +func healthSafely[E Engine[H], H any](ctx context.Context, e E) (h Health) { + defer func() { + if p := recover(); p != nil { + h = Health{Status: HealthUnhealthy, Message: fmt.Sprintf("health panic: %v", p)} + } + }() + return e.Health(ctx) +} diff --git a/internal/domain/memory/contract.go b/internal/domain/memory/contract.go index 0fc821832..89edee5f9 100644 --- a/internal/domain/memory/contract.go +++ b/internal/domain/memory/contract.go @@ -8,22 +8,21 @@ import ( "fmt" "strconv" "time" + + "github.com/samcharles93/archie-core/internal/domain/lifecycle" ) -// HealthStatus is an engine's point-in-time health. -type HealthStatus string +// HealthStatus is a point-in-time health status. +type HealthStatus = lifecycle.HealthStatus const ( - HealthHealthy HealthStatus = "healthy" - HealthDegraded HealthStatus = "degraded" - HealthUnhealthy HealthStatus = "unhealthy" + HealthHealthy = lifecycle.HealthHealthy + HealthDegraded = lifecycle.HealthDegraded + HealthUnhealthy = lifecycle.HealthUnhealthy ) -// Health is a point-in-time engine health report. -type Health struct { - Status HealthStatus - Message string -} +// Health is a point-in-time health report. +type Health = lifecycle.Health // Manifest is an engine's declared shape. RequiresNetwork marks an engine // that calls an external service, so a caller can size timeouts and diff --git a/internal/domain/memory/registry.go b/internal/domain/memory/registry.go index 75a04dd27..86779563a 100644 --- a/internal/domain/memory/registry.go +++ b/internal/domain/memory/registry.go @@ -1,45 +1,22 @@ package memory import ( - "context" "errors" - "fmt" - "reflect" - "slices" - "sync" + + "github.com/samcharles93/archie-core/internal/domain/lifecycle" ) // 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") + ErrDuplicate = lifecycle.ErrDuplicate + ErrStarted = lifecycle.ErrStarted ) -type registryState uint8 - -const ( - stateIdle registryState = iota - stateRunning - stateStopped -) - -type engineStatus struct { - started bool - startErr error -} - // Registry owns memory engine registration and lifecycle. An engine's // failure affects only that engine. type Registry struct { - mu sync.Mutex - host Registrar - engines map[string]MemoryEngine - status map[string]engineStatus - order []string - state registryState + *lifecycle.Registry[MemoryEngine, Registrar] + host Registrar } // NewRegistry builds the family registry. A nil Clock is replaced with the @@ -48,182 +25,17 @@ 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), - } + return &Registry{Registry: lifecycle.New[MemoryEngine, Registrar]("memory engine", nil), host: host} } -// 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. +// Register validates the engine's declared shape and binds it to the +// registrar. A failure affects only that engine. func (r *Registry) Register(e MemoryEngine) error { - if isNilEngine(e) { + if lifecycle.IsNil(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 started engines in reverse order, bounded by ctx, and joins -// their errors. -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 + return r.Add(e, r.host) }