supervisor

package
v0.70.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 3, 2026 License: MIT Imports: 17 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ActorPool

type ActorPool struct {
	// contains filtered or unexported fields
}

ActorPool manages the lifecycle of server actors and provides stats for Supervisor. This replaces UpstreamAdapter with direct Actor integration (Phase 7.2).

func NewActorPool

func NewActorPool(manager *upstream.Manager, logger *zap.Logger) *ActorPool

NewActorPool creates a new actor pool.

func (*ActorPool) AddServer

func (p *ActorPool) AddServer(name string, cfg *config.ServerConfig) error

AddServer creates and starts an actor for the given server. If the actor already exists, it updates the configuration.

func (*ActorPool) Close

func (p *ActorPool) Close()

Close cleans up the actor pool.

func (*ActorPool) ConnectAll

func (p *ActorPool) ConnectAll(ctx context.Context) error

ConnectAll sends connect commands to all actors.

func (*ActorPool) ConnectServer

func (p *ActorPool) ConnectServer(ctx context.Context, name string) error

ConnectServer sends a connect command to an actor.

func (*ActorPool) DisconnectServer

func (p *ActorPool) DisconnectServer(name string) error

DisconnectServer sends a disconnect command to an actor.

func (*ActorPool) GetAllStates

func (p *ActorPool) GetAllStates() map[string]*ServerState

GetAllStates returns the current state of all servers.

func (*ActorPool) GetServerState

func (p *ActorPool) GetServerState(name string) (*ServerState, error)

GetServerState returns the current state of a server from its actor.

func (*ActorPool) IsUserLoggedOut

func (p *ActorPool) IsUserLoggedOut(name string) bool

IsUserLoggedOut returns true if the user explicitly logged out from the server. This prevents automatic reconnection after explicit logout.

func (*ActorPool) RemoveServer

func (p *ActorPool) RemoveServer(name string) error

RemoveServer stops and removes an actor.

func (*ActorPool) Subscribe

func (p *ActorPool) Subscribe() <-chan Event

Subscribe returns a channel that receives supervisor events.

func (*ActorPool) Unsubscribe

func (p *ActorPool) Unsubscribe(ch <-chan Event)

Unsubscribe removes a subscriber channel.

type ActorPoolSimple

type ActorPoolSimple struct {
	// contains filtered or unexported fields
}

ActorPoolSimple is a simplified facade over UpstreamManager that delegates all operations. Phase 7.3: Avoids double lifecycle management by using UpstreamManager's existing client management.

func NewActorPoolSimple

func NewActorPoolSimple(manager *upstream.Manager, logger *zap.Logger) *ActorPoolSimple

NewActorPoolSimple creates a simplified actor pool that delegates to UpstreamManager.

func (*ActorPoolSimple) AddServer

func (p *ActorPoolSimple) AddServer(name string, cfg *config.ServerConfig) error

AddServer adds a server configuration to the manager.

func (*ActorPoolSimple) Close

func (p *ActorPoolSimple) Close()

Close cleans up the pool.

func (*ActorPoolSimple) ConnectAll

func (p *ActorPoolSimple) ConnectAll(ctx context.Context) error

ConnectAll tells the manager to connect all servers.

func (*ActorPoolSimple) ConnectServer

func (p *ActorPoolSimple) ConnectServer(ctx context.Context, name string) error

ConnectServer tells the manager to connect a server.

func (*ActorPoolSimple) DisconnectServer

func (p *ActorPoolSimple) DisconnectServer(name string) error

DisconnectServer tells the manager to disconnect a server.

func (*ActorPoolSimple) GetAllStates

func (p *ActorPoolSimple) GetAllStates() map[string]*ServerState

GetAllStates returns the current state of all servers from the manager.

func (*ActorPoolSimple) GetServerState

func (p *ActorPoolSimple) GetServerState(name string) (*ServerState, error)

GetServerState returns the current state of a server from the manager. Phase 7.1 FIX: Fetches tools for the specific server to avoid blocking all servers.

func (*ActorPoolSimple) IsUserLoggedOut

