diff --git a/internal/app/archied/gateway.go b/internal/app/archied/gateway.go index 7eb8430fd..825eeb05d 100644 --- a/internal/app/archied/gateway.go +++ b/internal/app/archied/gateway.go @@ -119,8 +119,21 @@ func RunGateway(ctx context.Context, options GatewayOptions) error { if err != nil { return fmt.Errorf("listen for gateway: %w", err) } + return b.serveGatewayListener(ctx, listener, loopback, contract, opts) +} + +// serveGatewayListener is the serving tail of RunGateway: the listener is +// bound, the process declares itself serving, and the chat contract answers +// until ctx ends. +func (b *boot) serveGatewayListener(ctx context.Context, listener net.Listener, loopback bool, contract gateway.ChatContract, opts []grpc.ServerOption) error { defer listener.Close() b.log.Info("archie-gateway running", "addr", listener.Addr().String(), "token_required", !loopback) + // Boot is over and this listener is about to accept: the same fact + // systemd's READY=1 asserts, so the announcement goes out here rather than + // from a second notion of "started" (archie-core-1174). Not later: Serve + // begins accepting the moment it is called, and a unit whose + // TimeoutStartSec expires first would restart a healthy process. + b.announceReady() return serveGateway(ctx, listener, contract, b.chatSessionStore, opts) } diff --git a/internal/app/archied/gateway_test.go b/internal/app/archied/gateway_test.go index a8c4ad1fd..024b815dd 100644 --- a/internal/app/archied/gateway_test.go +++ b/internal/app/archied/gateway_test.go @@ -1,6 +1,20 @@ package archied -import "testing" +import ( + "context" + "log/slog" + "net" + "testing" + "time" + + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" + + pb "github.com/samcharles93/archie-core/internal/contracts/gateway/v1" + "github.com/samcharles93/archie-core/internal/domain/messaging" + "github.com/samcharles93/archie-core/internal/domain/taskactions" + "github.com/samcharles93/archie-core/internal/taskstate" +) func TestGatewayServerOptsLoopbackIsInsecure(t *testing.T) { opts, loopback, err := gatewayServerOpts("127.0.0.1:8585", "") @@ -36,3 +50,87 @@ func TestGatewayServerOptsMalformedListen(t *testing.T) { t.Fatal("malformed listen address should error") } } + +// stubGatewayContract satisfies messaging.ChatContract with zero values: the +// serve test exercises the listener, the READY announcement and one read RPC, +// not the chat runtime. +type stubGatewayContract struct{} + +func (stubGatewayContract) Snapshot(context.Context) (messaging.ChatSnapshot, error) { + return messaging.ChatSnapshot{}, nil +} + +func (stubGatewayContract) GetSession(context.Context, string) (messaging.SessionContext, bool, error) { + return messaging.SessionContext{}, false, nil +} + +func (stubGatewayContract) RecentMessages(context.Context, string, int) ([]messaging.Message, error) { + return nil, nil +} + +func (stubGatewayContract) RecentTurns(context.Context, string, int) ([]messaging.TurnRecord, error) { + return nil, nil +} + +func (stubGatewayContract) Route(context.Context, messaging.Inbound) (messaging.ChatReply, error) { + return messaging.ChatReply{}, nil +} + +func (stubGatewayContract) Stream(context.Context, messaging.Inbound) (<-chan messaging.ChatEvent, error) { + return nil, nil +} + +func (stubGatewayContract) Cancel(context.Context, string) (messaging.ChatCancellation, error) { + return messaging.ChatCancellation{}, nil +} + +func (stubGatewayContract) SetPersona(context.Context, string, string) (bool, error) { + return false, nil +} + +func (stubGatewayContract) ApplyTaskAction(context.Context, string, int64, taskstate.Action) (messaging.TaskActionResult, error) { + return messaging.TaskActionResult{}, nil +} + +func (stubGatewayContract) ApplyOperatorTaskAction(context.Context, taskactions.Actor, int64, taskstate.Action) (messaging.TaskActionResult, error) { + return messaging.TaskActionResult{}, nil +} + +// TestGatewayServingAnnouncesReady: archie-gateway run as a Type=notify unit +// must send READY=1 at the moment it declares itself serving, or systemd kills +// a healthy process once TimeoutStartSec expires (archie-core-1174). The +// announcement is judged against the same evidence archied's run loop uses: +// the contract answers over the bound listener, so READY asserts a serving +// process rather than a bound socket. +func TestGatewayServingAnnouncesReady(t *testing.T) { + listener := newNotifyListener(t) + b := &boot{log: slog.New(slog.DiscardHandler)} + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + + ln, err := (&net.ListenConfig{}).Listen(ctx, "tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen: %v", err) + } + + serveCh := make(chan error, 1) + go func() { serveCh <- b.serveGatewayListener(ctx, ln, true, stubGatewayContract{}, nil) }() + + if !listener.waitForState(t, 5*time.Second, readyState) { + t.Fatal("no READY=1 datagram within 5s of the Gateway serving") + } + + conn, err := grpc.NewClient("passthrough:///"+ln.Addr().String(), grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatalf("dial: %v", err) + } + defer conn.Close() + if _, err := pb.NewChatServiceClient(conn).Snapshot(t.Context(), &pb.SnapshotRequest{}); err != nil { + t.Fatalf("Snapshot over gRPC: %v", err) + } + + cancel() + if err := <-serveCh; err != nil { + t.Fatalf("serveGatewayListener returned: %v", err) + } +} diff --git a/internal/app/archied/sd_notify.go b/internal/app/archied/sd_notify.go index 1ca5f8154..ea42accec 100644 --- a/internal/app/archied/sd_notify.go +++ b/internal/app/archied/sd_notify.go @@ -95,11 +95,20 @@ func sendNotify(addr, state string) error { } // announceReady tells systemd the daemon has finished starting. It is called at -// the moment the process declares itself serving (runLoop, next to -// healthSurface.markServing), which is the same fact READY=1 asserts: boot is -// over and the run loop is about to take over. +// the moment a process declares itself serving: the daemon's run loop (next to +// healthSurface.markServing), and the serve steps of archie-gateway and +// archie-state-store (archie-core-1174), which have health surfaces of their +// own and would otherwise hang a Type=notify unit until TimeoutStartSec while +// perfectly healthy. func (b *boot) announceReady() { - newNotifier(os.Getenv, b.log).send(readyState) + notifyReady(b.log) +} + +// notifyReady is announceReady without the boot: the Gateway's serving tail +// runs on a boot it owns, but a free helper keeps the announcement one call +// rather than a second notion of "started" on each surface. +func notifyReady(log *slog.Logger) { + newNotifier(os.Getenv, log).send(readyState) } // startWatchdog arms the heartbeat sampler for the daemon's run loop. It does diff --git a/internal/app/archied/sd_notify_test.go b/internal/app/archied/sd_notify_test.go index bd2aedcf2..cf9e460f8 100644 --- a/internal/app/archied/sd_notify_test.go +++ b/internal/app/archied/sd_notify_test.go @@ -17,6 +17,7 @@ import ( "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/daemon" "github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore" + "github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgtest" ) // notifyRecorder captures every record at every level. The other recording @@ -119,6 +120,28 @@ func countState(states []string, want string) int { return n } +// waitForState reads datagrams until one carries want or the window closes. +// The states drain above collects a window's worth; a boot-path test waiting +// for one state returns as soon as it arrives. +func (l *notifyListener) waitForState(t *testing.T, window time.Duration, want string) bool { + t.Helper() + deadline := time.Now().Add(window) + buf := make([]byte, 1024) + for time.Now().Before(deadline) { + if err := l.conn.SetReadDeadline(time.Now().Add(50 * time.Millisecond)); err != nil { + t.Fatalf("set notify read deadline: %v", err) + } + n, _, err := l.conn.ReadFromUnix(buf) + if err != nil { + continue + } + if string(buf[:n]) == want { + return true + } + } + return false +} + // newNotifyTestBoot builds the composition the notify path reads: a boot whose // config holder supplies the run loop's poll cadence, and a real daemon whose // own poll loop stamps the progress marker the heartbeat sampler samples. @@ -363,3 +386,36 @@ func TestNotifySocketFailureIsNotFatal(t *testing.T) { t.Errorf("an unusable notify socket logged %d errors, want none: %v", len(errs), errs) } } + +// TestStateStoreBootAnnouncesReady: archie-state-store run as a Type=notify +// unit must send READY=1 once its boot is over and it is serving the contract, +// or systemd kills a healthy process once TimeoutStartSec expires +// (archie-core-1174). The real RunStateStore composition drives it, over a +// real State Store database, the way the provider-seeding boot test does. +func TestStateStoreBootAnnouncesReady(t *testing.T) { + listener := newNotifyListener(t) + url := pgtest.URL(t) + path := filepath.Join(t.TempDir(), "config.toml") + body := fmt.Sprintf("bot_user = 'archie'\ndatabase_url = %q\n", url) + if err := os.WriteFile(path, []byte(body), 0o600); err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + errCh := make(chan error, 1) + go func() { errCh <- RunStateStore(ctx, StateStoreOptions{Config: path, Listen: "127.0.0.1:0"}) }() + + if !listener.waitForState(t, 15*time.Second, readyState) { + select { + case bootErr := <-errCh: + t.Fatalf("RunStateStore exited before announcing ready: %v", bootErr) + default: + t.Fatal("no READY=1 datagram within 15s of boot") + } + } + + cancel() + if err := <-errCh; err != nil && !errors.Is(err, context.Canceled) { + t.Fatalf("RunStateStore shutdown: %v", err) + } +} diff --git a/internal/app/archied/state_store.go b/internal/app/archied/state_store.go index 66ae01e8e..0bbfff103 100644 --- a/internal/app/archied/state_store.go +++ b/internal/app/archied/state_store.go @@ -146,6 +146,14 @@ func RunStateStore(ctx context.Context, options StateStoreOptions) error { //nol if err := b.startOptionalSurfaces(ctx, options); err != nil { return err } + // Boot is over and every listener this process serves is bound: the gRPC + // contract below and, when -ready-addr asked for one, the readiness HTTP + // surface. systemd's READY=1 asserts the same fact, so the announcement + // goes out here rather than from a second notion of "started" + // (archie-core-1174). Not earlier: a readiness surface that fails to bind + // fails the boot, and READY must not precede it. Not later: Serve begins + // accepting the moment it is called. + b.announceReady() deps := b.stateStoreDeps(grants) deps.ControlPlane = control