feat(messaging): record channel lifecycle, and decide its surface

archie-core-8cda.6.8's producer half. The service handed every channel an empty
channels.Lifecycle{}, so starting, running, failed and stopped were recorded
nowhere and internal/channels/status.Manager -- which has had MarkStarting,
MarkRunning, MarkDegraded, MarkFailed, MarkStopped and Snapshot all along -- had no
production writer at all. The channels have always reported: all three call
ReportStarting and ReportRunning on whichever lifecycle they are given.

Each composed channel now gets its own report into a manager keyed by channel, so
one channel's failure marks only itself; a channel that cannot start is marked
failed with its reason rather than only logged, and a channel that returns is
marked stopped. Service.ChannelStatus is the producer a dashboard surface reads.

Left open deliberately: the cross-process carrier, and reload's direction.
docs/architecture/migration-decisions.md records the shape by the precedent the
contract already establishes -- archie-core-ymut's config snapshot is "the one
surface whose writer is the daemon and whose reader is the UI process", a pair of
administrative RPCs deny-by-default under authorizesTaskScopedCall -- and names
what that settles: channel state is runtime state rather than a settings document,
so it does not belong among the ControlPlaneService's validated resource kinds; the
UI already dials the State Store and pumps its cursor, so no new transport is
needed; and the contract PRD's grouped table gains a group in the same change that
adds the RPCs. Reload runs the other way and is left as a named open question
rather than decided by analogy with a status report, because a request queue and a
status report do not have the same lifetime. It also records that 8cda.6.9's
component self-report is the same shape, so the two do not become two homes for
"what a component reports about itself".

Red-proofed: restoring the empty lifecycle fails TestServiceRecordsChannelLifecycle
with "channel webhook never reached running; last report State:configured", so the
test pins the fix rather than the manager's existence.

Verified: task check exit 0.
This commit is contained in:
sam committed 2026-09-22 07:57:29 +10:00
1 parent 16ed387b97
commit 2e4db2bdc3
4 files changed
+283 -1

No files matched your search