func (p *ActorPoolSimple) IsUserLoggedOut(name string) bool

IsUserLoggedOut returns true if the user explicitly logged out from the server. This prevents automatic reconnection after explicit logout.

func (*ActorPoolSimple) RemoveServer

func (p *ActorPoolSimple) RemoveServer(name string) error

RemoveServer removes a server from the manager.

func (*ActorPoolSimple) SendNotification

func (p *ActorPoolSimple) SendNotification(notification *upstream.Notification)

SendNotification implements upstream.NotificationHandler interface

func (*ActorPoolSimple) Subscribe

func (p *ActorPoolSimple) Subscribe() <-chan Event

Subscribe returns a channel that receives supervisor events.

func (*ActorPoolSimple) Unsubscribe

func (p *ActorPoolSimple) Unsubscribe(ch <-chan Event)

Unsubscribe removes a subscriber channel.

type DiscoveryCapture added in v0.67.0

type DiscoveryCapture struct {
	Generation uint64
	Epoch      int64
}

DiscoveryCapture binds a discovery result to the connection it was listed under (Spec 105 FR-009 "stale generation"). A discovery caller takes it BEFORE listing a server's tools and hands it back to the publish call:

  • Generation is the Supervisor's own edge counter (ServerState.ConnectionGeneration); the publish is dropped when it has moved on (astra r1 I2).
  • Epoch is the live client's connection-instance token (managed.Client.ConnectionEpoch) at capture time; it is stamped on the snapshot with the result so every identity read can tell whether the stamp still describes the live connection (astra r2 C3).

type Event

type Event struct {
	Type       EventType
	ServerName string
	Timestamp  time.Time
	Payload    map[string]interface{}
}

Event represents a supervisor lifecycle event.

type EventType

type EventType string

EventType represents supervisor lifecycle events.

const (
	// EventServerAdded is emitted when a new server is added to desired state
	EventServerAdded EventType = "server.added"

	// EventServerRemoved is emitted when a server is removed from desired state
	EventServerRemoved EventType = "server.removed"

	// EventServerUpdated is emitted when a server's desired config changes
	EventServerUpdated EventType = "server.updated"

	// EventServerConnected is emitted when a server successfully connects
	EventServerConnected EventType = "server.connected"

	// EventServerDisconnected is emitted when a server disconnects
	EventServerDisconnected EventType = "server.disconnected"

	// EventServerStateChanged is emitted when a server's connection state changes
	EventServerStateChanged EventType = "server.state_changed"

	// EventReconciliationComplete is emitted after a reconciliation cycle completes
	EventReconciliationComplete EventType = "reconciliation.complete"

	// EventReconciliationFailed is emitted when reconciliation fails
	EventReconciliationFailed EventType = "reconciliation.failed"
)

type ReconcileAction

type ReconcileAction string

ReconcileAction describes what action the supervisor should take.

const (
	// ActionNone means no action is needed
	ActionNone ReconcileAction = "none"

	// ActionConnect means the server should be connected
	ActionConnect ReconcileAction = "connect"

	// ActionDisconnect means the server should be disconnected
	ActionDisconnect ReconcileAction = "disconnect"

	// ActionReconnect means the server should be disconnected and reconnected
	ActionReconnect ReconcileAction = "reconnect"

	// ActionRemove means the server should be removed
	ActionRemove ReconcileAction = "remove"
)

type ReconcilePlan

type ReconcilePlan struct {
	Actions   map[string]ReconcileAction // server name -> action
	Timestamp time.Time
	Reason    string
}

ReconcilePlan describes the actions to take during reconciliation.

type ServerState

