package archiemessaging import ( "context" "encoding/json" "log/slog" "net" "path/filepath" "testing" "time" "github.com/samcharles93/archie-core/internal/channels" "github.com/samcharles93/archie-core/internal/domain/messaging" ) // gatedChannel reports Running only once bind is closed, standing in for a // channel whose listener has not bound yet. type gatedChannel struct{ bind chan struct{} } func (c *gatedChannel) Name() string { return "gated" } func (c *gatedChannel) Start(ctx context.Context, _ messaging.ChatContract, lifecycle channels.Lifecycle) error { select { case <-ctx.Done(): return nil case <-c.bind: } lifecycle.Running() <-ctx.Done() return nil } func (c *gatedChannel) Stop(context.Context) error { return nil } func (c *gatedChannel) ConfigSchema() json.RawMessage { return nil } func (c *gatedChannel) ValidateConfig(map[string]any) error { return nil } // READY=1 must not reach systemd before every channel has bound, or a channel // that then fails to bind is reported ready. func TestReadyWaitsForChannelsToBind(t *testing.T) { addr := filepath.Join(t.TempDir(), "s") sock, err := net.ListenUnixgram("unixgram", &net.UnixAddr{Name: addr, Net: "unixgram"}) if err != nil { t.Fatal(err) } t.Cleanup(func() { _ = sock.Close() }) t.Setenv("NOTIFY_SOCKET", addr) ch := &gatedChannel{bind: make(chan struct{})} inst := &channelInstance{name: "gated", channel: ch} srv, err := compose(context.Background(), deps{Log: slog.Default(), ExtensionChannels: []*channelInstance{inst}}) if err != nil { t.Fatalf("compose: %v", err) } ctx, cancel := context.WithCancel(context.Background()) t.Cleanup(cancel) go func() { _ = srv.Start(ctx) }() read := func(wait time.Duration) string { _ = sock.SetReadDeadline(time.Now().Add(wait)) buf := make([]byte, 64) n, err := sock.Read(buf) if err != nil { return "" } return string(buf[:n]) } if got := read(200 * time.Millisecond); got != "" { t.Fatalf("announced %q before the channel bound", got) } close(ch.bind) if got := read(5 * time.Second); got != "READY=1" { t.Fatalf("after bind got %q, want READY=1", got) } }