+38
View File
@@ -322,6 +322,44 @@ Service then imports only `internal/infrastructure/controlplanerpc`,
`gatewayrpc` and `staterpc`, so `go list -deps ./cmd/archie-messaging` loses all
four banned packages and the gate can land green.
**Channel state to the dashboard: one administrative surface, following the
config-snapshot precedent (2026-09-22, `archie-core-8cda.6.8`).** The Messaging
Service now records its channels' lifecycle -- `internal/channels/status.Manager`,
one entry per composed channel, written by each channel's own report through
`channels.Lifecycle` -- and nothing reads that across a process boundary.
`/api/channels` answers with nothing because `webui.Server.Channels` has no
production source, and POST `/api/channels/{id}/reload` answers 501 for the same
reason. The carrier is the State Store, and the shape is the one
`archie-core-ymut` already established for config snapshots
(`docs/prds/state-store-contract.md`, "the one surface whose writer is the daemon
and whose reader is the UI process"): a pair of administrative RPCs, deny-by-default
under `authorizesTaskScopedCall`, so a task-scoped grant reaches neither.
What that decides, so the implementation need not invent it:
- A channel's state is **runtime** state, not a settings document. It does not
belong in the `ControlPlaneService` resource kinds, which are validated,
versioned documents seeded from config; a channel that is failed is not a
document anybody edits.
- The reader is the UI process, which already dials the State Store and pumps its
cursor, so the surface needs no new transport in either direction.
- Adding the pair changes the contract's RPC count, so
`docs/prds/state-store-contract.md`'s grouped table gains a group in the same
change that adds the RPCs -- the table is the contract's own index, and a
surface it does not list is a surface nobody finds.
**Left open here, deliberately.** Reload runs the other way -- the UI asks the
service to reload a channel -- and the config-snapshot precedent only describes a
writer-to-reader direction. Two candidates: a second surface carrying a request
the service observes and clears, or a field on the same surface the service
watches. Deciding it now would be choosing a lifetime for a request queue by
analogy with a status report; they are not the same object.
`archie-core-8cda.6.9`'s component self-report is the **same shape**: a process
reporting something about itself for the UI to read. Whether it shares this
surface or gets its own is a decision for `6.9`, and the one outcome to avoid is
two homes for "what a component reports about itself".
### 3. Identity data migration
The migration must define:
@@ -0,0 +1,52 @@
package archiemessaging
import (
"github.com/samcharles93/archie-core/internal/channels"
"github.com/samcharles93/archie-core/internal/channels/status"
)
// channelDescriptors declares the operator-facing identity of each composed
// channel. Only what an operator may see: no configuration value ever enters a
// descriptor, so the manager cannot become a second source for a token or a
// credential.
func channelDescriptors(instances []channelInstance) []status.Descriptor {
descriptors := make([]status.Descriptor, 0, len(instances))
for _, instance := range instances {
descriptors = append(descriptors, status.Descriptor{
ID: instance.name,
Name: instance.name,
Configured: true,
// Telegram is the only front-end that carries a reload seam today
// (archiemessaging.telegramFeatures rewires it on request). Declaring
// the others would invite the dashboard to offer a button that
// answers "reloaded" and changed nothing.
ReloadSupported: instance.name == "telegram",
})
}
return descriptors
}
// lifecycleFor returns the report a channel writes its own state through. Each
// channel gets its own closure, so one channel's failure marks only itself --
// which is the reason the manager is keyed by channel rather than being one flag
// on the service.
//
// Before this, Start handed every channel an empty channels.Lifecycle{}, so
// nothing recorded starting, running or failed anywhere and
// internal/channels/status.Manager had no production writer at all
// (archie-core-8cda.6.8). The channels have always reported: all three call
// ReportStarting and ReportRunning on whichever lifecycle they are handed.
func (s *Service) lifecycleFor(id string) channels.Lifecycle {
return channels.Lifecycle{
Starting: func() { s.status.MarkStarting(id) },
Running: func() { s.status.MarkRunning(id) },
}
}
// ChannelStatus reports the last known state of every composed channel. It is the
// producer side of the dashboard surface: whatever carries this to the UI reads
// here rather than reconstructing it, and the manager stays the one place channel
// lifecycle is recorded.
func (s *Service) ChannelStatus() []status.Status {
return s.status.Snapshot()
}
@@ -0,0 +1,178 @@
package archiemessaging
import (
"context"
"encoding/json"
"fmt"
"log/slog"
"net"
"testing"
"time"
"github.com/samcharles93/archie-core/internal/channels"
"github.com/samcharles93/archie-core/internal/channels/status"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/domain/messaging"
)
// waitForState polls the service's own report until the channel reaches want, so
// the assertion races the channel's goroutine rather than the clock.
func waitForState(t *testing.T, srv *Service, id string, want status.State) status.Status {
t.Helper()
deadline := time.Now().Add(5 * time.Second)
var last status.Status
for time.Now().Before(deadline) {
for _, candidate := range srv.ChannelStatus() {
if candidate.ID != id {
continue
}
last = candidate
if candidate.State == want {
return candidate
}
}
time.Sleep(10 * time.Millisecond)
}
t.Fatalf("channel %s never reached %s; last report %+v", id, want, last)
return status.Status{}
}
// TestServiceRecordsChannelLifecycle pins the fact archie-core-8cda.6.8 is about:
// a channel's own report reaches a manager. Before this the service handed every
// channel an empty Lifecycle, so starting/running/stopped were recorded nowhere
// and internal/channels/status.Manager had no production writer at all.
func TestServiceRecordsChannelLifecycle(t *testing.T) {
port := freePort(t)
addr := fmt.Sprintf("127.0.0.1:%d", port)
srv, err := compose(t.Context(), deps{
Config: ResolvedConfig{
Options: Options{ShutdownTimeout: 2 * time.Second},
WebhookAddr: addr,
Webhook: config.WebhookRoute{Path: "/smoke"},
},
Log: slog.Default(),
Chat: &recordingChatContract{routes: make(chan messaging.Inbound, 1), reply: "ok"},
})
if err != nil {
t.Fatalf("compose: %v", err)
}
// Composed but not started: the only honest thing to report is configured.
composed := srv.ChannelStatus()
if len(composed) != 1 || composed[0].State != status.StateConfigured {
t.Fatalf("ChannelStatus before Start = %+v, want one configured channel", composed)
}
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
started := make(chan error, 1)
go func() { started <- srv.Start(ctx) }()
running := waitForState(t, srv, "webhook", status.StateRunning)
srv.Stop()
select {
case err := <-started:
if err != nil {
t.Fatalf("srv.Start returned %v, want a clean stop", err)
}
case <-time.After(3 * time.Second):
t.Fatal("srv.Start did not return after Stop")
}
stopped := waitForState(t, srv, "webhook", status.StateStopped)
if stopped.State != status.StateStopped {
t.Fatalf("state after Stop = %s, want stopped", stopped.State)
}
// The descriptor is the operator-facing half, and it must not carry
// configuration: a token in here would make the manager a second source for a
// credential.
if !running.Configured || running.Name != "webhook" {
t.Errorf("status = %+v, want a configured, named webhook", running)
}
if running.ReloadSupported {
t.Error("webhook declares reload support, but no reload seam backs it")
}
}
// TestServiceRecordsAChannelThatCannotStart is the half a status surface exists
// for: a channel that died must be visible on the operator's surface, not only in
// the log, because "nothing reported" and "nothing running" look identical on a
// dashboard.
func TestServiceRecordsAChannelThatCannotStart(t *testing.T) {
// Hold the port, so the channel's own listen fails deterministically.
var lc net.ListenConfig
occupied, err := lc.Listen(t.Context(), "tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("occupy a port: %v", err)
}
t.Cleanup(func() { _ = occupied.Close() })
srv, err := compose(t.Context(), deps{
Config: ResolvedConfig{
Options: Options{ShutdownTimeout: 2 * time.Second},
WebhookAddr: occupied.Addr().String(),
Webhook: config.WebhookRoute{Path: "/smoke"},
},
Log: slog.Default(),
Chat: &recordingChatContract{routes: make(chan messaging.Inbound, 1), reply: "ok"},
})
if err != nil {
t.Fatalf("compose: %v", err)
}
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
started := make(chan error, 1)
go func() { started <- srv.Start(ctx) }()
t.Cleanup(srv.Stop)
failed := waitForState(t, srv, "webhook", status.StateFailed)
if failed.Detail == "" {
t.Error("a failed channel carries no detail; the operator cannot tell why it is down")
}
}
// TestChannelDescriptorsDeclareCapabilities pins the declarations the dashboard
// acts on. Reload is the one with a real consequence: a channel declaring it
// invites a button that must do something.
func TestChannelDescriptorsDeclareCapabilities(t *testing.T) {
descriptors := channelDescriptors([]channelInstance{
{name: "telegram", channel: fakeChannel{}},
{name: "email", channel: fakeChannel{}},
{name: "webhook", channel: fakeChannel{}},
})
if len(descriptors) != 3 {
t.Fatalf("descriptors = %+v, want one per composed channel", descriptors)
}
byID := map[string]status.Descriptor{}
for _, descriptor := range descriptors {
byID[descriptor.ID] = descriptor
}
if !byID["telegram"].ReloadSupported {
t.Error("telegram does not declare reload support, but it is the channel with a reload seam")
}
for _, id := range []string{"email", "webhook"} {
if byID[id].ReloadSupported {
t.Errorf("%s declares reload support with nothing backing it", id)
}
}
for id, descriptor := range byID {
if !descriptor.Configured {
t.Errorf("%s is composed but not declared configured", id)
}
}
}
// fakeChannel satisfies channels.Channel for descriptor tests, which read identity
// and capabilities only.
type fakeChannel struct{}
func (fakeChannel) Name() string { return "fake" }
func (fakeChannel) Stop(context.Context) error { return nil }
func (fakeChannel) ConfigSchema() json.RawMessage { return json.RawMessage(`{}`) }
func (fakeChannel) ValidateConfig(map[string]any) error { return nil }
func (fakeChannel) Start(context.Context, messaging.ChatContract, channels.Lifecycle) error {
return nil
}
+15 -1
View File
@@ -10,6 +10,7 @@ import (
"github.com/samcharles93/archie-core/internal/channels"
"github.com/samcharles93/archie-core/internal/channels/email"
"github.com/samcharles93/archie-core/internal/channels/status"
"github.com/samcharles93/archie-core/internal/channels/telegram"
"github.com/samcharles93/archie-core/internal/channels/webhook"
"github.com/samcharles93/archie-core/internal/config"
@@ -34,6 +35,10 @@ type channelInstance struct {
// Service manages the lifecycle of the extracted Messaging Service and its
// channel adapters.
type Service struct {
// status owns channel lifecycle facts, one entry per composed channel. It is
// the single writer channels report through (see lifecycleFor), and the
// producer a dashboard surface reads.
status *status.Manager
cfg ResolvedConfig
log *slog.Logger
chat messaging.ChatContract
@@ -89,6 +94,7 @@ func compose(ctx context.Context, d deps) (*Service, error) {
}
}
srv.status = status.NewManager(channelDescriptors(srv.channels))
return srv, nil
}
@@ -160,9 +166,17 @@ func (s *Service) Start(ctx context.Context) error {
c := ch
wg.Go(func() {
s.log.Info("starting channel", "name", c.name)
if err := c.channel.Start(ctx, s.chat, channels.Lifecycle{}); err != nil && ctx.Err() == nil {
if err := c.channel.Start(ctx, s.chat, s.lifecycleFor(c.name)); err != nil && ctx.Err() == nil {
// The channel could not run: say so on the operator's surface, not
// only in the log, which is the difference between a dashboard that
// shows a dead channel and one that shows nothing at all.
s.status.MarkFailed(c.name, err.Error())
s.log.Error("channel stopped with error", "name", c.name, "err", err)
return
}
// A channel that returns without an error has stopped, either because
// the service was asked to or because its own loop ended.
s.status.MarkStopped(c.name, "")
})
}