type ServerState struct {
	// Desired state from configuration
	Name        string
	Config      *config.ServerConfig
	Enabled     bool
	Quarantined bool

	// Actual state from upstream manager
	Connected      bool
	ConnectionInfo *types.ConnectionInfo
	LastSeen       time.Time
	ToolCount      int
	Tools          []*config.ToolMetadata // Phase 7.1: Cached tools for lock-free reads
	// ToolsDiscovered mirrors stateview.ServerStatus.ToolsDiscovered on the
	// retained snapshot: set when discovery publishes a tool set for the
	// server (even an empty one). It is PER CONNECTION: cleared on every
	// connection-state edge (disconnect AND connect) and whenever reconcile
	// observes the server disconnected, so a stale stamp can never certify
	// the previous connection's retained Tools for a new connection (Spec 105
	// FR-009, research D4; astra r1 I1/I4).
	ToolsDiscovered bool
	// ConnectionGeneration counts the server's connection-state edges
	// (bumped on every connect / disconnect event and on a disconnect
	// reconcile observes). A discovery result is published only if the
	// generation it was captured under is still current, so a result whose
	// capture straddled a reconnect is dropped instead of landing on the new
	// connection (Spec 105 FR-009 "stale generation"; astra r1 I2).
	ConnectionGeneration uint64
	// ConnectionEpoch is the live client's connection-instance token
	// (managed.Client.ConnectionEpoch) as the adapter last reported it: set
	// on the states the adapter builds (ActorPoolSimple) and recorded on the
	// retained snapshot by every event and reconcile pass. A reconcile that
	// finds the live token moved since the last observation has missed a
	// connection edge (dropped events) and treats it as one: marker cleared,
	// generation bumped, rediscovery kicked (astra r2 C3). Zero when the
	// adapter reports no token (unit fixtures).
	ConnectionEpoch int64
	// DiscoveryEpoch is the ConnectionEpoch the current discovery stamp was
	// captured under (DiscoveryCapture.Epoch), published together with
	// ToolsDiscovered and mirrored to stateview.ServerStatus.DiscoveryEpoch,
	// which identity resolution compares with the live client's token. Zero
	// while no discovery has been published for this connection.
	DiscoveryEpoch int64

	// Reconciliation metadata
	DesiredVersion int64 // Config version that defines this desired state
	LastReconcile  time.Time
	ReconcileCount int
}

ServerState represents the desired and actual state of an upstream server.

type ServerStateSnapshot

type ServerStateSnapshot struct {
	Servers   map[string]*ServerState
	Timestamp time.Time
	Version   int64 // Monotonically increasing
}

ServerStateSnapshot is an immutable view of all server states.

func (*ServerStateSnapshot) Clone

Clone creates a deep copy of the snapshot.

type Supervisor

type Supervisor struct {
	// contains filtered or unexported fields
}

Supervisor manages the desired vs actual state reconciliation for upstream servers. It subscribes to config changes and emits events when server states change.

func New

func New(configSvc *configsvc.Service, upstream UpstreamInterface, logger *zap.Logger) *Supervisor

New creates a new supervisor.

func (*Supervisor) CanInspect

func (s *Supervisor) CanInspect(serverName string) (bool, string, time.Duration)

CanInspect checks if inspection is allowed for a server (circuit breaker) Returns (allowed bool, reason string, cooldownRemaining time.Duration)

func (*Supervisor) CurrentErrorCodes added in v0.66.0

func (s *Supervisor) CurrentErrorCodes() map[string]int

CurrentErrorCodes returns the standing diagnostic state of this install: stable MCPX_* code -> number of configured servers currently in that state. Returns nil when nothing is failing.

This is the companion to the edge-triggered counter above and exists because edge-triggering alone would DELETE the "installs currently affected" signal: diagnostics.error_code_counts_24h decays over a 24h window, carries omitempty, and the whole Diagnostics object is omitted when isZero(). A permanently parked install would emit one event and then vanish from the payload — trading an inflated number for a missing one, which reads as zero.

Anonymity: the map is keyed exclusively by the fixed MCPX_ catalog (~30 codes, prefix-checked here as defense in depth) and valued by a count. It carries no server name, URL, command, or free text. Only enabled, non-quarantined servers are counted — a server the user disabled or quarantined is not "currently affected".

func (*Supervisor) CurrentSnapshot

func (s *Supervisor) CurrentSnapshot() *ServerStateSnapshot

CurrentSnapshot returns the current state snapshot (lock-free read).

func (*Supervisor) DiscoveryGeneration added in v0.67.0

