presence

package
v0.152.2 Latest Latest
Warning

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

Go to latest
Published: Oct 13, 2026 License: MIT Imports: 7 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

View Source
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).

View Source
const (
	StatusOnline  = "online"
	StatusOffline = "offline"
)

Status values surfaced by List (computed lazily from last_seen vs TTL).

View Source
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.

View Source
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

View Source
var (
	// ErrUnknownAgent is returned when an agent_id is not in the registry.
	ErrUnknownAgent = errors.New("presence: unknown agent")
	// ErrUnauthorizedAgent is returned when the presented agent_token does not match
	// 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

func NewService(store *jobstore.Store) *Service

NewService builds a Service over the shared jobstore with production defaults (real clock, DefaultTTL, DefaultMessageTTL, crypto/rand ids).

func (*Service) Configure

func (s *Service) Configure(ttl, msgTTL time.Duration)

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

func (s *Service) Deregister(agentID, token string) error

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

func (s *Service) List(roleFilter, projectFilter string) ([]Agent, error)

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

func (s *Service) ListInbox(agentID string, includeRead bool) ([]Message, error)

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

func (s *Service) Poll(agentID, token string, ack bool) ([]Message, error)

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

func (s *Service) Post(from, to, kind, body, ref string) (delivered int, err error)

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

func (s *Service) Prune() (presenceN, msgN int, err error)

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

func (s *Service) Role(agentID string) (string, bool)

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.

Jump to

Keyboard shortcuts

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