* feat(gateway): give /status a real daemon-health surface Phase 2 of archie-core-wp9s. Phase 1 split the commands apart (health vs work) but left /status with one aggregate queue line and a static runtime block; it could not answer the questions an operator actually asks when something feels wrong. /status now reports, between the queue line and the runtime block: - Broker: the live state of this process's own NATS connection (eventbus/nats.Client.Connected), not a fresh dial -- a probe would report the probe's reachability, not the daemon's. - Containers: the pool's own active counter against the configured cap (Pool.Active/Cap), not a Docker listing, which would include containers this pool does not own. A zero cap means unlimited, so it is not shown as a ratio. - Channels: the channel manager's real lifecycle state, including a failed adapter's reason (the documented decision: read the existing manager rather than re-deriving health per adapter). - Chat model: last-known outcome of every chat-model call this process made, recorded once in sendChatTurn (the single choke point) and read back by /status. The second documented decision: never a live probe, so /status stays instant and reports what happened -- or says plainly that nothing has been attempted yet. - Last poll: when the most recent poll pass began, stamped on both poll paths (Run's single-identity loop and runIdentities' per-identity goroutines). A pass that hangs leaves the stamp stale, which is the signal; stamping completion would leave a wedged poller looking healthy. Truthful or absent: a section this process has no source for is omitted rather than rendered as a zero. The standalone Gateway owns no poll loop, pool or channel manager, so its /status reports broker and chat-model health only; aggregating across processes would need a new daemon RPC and is deliberately not built. Version stays out (/version owns it). /status and /tasks descriptions now describe what each command actually does on both published surfaces (Telegram menu/help and the shared specs), pinned by a test that also fails if the two surfaces drift. Sources are read through functions, not captured values: occupancy and channel state move, and the daemon is built after the gateways, so a source captured at construction would freeze /status on boot state. Left in place deliberately: the Runtime (provider/model) block, which Phase 1 flagged and which duplicates /model and /whoami. Removing it is a product call on a command Sam uses daily, not a mechanical follow-up. * docs(prds): record the two open /status health decisions as settled Both were flagged in PR #892 as needing the maintainer's call; both are now answered, and the PRD is the place a follow-up would look: - The Runtime (provider/model) block stays. It is the one line in /status the ticket's own rule says should not be there, but /status is read daily to see the active model at a glance, so the duplication is deliberate. Recorded as a settled product decision so it is not removed later as an oversight. - Health stays per-process. Pooling the daemon's and the Gateway's chat-model outcomes would need a new daemon<->gateway health RPC for one status line, and a per-process line is true where an aggregate would be a claim about a process the answering one cannot see. /agents' published description is still left to archie-core-mxls, unchanged.
165 lines
4.8 KiB
Go
165 lines
4.8 KiB
Go
package nats
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"log/slog"
|
|
|
|
"github.com/nats-io/nats.go"
|
|
"github.com/nats-io/nats.go/jetstream"
|
|
|
|
"github.com/samcharles93/archie-core/internal/eventbus"
|
|
)
|
|
|
|
// Compile-time proof that Client satisfies the broker-neutral contract.
|
|
// The interfaces live in internal/eventbus so domains can depend on the
|
|
// behaviour without importing this package.
|
|
var _ eventbus.Bus = (*Client)(nil)
|
|
|
|
// Client owns the NATS connection and its JetStream stream and consumer.
|
|
type Client struct {
|
|
conn *nats.Conn
|
|
js jetstream.JetStream
|
|
stream jetstream.Stream
|
|
consumer jetstream.Consumer
|
|
cfg Config
|
|
log *slog.Logger
|
|
}
|
|
|
|
// Connect dials the broker and provisions the stream and pull consumer. The
|
|
// stream uses file storage and the retention policy from Config.Retention
|
|
// (defaulting to work-queue for task distribution).
|
|
//
|
|
// On any failure the partially-built connection is closed before returning, so
|
|
// a failed Connect leaks nothing.
|
|
func Connect(ctx context.Context, cfg Config, log *slog.Logger) (*Client, error) {
|
|
if err := cfg.Validate(); err != nil {
|
|
return nil, err
|
|
}
|
|
cfg = cfg.withDefaults()
|
|
if log == nil {
|
|
log = slog.New(slog.DiscardHandler)
|
|
}
|
|
|
|
conn, err := dial(cfg)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// Every failure past this point must close conn. Cleared on success.
|
|
closeOnFail := conn.Close
|
|
defer func() {
|
|
if closeOnFail != nil {
|
|
closeOnFail()
|
|
}
|
|
}()
|
|
|
|
js, err := jetstream.New(conn)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("nats jetstream init: %w", err)
|
|
}
|
|
|
|
streamConfig := jetstream.StreamConfig{
|
|
Name: cfg.StreamName,
|
|
Subjects: cfg.Subjects,
|
|
Storage: jetstream.FileStorage,
|
|
Retention: *cfg.Retention,
|
|
Duplicates: cfg.DedupWindow,
|
|
}
|
|
// Limits are applied only when the composition explicitly sets them;
|
|
// leaving MaxAge nil keeps the stream unbounded exactly as before.
|
|
if cfg.MaxAge != nil {
|
|
streamConfig.MaxAge = *cfg.MaxAge
|
|
}
|
|
|
|
stream, err := js.CreateOrUpdateStream(ctx, streamConfig)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("nats create stream %q: %w", cfg.StreamName, err)
|
|
}
|
|
|
|
consumer, err := stream.CreateOrUpdateConsumer(ctx, jetstream.ConsumerConfig{
|
|
Name: cfg.ConsumerName,
|
|
Durable: cfg.ConsumerName,
|
|
FilterSubject: cfg.FilterSubject,
|
|
AckPolicy: jetstream.AckExplicitPolicy,
|
|
MaxDeliver: cfg.MaxDeliver,
|
|
AckWait: cfg.AckWait,
|
|
InactiveThreshold: cfg.InactiveTTL,
|
|
})
|
|
if err != nil {
|
|
return nil, fmt.Errorf("nats create consumer %q: %w", cfg.ConsumerName, err)
|
|
}
|
|
|
|
closeOnFail = nil
|
|
log.Info("nats connected",
|
|
"stream", cfg.StreamName,
|
|
"consumer", cfg.ConsumerName,
|
|
"url", conn.ConnectedUrl())
|
|
|
|
return &Client{
|
|
conn: conn,
|
|
js: js,
|
|
stream: stream,
|
|
consumer: consumer,
|
|
cfg: cfg,
|
|
log: log,
|
|
}, nil
|
|
}
|
|
|
|
// dial opens the raw connection, applying auth options from cfg.
|
|
func dial(cfg Config) (*nats.Conn, error) {
|
|
var opts []nats.Option
|
|
if cfg.Token != "" {
|
|
opts = append(opts, nats.Token(cfg.Token))
|
|
}
|
|
conn, err := nats.Connect(cfg.URL, opts...)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("nats connect %s: %w", cfg.URL, err)
|
|
}
|
|
return conn, nil
|
|
}
|
|
|
|
// Close shuts the connection down. It is safe to call on a nil client so
|
|
// callers holding an optional bus can defer it unconditionally.
|
|
func (c *Client) Close() {
|
|
if c == nil || c.conn == nil {
|
|
return
|
|
}
|
|
c.conn.Close()
|
|
c.log.Debug("nats connection closed")
|
|
}
|
|
|
|
// CoreConn exposes the raw connection for the NATS-specific RPC layers
|
|
// (forgerpc, worktreerpc, natsrpc) that register their own core-NATS
|
|
// subscriptions. The State Store is a gRPC contract, not a core-NATS RPC.
|
|
//
|
|
// This is the single sanctioned escape hatch and exists only because those
|
|
// packages are themselves NATS infrastructure, not domain code. Domain and
|
|
// application packages must use [Publisher], [Consumer] or [Requester]
|
|
// instead; taking the connection there would put SDK types back into their
|
|
// imports, which is what this package exists to prevent.
|
|
func (c *Client) CoreConn() (*nats.Conn, error) { return c.connection() }
|
|
|
|
// connection returns the live connection, or ErrNotConnected.
|
|
func (c *Client) connection() (*nats.Conn, error) {
|
|
if c == nil || c.conn == nil || c.conn.IsClosed() {
|
|
return nil, eventbus.ErrNotConnected
|
|
}
|
|
return c.conn, nil
|
|
}
|
|
|
|
// Connected reports whether this client's connection to the broker is live.
|
|
//
|
|
// It reads the connection the client already holds. It deliberately does not
|
|
// dial to check reachability: a fresh connection would report the dial's
|
|
// success rather than this process's own bus being up, and it would put a
|
|
// network round trip with its own timeout inside a caller that may be a chat
|
|
// command handler.
|
|
func (c *Client) Connected() bool {
|
|
conn, err := c.connection()
|
|
if err != nil {
|
|
return false
|
|
}
|
|
return conn.IsConnected()
|
|
}
|