func (s *Supervisor) DiscoveryGeneration(serverName string) DiscoveryCapture

DiscoveryGeneration returns one server's current DiscoveryCapture (a zero Generation for a server the snapshot does not hold — the live token is still captured, so the StateView write such a server gets carries it); see DiscoveryGenerations.

func (*Supervisor) DiscoveryGenerations added in v0.67.0

func (s *Supervisor) DiscoveryGenerations() map[string]DiscoveryCapture

DiscoveryGenerations returns every known server's current DiscoveryCapture — the Supervisor's ConnectionGeneration and the live client's connection token. A discovery caller captures it BEFORE listing tools and hands it back to the publish call, which drops any server whose generation has moved on (Spec 105 FR-009 "stale generation"; astra r1 I2) and stamps the token on the result (astra r2 C3).

func (*Supervisor) GetInspectionStats

func (s *Supervisor) GetInspectionStats(serverName string) (failures int, inCooldown bool, cooldownRemaining time.Duration)

GetInspectionStats returns inspection failure statistics for a server

func (*Supervisor) IsInspectionExempted

func (s *Supervisor) IsInspectionExempted(serverName string) bool

IsInspectionExempted checks if a server has an active inspection exemption. Automatically cleans up expired exemptions.

func (*Supervisor) MarkServersToolsDiscovered added in v0.67.0

func (s *Supervisor) MarkServersToolsDiscovered(serverNames []string, gens map[string]DiscoveryCapture)

MarkServersToolsDiscovered stamps ToolsDiscovered on the named servers WITHOUT touching their tool sets (Spec 105 FR-009, research D4). It is the marker for a discovery pass that completed with zero tools on a path that deliberately keeps whatever tool set the server already has — the lenient reactive connect path and the sweep, which must not wipe a server's tools on a transient empty result. A server that has never published a tool set is thereby "discovered, nothing served": every name on it resolves as absent (refused) rather than lingering in the connect→discovery window.

A server that still HOLDS a tool set is deliberately NOT stamped (astra r1 I1): the disconnect clears the marker but keeps the retained Tools (MCP-2094, restored on reconnect for counts and listings), so an unstamped server with tools is carrying the PREVIOUS connection's discovery result — and this connection listed none of it. Stamping would certify names this connection never served; wiping the set would break the lenient path's "never wipe on a transient empty result" contract. It stays in the discovery window (refusal says "retry") until a non-empty or authoritative pass replaces the set. gens is the DiscoveryGenerations() capture taken before the list; a server whose generation moved on is skipped.

func (*Supervisor) ReconcileQuiescent added in v0.70.0

func (s *Supervisor) ReconcileQuiescent() bool

ReconcileQuiescent reports whether the delayed startup reconciliation has dispatched and no reconcile action goroutine is in flight.

func (*Supervisor) RecordInspectionFailure

func (s *Supervisor) RecordInspectionFailure(serverName string)

RecordInspectionFailure records an inspection failure for circuit breaker

func (*Supervisor) RecordInspectionSuccess

func (s *Supervisor) RecordInspectionSuccess(serverName string)

RecordInspectionSuccess records a successful inspection, resetting failure counter

func (*Supervisor) RefreshServerToolsFromDiscovery added in v0.67.0

func (s *Supervisor) RefreshServerToolsFromDiscovery(serverName string, tools []*config.ToolMetadata, gen DiscoveryCapture) (published bool, err error)

RefreshServerToolsFromDiscovery publishes ONE server's completed discovery result — tools may be empty — into the Supervisor snapshot and the StateView, stamping ToolsDiscovered for it (Spec 105 FR-009, research D4). This is the per-server discovery path (connect, tools/list_changed, the operator's refresh), where an empty result is authoritative: the server really lists no tools, so every name on it must resolve as undiscovered rather than fall through to the connect→discovery window's fallback.

gen is the server's DiscoveryGeneration() captured before the tools were listed; published reports whether the result landed (false: the connection generation moved on, the result was dropped and the caller should re-list).

func (*Supervisor) RefreshToolsFromDiscovery

