Documentation
¶
Overview ¶
Package presence is the business layer for E36 driver-agent identity/mailbox (design §6.2/§9). It owns the协作主体 (driver agent) registry and the inbox messaging primitives on top of the neutral jobstore tables (agent_presence / messages): register/heartbeat, online/offline TTL judgement, addressed message fan-out (direct / role: / broadcast) and prune.
Layering (G022): presence depends ONLY on jobstore (the data layer); it never imports the入口/编排 layers, and jobstore never imports presence (the records there are neutral structs). agent_id/agent_token are minted here, not by jobstore, so id/token policy lives in one place.
Index ¶
- Constants
- Variables
- type Agent
- type Message
- type RegisterInput
- type RegisterResult
- type Service
- func (s *Service) Configure(ttl, msgTTL time.Duration)
- func (s *Service) Deregister(agentID, token string) error
- func (s *Service) List(roleFilter, projectFilter string) ([]Agent, error)
- func (s *Service) ListInbox(agentID string, includeRead bool) ([]Message, error)
- func (s *Service) Poll(agentID, token string, ack bool) ([]Message, error)
- func (s *Service) Post(from, to, kind, body, ref string) (delivered int, err error)
- func (s *Service) Prune() (presenceN, msgN int, err error)
- func (s *Service) Register(in RegisterInput) (RegisterResult, error)
- func (s *Service) Role(agentID string) (string, bool)
Constants ¶
const ( KindTask = "task" KindNote = "note" KindAnswer = "answer" KindEscalation = "escalation" )
Message kinds (design §9). Kept as constants for callers; Post does not restrict kind (forward-compat with new kinds).
const ( StatusOnline = "online" StatusOffline = "offline" )
Status values surfaced by List (computed lazily from last_seen vs TTL).
const DefaultMessageTTL = 24 * time.Hour
DefaultMessageTTL bounds how long an undelivered/unread message lives before the prune sweeper may drop it (design §12: message TTL default). A read message is pruned regardless; this caps the unread tail so an agent that registers, gets messages, then never polls again does not pin rows forever.
const DefaultTTL = 90 * time.Second
DefaultTTL is how long after its last heartbeat a driver agent is still counted online (design §12: 90s). last_seen_at older than now-TTL ⇒ offline (lazily computed at read time, never written back).
Variables ¶
var ( // ErrUnknownAgent is returned when an agent_id is not in the registry. ErrUnknownAgent = errors.New("presence: unknown agent") // the registry (soft isolation, design §11 — not a cross-trust-domain auth). ErrUnauthorizedAgent = errors.New("presence: agent token mismatch") )
Functions ¶
This section is empty.
Types ¶
type Agent ¶
type Agent struct {
AgentID string `json:"agent_id"`
Name string `json:"name"`
Role string `json:"role,omitempty"`
ProjectKey string `json:"project_key,omitempty"`
Client string `json:"client,omitempty"`
Status string `json:"status"`
LastSeenAt int64 `json:"last_seen_at"`
}
Agent is the public projection of a registered driver agent (design §9). It deliberately omits agent_token (never returned by List/presence reads, §10). The snake_case json tags make it the single wire contract reused by both the httpapi handler (server projection) and internal/client (decode), mirroring how job.JobResult is shared across the transport.
type Message ¶
type Message struct {
ID string `json:"id"`
FromAgent string `json:"from_agent"`
ToSpec string `json:"to_spec,omitempty"`
Kind string `json:"kind"`
Body string `json:"body,omitempty"`
Ref string `json:"ref,omitempty"`
CreatedAt int64 `json:"created_at"`
}
Message is the public projection of an inbox message (design §9), omitting recipient/status bookkeeping the caller does not need. The snake_case json tags make it the single wire contract shared by httpapi and internal/client.
type RegisterInput ¶
type RegisterInput struct {
Name string
Role string
ProjectKey string
CallerID string
Client string
MetaJSON string
}
RegisterInput carries the self-reported registration fields. CallerID/Client are stamped by the httpapi handler (provenance, E34), not by the agent.
type RegisterResult ¶
type RegisterResult struct {
AgentID string `json:"agent_id"`
AgentToken string `json:"agent_token"`
}
RegisterResult is what register returns: the public address (agent_id) and the private capability handle (agent_token) the agent presents on poll/deregister. json tags make it the wire shape returned by the register endpoint.
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
Service is the presence/mailbox business layer. nowFn/ttl/msgTTL are injectable so tests can pin the clock and the online/expiry windows.
func NewService ¶
NewService builds a Service over the shared jobstore with production defaults (real clock, DefaultTTL, DefaultMessageTTL, crypto/rand ids).
func (*Service) Configure ¶
Configure overrides the online TTL and/or message TTL from config (E36 收尾). A non-positive duration is ignored, so an unset config field keeps the built-in default — making NewService the single source of truth for the defaults. Called once at serve startup before the Service handles traffic.
func (*Service) Deregister ¶
Deregister actively removes an agent from the registry after verifying its token. It is idempotent: an unknown agent is treated as already gone (nil).
func (*Service) List ¶
List returns the registry, lazily computing online/offline from last_seen vs TTL (never written back). roleFilter/projectFilter, when non-empty, restrict the result; agent_token is never included (design §10).
func (*Service) ListInbox ¶
ListInbox returns an agent's inbox messages WITHOUT consuming them (no MarkRead) or refreshing presence (no TouchPresence) — the P5 read-only observability view, distinct from Poll. includeRead=false lists only unread (matching Poll's default scope); includeRead=true also returns已读. No token check: it is an internal /inner-gated read (SR202); an unknown agent_id yields an empty list (the inbox query simply matches no rows).
func (*Service) Poll ¶
Poll returns the agent's unread messages, refreshing its heartbeat. The agent_token is verified (soft isolation); a mismatch yields ErrUnauthorizedAgent and an unknown id yields ErrUnknownAgent. When ack is true the returned messages are marked read (consumed); when false they are left unread (peek).
func (*Service) Post ¶
Post delivers a message addressed by `to` and returns how many inbox rows it created (fan-out, design §9). Addressing forms:
- direct agent_id → 1 row, stored in that agent's inbox even when offline (store-and-forward up to message TTL); unknown id → 0.
- "role:<name>" → 1 row PER online agent of that role (fan-out / notify-all).
- "role-one:<name>" → 1 row to ONE random online agent of that role (work-assignment); no online match → 0.
- "broadcast" → 1 row per online agent.
With no reachable recipient nothing is stored and delivered=0 is returned, so the sender (or supervisor) can retry — best-effort by design (§9/§12; role/broadcast queue-on-online is explicitly out of scope). from is the sender's agent_id (or "system"/"job:<id>"), stamped by the caller.
func (*Service) Prune ¶
Prune is the serve sweeper entry point (design §9): drop presence rows offline past the TTL window and messages that are read or past their TTL. Returns the counts removed.
func (*Service) Register ¶
func (s *Service) Register(in RegisterInput) (RegisterResult, error)
Register registers a new driver agent or renews an existing one. Idempotency (design §10): if an agent with the same name+caller already exists its agent_id (and agent_token) are reused and last_seen refreshed (续约); otherwise a fresh uuid + token are minted. The token is only ever returned here.
func (*Service) Role ¶
Role returns the registered role of a driver agent_id (监督派生作答闸 P3.1: the answer path grades a responder by its presence role). The bool is false for an unknown agent_id (pruned/never registered) so the caller treats it as "no role" — it does NOT consult the online TTL (a briefly-offline-but-registered sup must still be graded as a supervisor). It satisfies answerguard.RoleLookup structurally; presence stays import-free of answerguard.