func (s *Supervisor) RefreshToolsFromDiscovery(tools []*config.ToolMetadata, gens map[string]DiscoveryCapture) (stale []string, err error)

RefreshToolsFromDiscovery updates both the Supervisor snapshot and StateView with tools from background discovery. This is called after DiscoverAndIndexTools completes to keep the cached tool lists in sync.

Only servers that contributed at least one tool are touched: a server absent from the flat list cannot be told apart from one that listed zero tools, so it keeps whatever the previous pass published. A single server whose discovery completed with ZERO tools is published through RefreshServerToolsFromDiscovery, which names the server explicitly.

gens is the DiscoveryGenerations() capture taken before the tools were listed: a server whose connection generation has moved on since is NOT published (its result belongs to a previous connection) and is returned in stale, so the caller can re-list it under the current connection.

func (*Supervisor) RequestInspectionExemption

func (s *Supervisor) RequestInspectionExemption(serverName string, duration time.Duration) error

RequestInspectionExemption grants temporary connection permission for a quarantined server. This allows security inspection to temporarily connect to quarantined servers. Triggers immediate reconciliation to connect the server.

func (*Supervisor) RevokeInspectionExemption

func (s *Supervisor) RevokeInspectionExemption(serverName string)

RevokeInspectionExemption revokes the temporary connection permission and triggers disconnection.

func (*Supervisor) SetErrorCodeNotifier added in v0.30.0

func (s *Supervisor) SetErrorCodeNotifier(fn func(code string))

SetErrorCodeNotifier registers a callback that fires whenever a diagnostic error code is classified and attached to a server (Spec 044 Phase H). The callback receives the stable MCPX_* code string and is invoked SYNCHRONOUSLY at the classification site (Spec 080 FR-012: the pre-churn last_error_code must be durable before a crash can follow the classification). The callback must be fast (sub-ms), must not call back into the Supervisor, and must NOT spawn goroutines that outlive the call: Runtime.Close relies on Supervisor.Stop() as a barrier — once Stop returns, no callback-driven DB write may remain in flight, or it could land after the clean-shutdown marker resolves or after the DB closes (Spec 080 FR-010).

func (*Supervisor) SetOnServerConnectedCallback

func (s *Supervisor) SetOnServerConnectedCallback(callback func(serverName string))

SetOnServerConnectedCallback sets a callback to be invoked when a server connects. This allows for reactive tool discovery instead of relying on periodic polling.

func (*Supervisor) Start

func (s *Supervisor) Start()

Start begins the supervisor's reconciliation loop.

func (*Supervisor) StateView

func (s *Supervisor) StateView() *stateview.View

StateView returns the read-only state view (Phase 4). This provides a lock-free view of server statuses for API consumers.

func (*Supervisor) Stop

func (s *Supervisor) Stop()

Stop gracefully stops the supervisor.

func (*Supervisor) Subscribe

func (s *Supervisor) Subscribe() <-chan Event

Subscribe returns a channel that receives supervisor events.

func (*Supervisor) ToolTierGeneration added in v0.70.0

func (s *Supervisor) ToolTierGeneration() uint64

ToolTierGeneration returns the Spec 108 FR-027 counter bumped once per publishDiscoveredTools call — a coarse, whole-fleet signal that some server's discovered tool set (and therefore some tool's effective annotations) may have changed since a caller last read it. Lock-free.

func (*Supervisor) Unsubscribe

func (s *Supervisor) Unsubscribe(ch <-chan Event)

Unsubscribe removes a subscriber.

type UpstreamInterface

type UpstreamInterface interface {
	AddServer(name string, cfg *config.ServerConfig) error
	RemoveServer(name string) error
	ConnectServer(ctx context.Context, name string) error
	DisconnectServer(name string) error
	ConnectAll(ctx context.Context) error
	GetServerState(name string) (*ServerState, error)
	GetAllStates() map[string]*ServerState
	IsUserLoggedOut(name string) bool // Returns true if user explicitly logged out (prevents auto-reconnect)
	Subscribe() <-chan Event
	Unsubscribe(ch <-chan Event)
	Close()
}

UpstreamInterface defines the interface for upstream adapters.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL