Documentation
¶
Overview ¶
Package agent is the home's side of the cluster channel (Epic 31 phase 2, specs/epics/31-multi-instance/design-agent.md): the authenticated, encrypted WebSocket every Maktaba process holds to the home (/api/cluster/agent), the hub that keeps the live state of every connected process, the browser WebSocket (/api/cluster/ws), the history endpoints that read the cluster files on the share, the per-process commands and the LLM router with its OpenAI-compatible door.
Nothing here goes through the database: the hub reads cluster_nodes to authenticate a node, the library roots to find the share, and the queue snapshot it shows; everything the processes send stays in memory or in files.
Index ¶
- Constants
- Variables
- func Accepts(name string) bool
- func CheckClientProof(c2s, th, proof []byte) bool
- func ClientProof(c2s, th []byte) []byte
- func ClusterKeyPath(override string) string
- func DBLibrary(db *sql.DB, now func() time.Time) func(ctx context.Context) (*LibrarySnapshot, error)
- func DBLibraryRoots(db *sql.DB) func(ctx context.Context) ([]LibraryRoot, error)
- func DH(priv, pub []byte) ([]byte, error)
- func DefaultArchiveDir() string
- func DeriveKeys(ikm, clientNonce, serverNonce []byte) (c2s, s2c []byte, err error)
- func FallbackDir() string
- func HomeIKM(homeKey, dhEE []byte) []byte
- func HomeKeyPath(override string) string
- func IPDir(ip string) string
- func LANAddress() string
- func LoadOrCreateClusterKey(path string) (priv, pub []byte, err error)
- func LoadOrCreateHomeKey(path string) ([]byte, error)
- func LoadOrCreateKey(path string, mode os.FileMode) ([]byte, error)
- func NodeIKM(dhEE, dhSE, dhES []byte) []byte
- func ParseKeyMode(v string) (os.FileMode, bool)
- func RequestFits(req *LLMRequest) bool
- func ServerProof(s2c, th []byte) []byte
- func ShareRootOf(roots []LibraryRoot) string
- func Transcript(hello, challenge []byte) []byte
- func ValidDate(s string) bool
- func ValidIPDir(s string) bool
- type AccessGranter
- type ArchiveConfig
- type ArchiveStats
- type Archiver
- type Cache
- type CacheQuery
- type CacheRecord
- type CertIssue
- type CertIssuer
- type Cipher
- type CmdRequest
- type CmdResult
- type Config
- type FileStats
- type FileWriter
- type FilesIndex
- type Hub
- func (h *Hub) AnswerAccessRequests(g AccessGranter, logger *slog.Logger)
- func (h *Hub) BroadcastRevoked(r RevokedSessions) int
- func (h *Hub) ClockSkews() map[string]time.Duration
- func (h *Hub) CmdHTTP(w http.ResponseWriter, r *http.Request)
- func (h *Hub) Command(ctx context.Context, sessionID, name string, args json.RawMessage, by string) (CmdResult, error)
- func (h *Hub) CommandWithin(ctx context.Context, sessionID, name string, args json.RawMessage, by string, ...) (CmdResult, error)
- func (h *Hub) EnsureAccess(ctx context.Context, g AccessGranter, every time.Duration, logger *slog.Logger)
- func (h *Hub) Files(w http.ResponseWriter, r *http.Request)
- func (h *Hub) Gone() []Process
- func (h *Hub) History(w http.ResponseWriter, r *http.Request)
- func (h *Hub) HomeIP() string
- func (h *Hub) HomeProcesses() []string
- func (h *Hub) LLMChat(w http.ResponseWriter, r *http.Request)
- func (h *Hub) LLMEmbeddings(w http.ResponseWriter, r *http.Request)
- func (h *Hub) LLMModels(w http.ResponseWriter, r *http.Request)
- func (h *Hub) Locate(ctx context.Context) Location
- func (h *Hub) Location() Location
- func (h *Hub) MachineAgent(nodeID string) string
- func (h *Hub) MachineAgents() map[string]string
- func (h *Hub) MachineStates() map[string]json.RawMessage
- func (h *Hub) MachinesOffDatabase() []OffDatabase
- func (h *Hub) Mount(r chi.Router)
- func (h *Hub) NodeChanged(nodeID string)
- func (h *Hub) NodeHosts() map[string][]string
- func (h *Hub) NodeWorkers() map[string]NodeWorker
- func (h *Hub) Processes() []Process
- func (h *Hub) ProcessesHTTP(w http.ResponseWriter, r *http.Request)
- func (h *Hub) PushDatabase(ctx context.Context, caFile string, every time.Duration, logger *slog.Logger)
- func (h *Hub) Record(fields map[string]any)
- func (h *Hub) RelayHTTP(w http.ResponseWriter, r *http.Request)
- func (h *Hub) RevokeNode(nodeID string)
- func (h *Hub) Router() *Router
- func (h *Hub) Run(ctx context.Context)
- func (h *Hub) ServeAgent(w http.ResponseWriter, r *http.Request)
- func (h *Hub) ServeBrowser(w http.ResponseWriter, r *http.Request)
- func (h *Hub) Session(id string) *Session
- type KeyIssuer
- type LLMError
- type LLMEvent
- type LLMRequest
- type LLMRequestFrame
- type LibraryRoot
- type LibrarySnapshot
- type LibraryStats
- type Location
- type Locator
- type LogRecord
- type MachineFiles
- type ModelHolder
- type ModelInfo
- type NodeStore
- type NodeWorker
- type OffDatabase
- type PathMap
- type Proc
- type Process
- type ProcessLLM
- type QueueLine
- type QueueLiteStage
- type QueuePoolLine
- type QueuePoolLite
- type QueueSnapshotLite
- type QueueStageLine
- type RevokedSessions
- type Router
- func (rt *Router) Cancel(id string)
- func (rt *Router) CancelFrom(session, clientID string)
- func (rt *Router) Chunk(session, id string, data json.RawMessage)
- func (rt *Router) Done(session, id string, usage json.RawMessage, e LLMError)
- func (rt *Router) HostGone(session string)
- func (rt *Router) Models() []ModelInfo
- func (rt *Router) Snapshot() map[string]any
- func (rt *Router) Submit(req *LLMRequest)
- func (rt *Router) Sweep()
- func (rt *Router) UpdateHost(session, ip string, since time.Time, runtimes json.RawMessage)
- type RouterConfig
- type Session
- type Sink
- type Sweeper
Constants ¶
const ( DefaultArchiveDays = 365 DefaultArchiveMaxGB = 20 )
Defaults of §7.10 / §9.
const ( TopicQueues = "queues" TopicJobs = "jobs" TopicWorkers = "workers" TopicMetrics = "metrics" TopicLibrary = "library" TopicLLM = "llm" TopicProcesses = "processes" )
Browser topics (design-agent.md §5). logs:<ip|node_id|session>:<level> is the per-viewer log tail.
const ( ProtocolVersion = 2 NonceSize = 16 KeySize = 32 )
Protocol constants of design-agent.md §4.2–§4.4 (handshake v2).
const ( KindEvents = "events" KindQueues = "queues" KindLibrary = "library" )
The hub's own files (design-agent.md §4): under the home's IP folder, <kind>/<YYYY-MM-DD>/hub.jsonl. Every other file belongs to the process that writes it.
const ( DefaultLogLevel = "info" DefaultMetricsEvery = 2 DefaultRetentionDays = 14 DefaultFileMB = 256 DefaultQueueTimeout = 300 * time.Second DefaultMaxParallel = 1 DefaultIdleTimeout = 10 * time.Minute DefaultAgentRatePerMin = 30 DefaultCacheHours = 24 )
Defaults of design-agent.md §3, §4, §6 and §7.
const ( LLMNoModel = "no_model" LLMNoCapacity = "no_capacity" LLMMachineGone = "machine_gone" LLMRuntimeError = "runtime_error" LLMCancelled = "cancelled" LLMTooLarge = "too_large" LLMTimeout = "timeout" LLMBadRequest = "bad_request" )
LLM error codes (design-agent.md §5.1, §8.2).
const ( KeyMode os.FileMode = 0o600 GroupKeyMode os.FileMode = 0o640 )
Key file modes MAKTABA_HOME_AGENT_KEY_MODE may choose: 0600 (the default) or 0640, for a home whose workers read the key as another user of the API's group (Docker: a shared volume).
const ( CloseNormal = websocket.StatusNormalClosure // 1000 CloseGoingAway = websocket.StatusGoingAway // 1001 CloseSlow = websocket.StatusTryAgainLater // 1013: the process cannot keep up CloseProtocolError = websocket.StatusCode(4000) CloseUnsupportedVersion = websocket.StatusCode(4001) CloseNotMember = websocket.StatusCode(4003) CloseAuthFailed = websocket.StatusCode(4004) CloseTimeout = websocket.StatusCode(4008) CloseReplaced = websocket.StatusCode(4009) CloseRevoked = websocket.StatusCode(4010) CloseSealError = websocket.StatusCode(4011) CloseTooLarge = websocket.StatusCode(4012) CloseRateLimited = websocket.StatusCode(4013) CloseDisconnect = websocket.StatusCode(4014) // MaxFrame is the largest sealed frame (§4.7); the transport limit is // above it so an oversized frame gets 4012 rather than a bare 1009. MaxFrame = 4 << 20 )
Close codes of design-agent.md §4.6.
const AgentPath = "/api/cluster/agent"
AgentPath is the processes' endpoint (public: authentication is in the protocol; it must be on the auth allowlist).
const CodeNoDoor = "no_door"
CodeNoDoor: the home runs without the door.
const GoneAge = time.Hour
GoneAge is how old a gone process's file, or an orphaned temp file, is before a sweep removes it: a temp file lives for one write, and a process that said it stopped is not coming back.
const ProcessSupervisor = "supervisor"
ProcessSupervisor is hello.process of a node's machine agent.
const StaleSeen = 10 * time.Minute
StaleSeen is how long a process goes without refreshing its last_seen (every 60 s) before readers stop listing it: it no longer runs.
Variables ¶
var ( ErrNoSession = errors.New("agent: no such session") ErrBadCommand = errors.New("agent: unknown command or bad arguments") ErrCmdTimeout = errors.New("agent: the process did not answer in time") )
Command errors.
var ( PingEvery = 15 * time.Second SilenceLimit = 45 * time.Second HandshakeTime = 10 * time.Second CmdTimeout = 10 * time.Second )
Timings (variables so tests can shorten them).
var ( // ErrFrameTooLarge: the frame would seal to more than MaxFrame; it is // not sent, and the session stays open. ErrFrameTooLarge = errors.New("agent: frame over the size limit") // ErrGone: the session is closed (or closing). ErrGone = errors.New("agent: session gone") )
Send errors.
var DayKinds = []string{"logs", "metrics", "llm", "jobs", "events", "queues", "library"}
DayKinds are the day-directory kinds a machine folder can hold.
var DefaultArchiveKinds = []string{"logs", "jobs", "llm", "events"}
DefaultArchiveKinds are the kinds archived unless MAKTABA_ARCHIVE_KINDS says otherwise.
var ErrFrame = errors.New("agent: frame rejected")
ErrFrame is returned for a sealed frame that does not open: a failed tag, a repeated or a skipped counter. The connection must close.
var ErrLowOrder = errors.New("agent: all-zero shared secret")
ErrLowOrder is returned when a Diffie-Hellman result is all zero (a low-order public key).
Functions ¶
func Accepts ¶
Accepts reports whether the hub sends a command of this name at all (CommandWithin refuses any other with ErrBadCommand): the switch's tests ask it of their fake hub.
func CheckClientProof ¶
CheckClientProof compares a client's proof in constant time.
func ClientProof ¶
ClientProof is HMAC-SHA256(k_c2s, "maktaba-agent-auth"‖th).
func ClusterKeyPath ¶
ClusterKeyPath is the home's long-term cluster key's file (§4.2): MAKTABA_HOME_CLUSTER_KEY, else ~/.maktaba/cluster/home-cluster.key.
func DBLibrary ¶
func DBLibrary(db *sql.DB, now func() time.Time) func(ctx context.Context) (*LibrarySnapshot, error)
DBLibrary builds library snapshots from the catalog.
func DBLibraryRoots ¶
DBLibraryRoots reads the library roots for the share root.
func DeriveKeys ¶
DeriveKeys returns (k_c2s, k_s2c): HKDF-SHA256(ikm, salt=client_nonce‖server_nonce, info="maktaba-agent-v2", L=64) split in two.
func FallbackDir ¶
func FallbackDir() string
FallbackDir is ~/.maktaba/cluster (the working directory's .maktaba/cluster when there is no home directory).
func HomeKeyPath ¶
HomeKeyPath is the home agent key's file (design-agent.md §4.3): the given override (MAKTABA_HOME_AGENT_KEY), else ~/.maktaba/cluster/home-agent.key: always local, never on the share.
func LANAddress ¶
func LANAddress() string
LANAddress is the home's own folder name and the address its own processes are filed under: the first non-loopback private IPv4 of an interface that is up, else the host name.
func LoadOrCreateClusterKey ¶
LoadOrCreateClusterKey returns the cluster key pair (X25519 private and public), creating the private half like the home agent key; it is always mode 0600.
func LoadOrCreateHomeKey ¶
LoadOrCreateHomeKey is LoadOrCreateKey with mode 0600.
func LoadOrCreateKey ¶
LoadOrCreateKey returns the 32-byte key at path, creating it (32 random bytes, written atomically, with the given mode: 0600 or 0640) when absent or not 32 bytes. An existing file with bits beyond mode is tightened to it; an existing 0600 file is opened to 0640 only when mode asks for 0640. Nothing else is ever loosened.
func ParseKeyMode ¶
ParseKeyMode reads MAKTABA_HOME_AGENT_KEY_MODE: "0600"/"600" or "0640"/"640"; anything else is refused.
func RequestFits ¶
func RequestFits(req *LLMRequest) bool
RequestFits reports whether req's llm.request frame fits in a sealed frame (the router's ids are all the same length).
func ServerProof ¶
ServerProof is HMAC-SHA256(k_s2c, "maktaba-agent-server"‖th), sent in welcome.
func ShareRootOf ¶
func ShareRootOf(roots []LibraryRoot) string
ShareRootOf is the share root of design-agent.md §4: the deepest directory common to every library root; when they share nothing but the filesystem root, the root of the library with the most videos.
func Transcript ¶
Transcript is th = SHA-256(hello_bytes ‖ challenge_bytes), over the two text frames exactly as sent and received.
func ValidIPDir ¶
ValidIPDir reports whether s is a safe machine folder name.
Types ¶
type AccessGranter ¶
type AccessGranter interface {
// AccessUsable reports whether a machine's role logs in on this home's database now.
AccessUsable(ctx context.Context, nodeID string) (bool, error)
// GrantAccess makes a machine's role again on this home's database, with a new
// password, and returns its access as the machine's home.access command takes it.
GrantAccess(ctx context.Context, nodeID string) (json.RawMessage, error)
// AccessTarget is where a re-made access points: the database's host ("": the host
// the machine reaches the home at), port and name.
AccessTarget(ctx context.Context, nodeID string) (host string, port int, db string, err error)
}
AccessGranter is the home's side of its machines' database access (the home owns it).
type ArchiveConfig ¶
type ArchiveConfig struct {
Dir string // MAKTABA_ARCHIVE_DIR, default ~/.maktaba/archive
Kinds []string // MAKTABA_ARCHIVE_KINDS
Days int // MAKTABA_ARCHIVE_DAYS (0: no age limit)
MaxBytes int64 // MAKTABA_ARCHIVE_MAX_GB in bytes (0: no size limit)
}
ArchiveConfig is the archive's settings.
type ArchiveStats ¶
type ArchiveStats struct {
Dir string `json:"dir"`
LastRun *time.Time `json:"last_run"`
// what the last pass archived
DaysArchived int `json:"days_archived"`
FilesArchived int `json:"files_archived"`
BytesArchived int64 `json:"bytes_archived"` // source bytes
// what the archive holds
DaysHeld int `json:"days_held"`
Files int `json:"files"`
SizeBytes int64 `json:"size_bytes"`
OldestDay *string `json:"oldest_day"`
LastError *string `json:"last_error"`
}
ArchiveStats is the processes snapshot's `archive`.
type Archiver ¶
type Archiver struct {
// contains filtered or unexported fields
}
Archiver keeps the archive.
func NewArchiver ¶
func NewArchiver(cfg ArchiveConfig, share func() string, now func() time.Time, logger *slog.Logger) *Archiver
NewArchiver returns an archiver for cfg reading the share at share().
func (*Archiver) Pass ¶
Pass is one run: archive the closed days, then (once a day) apply the retention, then count what the archive holds.
func (*Archiver) Stats ¶
func (a *Archiver) Stats() ArchiveStats
Stats is a copy of the archive's numbers.
type Cache ¶
type Cache interface {
// Metrics stores a metrics frame (without "t"), its flat health map
// (health_samples names) and whether it is the process's final frame.
Metrics(p Proc, frame json.RawMessage, health map[string]float64, final bool)
// Logs stores a logs frame's records.
Logs(p Proc, recs []LogRecord)
// Covers reports whether the cache holds kind ("metrics" | "logs")
// for the whole of [from, to).
Covers(kind string, from, to time.Time) bool
ReadMetrics(ctx context.Context, q CacheQuery) ([]CacheRecord, error)
ReadLogs(ctx context.Context, q CacheQuery) ([]CacheRecord, error)
// Run writes until ctx ends; Backfill loads the cluster files of the
// cache window from dir.
Run(ctx context.Context)
Backfill(ctx context.Context, dir string) error
// Stats is shown in the processes snapshot as `cache`.
Stats() any
}
Cache is what the hub needs from the cache.
type CacheQuery ¶
type CacheQuery struct {
IP string
WorkerID string // "" for every process
Level string // logs: records at or above it ("" for all)
Q string // logs: case-insensitive substring
From, To time.Time
Limit int
}
CacheQuery is a history read (the REST filters).
type CacheRecord ¶
type CacheRecord struct {
WorkerID string
TS time.Time
Line json.RawMessage
}
CacheRecord is one cached line: the process it came from, its time and the record as the files hold it (a log record; a metrics frame without "t").
type CertIssue ¶
type CertIssue struct {
Cert string `json:"cert"`
CACert string `json:"ca_cert"`
CASHA256 string `json:"ca_sha256"`
NotAfter time.Time `json:"not_after"`
}
CertIssue is a signed certificate, the CA it chains to and the CA's fingerprint.
type CertIssuer ¶
type CertIssuer interface {
IssueCert(ctx context.Context, nodeID, csrPEM string) (CertIssue, error)
}
CertIssuer signs a machine's cluster-link certificate (story 35.16).
type Cipher ¶
type Cipher struct {
// contains filtered or unexported fields
}
Cipher seals or opens one direction's frames: ChaCha20-Poly1305(key, nonce = 4 zero bytes ‖ 8-byte big-endian counter, aad = ""), the counter starting at 0 and moving by one per frame. Because the nonce is the expected counter, a repeated, skipped or forged frame fails to open. Not safe for concurrent use: each direction has one owner (the session's reader or writer goroutine).
type CmdRequest ¶
type CmdRequest struct {
Name string `json:"name"`
Args json.RawMessage `json:"args"`
}
CmdRequest is the body of POST /api/cluster/processes/{session}/cmd.
type CmdResult ¶
type CmdResult struct {
ID string `json:"id"`
OK bool `json:"ok"`
Detail json.RawMessage `json:"detail"`
}
CmdResult is a process's answer (cmd.result).
type Config ¶
type Config struct {
Store NodeStore
// HomeKey authenticates the home's own processes; nil refuses them.
HomeKey []byte
// HomeKeyMode is MAKTABA_HOME_AGENT_KEY_MODE (0600 or 0640), for the
// caller that loads HomeKey.
HomeKeyMode os.FileMode
// ClusterKey is the private half of the home's long-term cluster key
// (design-agent.md §4.2); nil refuses machines.
ClusterKey []byte
// Cache is the database cache of the channel (track C1); nil: none.
Cache Cache
// Archive is the home's long-term archive (§7.10); nil: none.
Archive *ArchiveConfig
// CacheWindow is MAKTABA_CLUSTER_CACHE_HOURS, for the cache's
// Options.Window.
CacheWindow time.Duration
// LogLevel is MAKTABA_CLUSTER_LOG_LEVEL (sent in welcome).
LogLevel string
MetricsEvery int
// HomeAddr is the home's folder / address ("" → LANAddress()).
HomeAddr string
// Locator finds the cluster directory; nil writes no files.
Locator *Locator
// LocalDir is this machine's own cluster folder (~/.maktaba/cluster): its
// local fallback and its status folder are swept too. Empty: not swept.
LocalDir string
RetentionDays int
FileMaxBytes int64
// Queues builds the queue snapshot (the Processing page's data);
// Workers the GET /api/workers list; Library the library numbers.
// nil: that topic stays empty.
Queues func(ctx context.Context) (queues.Snapshot, error)
Workers func(ctx context.Context) ([]queues.Worker, error)
Library func(ctx context.Context) (*LibrarySnapshot, error)
// Relay is the extension service door (svc.request frames, GET
// /api/cluster/relay); nil: every svc.request is refused (no_door).
Relay *relay.Door
LLMQueueTimeout time.Duration
LLMMaxParallel int
LLMIdleTimeout time.Duration
// AgentRatePerMin caps handshakes per IP on /api/cluster/agent
// (default 30; negative: no limit); past it the close is 4013.
AgentRatePerMin int
// BrowserOrigins are extra Origin patterns allowed on /api/cluster/ws
// (the API's own origin is always allowed).
BrowserOrigins []string
// Delegation issues the nodes' delegation keys (Epic 35 story 35.9); nil: the
// machine agents get none (full nodes then cannot act for users).
Delegation KeyIssuer
// Certs signs a machine's cluster-link certificate from its CSR (cert.csr, story
// 35.16: a machine joined before the link gets its certificate on its channel
// session, no re-join); nil: cert.csr is refused.
Certs CertIssuer
// HasCert reports whether a machine holds a cluster-link certificate: only such a
// machine's plain session is cert-only while the link is required (one that never got
// one — a worker-only machine, an older release — keeps its channel); nil: none does.
HasCert func(ctx context.Context, nodeID string) bool
// DBClientCert keeps a machine's word, from its machine agent's update.state
// (db_client_cert), on whether every one of its processes presents its cluster
// certificate to this home's database: once the link is required the home's Postgres
// asks only such a machine's role for it (pgbundle Reach.CertRoles), so requiring the
// link never cuts a machine off its database. Called when a session first says it and
// when it changes; nil: not kept.
DBClientCert func(ctx context.Context, nodeID string, presents bool) error
Now func() time.Time
Logger *slog.Logger
}
Config wires a Hub.
func FromEnv ¶
FromEnv reads the hub's settings (design-agent.md §4, §6, §7):
MAKTABA_CLUSTER_DIR local cluster folder (overrides the share)
MAKTABA_SHARE_ROOT share root, database form (default: from the library roots)
MAKTABA_PATH_MAP database → local prefixes, the workers' --path-map format
MAKTABA_CLUSTER_RETENTION_DAYS default 14
MAKTABA_CLUSTER_FILE_MB default 256
MAKTABA_CLUSTER_LOG_LEVEL default info
MAKTABA_LLM_QUEUE_TIMEOUT_S default 300
MAKTABA_LLM_MAX_PARALLEL default 1 (per runtime that does not say)
MAKTABA_CLUSTER_AGENT_RATE_PER_MIN handshakes per IP a minute, default 30
MAKTABA_CLUSTER_IP the home's IP folder name (default: its first private IPv4)
MAKTABA_CLUSTER_CACHE_HOURS the database cache's window, default 24
MAKTABA_CORS_ALLOWED_ORIGINS extra browser origins for /api/cluster/ws
MAKTABA_ARCHIVE_DIR the home's long-term archive, default ~/.maktaba/archive
MAKTABA_ARCHIVE_KINDS the kinds archived, default logs,jobs,llm,events
MAKTABA_ARCHIVE_DAYS days kept in the archive, default 365 (0: no age limit)
MAKTABA_ARCHIVE_MAX_GB the archive's size cap, default 20 (0: no size limit)
MAKTABA_HOME_AGENT_KEY_MODE the home agent key file's mode: 0600 (default) or 0640
(0640 lets home workers of the API's group read it, e.g. Docker)
The key files are read by the caller: MAKTABA_HOME_AGENT_KEY (MAKTABA_CLUSTER_KEY_PATH also accepted) and MAKTABA_HOME_CLUSTER_KEY (always 0600).
Bad values fall back to the default and are reported as warnings.
type FileStats ¶
type FileStats struct {
Dropped int64 `json:"dropped"`
Capped int64 `json:"capped"`
Errors int64 `json:"errors"`
}
Stats are the writer's counters.
type FileWriter ¶
type FileWriter struct {
MaxBytes int64
Now func() time.Time
Logger *slog.Logger
// contains filtered or unexported fields
}
FileWriter is the hub's buffered, asynchronous writer: Write never blocks (a full buffer counts the record as dropped), one goroutine owns the files, flushes at least every second, rotates by UTC day, caps each file at MaxBytes (past it records are counted, not written) and logs disk errors once a minute.
func NewFileWriter ¶
NewFileWriter returns a writer with a buffer of n records.
func (*FileWriter) Run ¶
func (fw *FileWriter) Run(ctx context.Context)
Run owns the files until ctx ends (then flushes and closes them).
func (*FileWriter) SetTarget ¶
func (fw *FileWriter) SetTarget(dir, ipDir string)
SetTarget points the writer at a cluster dir and the home's folder; open files are closed and reopened there on the next record.
func (*FileWriter) Write ¶
func (fw *FileWriter) Write(kind string, v any)
Write queues one JSON line for kind; it never blocks.
type FilesIndex ¶
type FilesIndex struct {
Files Location `json:"files"`
Nodes []MachineFiles `json:"nodes"`
}
FilesIndex is GET /api/cluster/files.
type Hub ¶
type Hub struct {
// contains filtered or unexported fields
}
Hub is the live centre of the cluster.
func (*Hub) AnswerAccessRequests ¶
func (h *Hub) AnswerAccessRequests(g AccessGranter, logger *slog.Logger)
AnswerAccessRequests answers the machines' own requests for their database access with g (EnsureAccess does, besides its push).
func (*Hub) BroadcastRevoked ¶
func (h *Hub) BroadcastRevoked(r RevokedSessions) int
BroadcastRevoked sends auth.revoked to every machine agent (story 35.9 AC4). Session ids travel as their SHA-256 (the nodes key their caches by it). It returns how many agents were told.
func (*Hub) ClockSkews ¶
ClockSkews are the connected machine agents' clocks minus the home's, by node id (story 35.16 EC2: a machine more than 5 minutes off cannot use its new certificate yet).
func (*Hub) CmdHTTP ¶
func (h *Hub) CmdHTTP(w http.ResponseWriter, r *http.Request)
CmdHTTP implements POST /api/cluster/processes/{session}/cmd: 200 with the process's {id, ok, detail}; 404 no such session; 400 unknown command; 504 no answer within 10 s.
func (*Hub) Command ¶
func (h *Hub) Command(ctx context.Context, sessionID, name string, args json.RawMessage, by string) (CmdResult, error)
Command sends a command to a process and waits for its cmd.result (at most CmdTimeout). "disconnect" closes the session once answered (or at the timeout). by names who asked (for the events file).
func (*Hub) CommandWithin ¶
func (h *Hub) CommandWithin(ctx context.Context, sessionID, name string, args json.RawMessage, by string, wait time.Duration) (CmdResult, error)
CommandWithin is Command waiting up to wait (a promotion takes minutes).
func (*Hub) EnsureAccess ¶
func (h *Hub) EnsureAccess(ctx context.Context, g AccessGranter, every time.Duration, logger *slog.Logger)
EnsureAccess keeps every connected machine able to log in to this home's database: a machine that says it cannot, twice in a row, for a reason a re-made access mends (remakeWhy: its role refused, or the database moved to another port or database), or whose role does not log in on the home's current database (checked once per agent session: a move carried no roles) gets its access re-made and pushed (home.access); again after accessRetry, then twice as long each time up to accessRetryMax, until it logs in. It runs every interval until ctx ends.
func (*Hub) Files ¶
func (h *Hub) Files(w http.ResponseWriter, r *http.Request)
Files implements GET /api/cluster/files.
func (*Hub) History ¶
func (h *Hub) History(w http.ResponseWriter, r *http.Request)
History implements GET /api/cluster/files/{ip}/{kind}.
func (*Hub) HomeProcesses ¶
HomeProcesses are the sessions of the home's own processes (its workers).
func (*Hub) LLMChat ¶
func (h *Hub) LLMChat(w http.ResponseWriter, r *http.Request)
LLMChat implements POST /api/cluster/llm/v1/chat/completions.
func (*Hub) LLMEmbeddings ¶
func (h *Hub) LLMEmbeddings(w http.ResponseWriter, r *http.Request)
LLMEmbeddings implements POST /api/cluster/llm/v1/embeddings.
func (*Hub) LLMModels ¶
func (h *Hub) LLMModels(w http.ResponseWriter, r *http.Request)
LLMModels implements GET /api/cluster/llm/v1/models.
func (*Hub) Locate ¶
Locate resolves the cluster directory now and points the writer at it; a change is recorded in the events file and re-sent to process viewers.
func (*Hub) MachineAgent ¶
MachineAgent is the session of a machine's own agent (its supervisor), "" when it is not connected.
func (*Hub) MachineAgents ¶
MachineAgents are the connected machines' own agents (their supervisors): session id by node id. A machine's agent that reconnects is registered before the session it replaces is closed, and that one stays listed until its connection has shut, which can take seconds. So a closed session is never named, and of two live ones the newer is: naming the old one would leave the new one untold until the old one is removed.
func (*Hub) MachineStates ¶
func (h *Hub) MachineStates() map[string]json.RawMessage
MachineStates are the connected machine agents' last update.state (their release, platform, install kind and update run), by node id (Epic 35 story 35.12).
func (*Hub) MachinesOffDatabase ¶
func (h *Hub) MachinesOffDatabase() []OffDatabase
MachinesOffDatabase are the connected machines that say they cannot log in to this home's database (their update.state's home_db), with why and whether they follow their re-made access already.
func (*Hub) Mount ¶
Mount wires the hub's routes:
GET /api/cluster/agent public (protocol auth), 30 handshakes/min per IP: processes
GET /api/cluster/ws signed-in users: browsers
GET /api/cluster/processes admin: the processes snapshot
GET /api/cluster/files admin
GET /api/cluster/files/{ip}/{kind} admin
POST /api/cluster/processes/{session}/cmd admin
GET /api/cluster/llm/v1/models admins (admin token or session) and personal access tokens
POST /api/cluster/llm/v1/chat/completions same
POST /api/cluster/llm/v1/embeddings same
func (*Hub) NodeChanged ¶
NodeChanged tells the node's processes to re-read their stage switches and drain at once (phase-1 PUT /api/cluster/nodes/{id}).
func (*Hub) NodeHosts ¶
NodeHosts are the host names each connected machine's sessions report (its machine agent and its workers), by node id: a job's claimer ("host/pid/id") is one of them, whatever the machine is named in the cluster.
func (*Hub) NodeWorkers ¶
func (h *Hub) NodeWorkers() map[string]NodeWorker
NodeWorkers are the connected machines' pipeline workers, one by node id (the lowest worker id of the machine's: maktaba-node before maktaba-node@2): a worker-only machine's next update reaches it there (update.convert).
func (*Hub) ProcessesHTTP ¶
func (h *Hub) ProcessesHTTP(w http.ResponseWriter, r *http.Request)
ProcessesHTTP implements GET /api/cluster/processes.
func (*Hub) PushDatabase ¶
func (h *Hub) PushDatabase(ctx context.Context, caFile string, every time.Duration, logger *slog.Logger)
PushDatabase hands every connected machine this home's database CA over the machine channel (or the home's word that its database has no TLS: caFile ""), which the cluster key authenticates (specs/epics/37-node-replica): a machine verifies its home's database with it, never with what the database connection itself would say. Each machine's agent session is told once, as soon as it connects, and again when the CA changes (looked at every interval); it runs until ctx ends. A machine that waited for the next interval instead would run that long unable to verify its home's database (its copy idle), then start again in the middle of its work.
func (*Hub) Record ¶
Record appends an event of the home's own to the hub's events file (its `event` field names it: the update flow's, story 35.15 AC2).
func (*Hub) RelayHTTP ¶
func (h *Hub) RelayHTTP(w http.ResponseWriter, r *http.Request)
RelayHTTP implements GET /api/cluster/relay (admin): the door's status and its recent calls.
func (*Hub) RevokeNode ¶
RevokeNode closes the node's sessions at once and refuses sessions whose handshake read the registry before now (phase-1 revoke / remove).
func (*Hub) Run ¶
Run starts the loops (file writer, location, queues, workers, library, retention, LLM sweeps) and blocks until ctx ends; then it closes every session.
func (*Hub) ServeAgent ¶
func (h *Hub) ServeAgent(w http.ResponseWriter, r *http.Request)
ServeAgent implements GET /api/cluster/agent: the handshake of design-agent.md §4.2/§4.3, then sealed frames until either side leaves.
func (*Hub) ServeBrowser ¶
func (h *Hub) ServeBrowser(w http.ResponseWriter, r *http.Request)
ServeBrowser implements GET /api/cluster/ws (signed-in users; the admin-only topics and commands need an admin).
type KeyIssuer ¶
type KeyIssuer interface {
Issue(ctx context.Context, nodeID string) (delegation.Key, bool, error)
Revoke(ctx context.Context, nodeID string)
}
KeyIssuer issues and revokes the nodes' delegation keys (delegation.KeyStore).
type LLMEvent ¶
type LLMEvent struct {
ID string `json:"id"`
Model string `json:"model"`
Op string `json:"op"`
FromSession *string `json:"from_session"`
ToSession *string `json:"to_session"`
State string `json:"state"` // queued | started | done | failed
Usage json.RawMessage `json:"usage"`
Error *string `json:"error"`
}
LLMEvent is the browsers' `llm` message.
type LLMRequest ¶
type LLMRequest struct {
ClientID string // the requester's own id
Model string
Op string
Body json.RawMessage
Stream bool
FromSession string // "" for the HTTP door
FromIP string
Sink Sink
// contains filtered or unexported fields
}
LLMRequest is a request to the cluster.
func (*LLMRequest) ID ¶
func (r *LLMRequest) ID() string
ID is the router's id of the request (the one the runner sees).
type LLMRequestFrame ¶
type LLMRequestFrame struct {
T string `json:"t"`
ID string `json:"id"`
Model string `json:"model"`
Op string `json:"op"`
Body json.RawMessage `json:"body"`
Stream bool `json:"stream"`
}
LLMRequestFrame is an llm.request frame.
type LibraryRoot ¶
LibraryRoot is one library root as stored, with its library's video count (the tie-breaker when the roots share nothing but the filesystem root).
type LibrarySnapshot ¶
type LibrarySnapshot struct {
TS time.Time `json:"ts"`
Libraries []LibraryStats `json:"libraries"`
Totals LibraryStats `json:"totals"`
}
LibrarySnapshot is the `library` message and one line of library/<date>/hub.jsonl.
type LibraryStats ¶
type LibraryStats struct {
LibraryID string `json:"library_id,omitempty"`
Name string `json:"name,omitempty"`
Videos int64 `json:"videos"`
Hours float64 `json:"hours"`
Bytes int64 `json:"bytes"`
TranscribedVideos int64 `json:"transcribed_videos"`
TranscribedHours float64 `json:"transcribed_hours"`
Series int64 `json:"series"`
Seasons int64 `json:"seasons"`
Tagged int64 `json:"tagged"`
Indexed int64 `json:"indexed"`
}
LibraryStats is one library in a library snapshot.
type Location ¶
type Location struct {
Dir string `json:"dir"`
Reason *string `json:"reason"`
ShareRoot string `json:"share_root,omitempty"`
}
Location is where the cluster files live (design-agent.md §4) as the processes and browsers see it: `files: {dir, on_share, reason}`.
type Locator ¶
type Locator struct {
// Override is MAKTABA_CLUSTER_DIR (a local path).
Override string
// ShareRoot is MAKTABA_SHARE_ROOT (database form); empty: derived from
// the library roots.
PathMap PathMap
// Roots reads the library roots (nil: none known).
Roots func(ctx context.Context) ([]LibraryRoot, error)
// Fallback is the local directory used when the share is not
// reachable (default ~/.maktaba/cluster).
Fallback string
}
Locator resolves the cluster directory: MAKTABA_CLUSTER_DIR when set; else <share root>/maktaba/cluster through the path map when the share is reachable; else the local fallback (~/.maktaba/cluster).
type LogRecord ¶
type LogRecord struct {
TS string `json:"ts"`
Level string `json:"level"`
Event string `json:"event"`
Logger string `json:"logger"`
Fields json.RawMessage `json:"fields"`
}
LogRecord is one record of a logs frame.
type MachineFiles ¶
type MachineFiles struct {
IP string `json:"ip"`
Processes []json.RawMessage `json:"processes"`
Dates map[string][]string `json:"dates"`
ArchivedDates map[string][]string `json:"archived_dates"`
}
MachineFiles is one machine folder in GET /api/cluster/files: the days the share holds per kind, and the days the home's archive holds (archived_dates, §7.10; a day may be in both).
type ModelHolder ¶
type ModelHolder struct {
Session string `json:"session"`
IP string `json:"ip"`
Provider string `json:"provider"`
BaseURL string `json:"base_url"`
Loaded bool `json:"loaded"`
MaxParallel int `json:"max_parallel"`
InFlight int `json:"in_flight"`
}
ModelHolder is a runtime that holds a model.
type ModelInfo ¶
type ModelInfo struct {
Model string `json:"model"`
Hosts []ModelHolder `json:"hosts"`
}
ModelInfo is one model in the cluster.
type NodeStore ¶
NodeStore is the slice of the phase-1 machine registry the hub reads: a node's state and pairing key (cluster.MemoryStore and cluster.PGStore satisfy it).
type NodeWorker ¶
type NodeWorker struct {
Session, WorkerID, Version string
}
NodeWorker is a machine's pipeline worker on the channel: its session, its worker id and the pipeline version it reported.
type OffDatabase ¶
OffDatabase is a connected machine that says it cannot log in to this home's database.
type PathMap ¶
type PathMap struct {
// contains filtered or unexported fields
}
PathMap translates database paths (the scanner's form, e.g. "Y:/Channel/a.mp4") to this host's paths ("/Volumes/Y/Channel/a.mp4"). It is the Go twin of the pipeline's engine/paths.py PathMap: the same text format (`Y:/=/Volumes/Y;O:/=/Volumes/O` or a JSON object), the same normalisation (forward slashes, a trailing "/", UNC `\\nas\share` → `//nas/share/`), case-insensitive matching, longest database prefix wins.
func ParsePathMap ¶
ParsePathMap parses MAKTABA_PATH_MAP. Empty text is an empty map.
func (PathMap) Pairs ¶
Pairs returns the (database prefix, local prefix) entries, each with its trailing "/", in the map's order.
type Proc ¶
type Proc struct {
SessionID string
WorkerID string
NodeID string
NodeName string
Host string
IP string
}
Proc identifies the process a frame came from.
type Process ¶
type Process struct {
Session string `json:"session"`
Kind string `json:"kind"`
NodeID *string `json:"node_id"`
NodeName *string `json:"node_name"`
IP string `json:"ip"`
Host string `json:"host"`
WorkerID string `json:"worker_id"`
PID int `json:"pid"`
OS *string `json:"os"`
Version *string `json:"version"`
ConnectedAt time.Time `json:"connected_at"`
GoneAt *time.Time `json:"gone_at,omitempty"`
LogLevel string `json:"log_level"`
Metrics json.RawMessage `json:"metrics"`
LLM *ProcessLLM `json:"llm"`
}
Process is a connected process as browsers see it.
type ProcessLLM ¶
type ProcessLLM struct {
Runtimes json.RawMessage `json:"runtimes"`
}
ProcessLLM is a process's LLM runtimes (its last llm.models).
type QueueLine ¶
type QueueLine struct {
TS time.Time `json:"ts"`
Snapshot QueueSnapshotLite `json:"snapshot"`
Stages []QueueStageLine `json:"stages"`
Pools []QueuePoolLine `json:"pools"`
Flows []queues.Flow `json:"flows"`
}
QueueLine is one line of queues/<date>/hub.jsonl: the queue snapshot in the Processing page's own shape (trimmed to its numbers) under `snapshot`, which the web app's charts read, and the flat per-stage rows of design-agent.md §7.6, which the CLI reads.
type QueueLiteStage ¶
type QueueLiteStage struct {
Stage string `json:"stage"`
Counts queues.Counts `json:"counts"`
RatePerMin float64 `json:"rate_per_min"`
EtaSec *float64 `json:"eta_sec"`
OldestWaitingSec *float64 `json:"oldest_waiting_sec"`
WaitingReason *queues.WaitingReason `json:"waiting_reason"`
}
QueueLiteStage is one queue in QueueSnapshotLite (the QueueSummary field names).
type QueuePoolLine ¶
type QueuePoolLine struct {
Pool string `json:"pool"`
Busy int `json:"busy"`
Size int `json:"size"`
}
QueuePoolLine is one pool row of design-agent.md §7.6.
type QueuePoolLite ¶
type QueuePoolLite struct {
Pool string `json:"pool"`
Busy int `json:"busy"`
EffectiveSize int `json:"effective_size"`
}
QueuePoolLite is one pool in QueueSnapshotLite.
type QueueSnapshotLite ¶
type QueueSnapshotLite struct {
At time.Time `json:"at"`
PausedAll bool `json:"paused_all"`
Queues []QueueLiteStage `json:"queues"`
Pools []QueuePoolLite `json:"pools"`
Flows []queues.Flow `json:"flows"`
IssuesCount int `json:"issues_count"`
}
QueueSnapshotLite is a queues.Snapshot without the stage registry, the running jobs or the health strip.
type QueueStageLine ¶
type QueueStageLine struct {
Stage string `json:"stage"`
Waiting int `json:"waiting"`
Ready int `json:"ready"`
Running int `json:"running"`
Paused int `json:"paused"`
Failed int `json:"failed"`
DonePerMin float64 `json:"done_per_min"`
OldestWaitS *float64 `json:"oldest_wait_s"`
}
QueueStageLine is one stage row of design-agent.md §7.6.
type RevokedSessions ¶
RevokedSessions is what a revocation names, as the home's session store reports it.
type Router ¶
type Router struct {
// contains filtered or unexported fields
}
Router routes LLM requests to the sessions that hold the models: loaded first, then the least loaded relative to max_parallel, then the requester's own machine; FIFO per model when everyone is busy.
func (*Router) Cancel ¶
Cancel is the requester giving up (router id): a queued request is dropped; a running one gets llm.cancel on its runner, which still ends it with llm.done (its output is discarded meanwhile).
func (*Router) CancelFrom ¶
CancelFrom is a process's llm.cancel for its own request id.
func (*Router) Chunk ¶
func (rt *Router) Chunk(session, id string, data json.RawMessage)
Chunk forwards a runner's output.
func (*Router) Done ¶
func (rt *Router) Done(session, id string, usage json.RawMessage, e LLMError)
Done finishes a request on its runner's word.
func (*Router) HostGone ¶
HostGone drops a session: requests running there fail with machine_gone; its own queued requests are dropped.
func (*Router) Submit ¶
func (rt *Router) Submit(req *LLMRequest)
Submit routes a request: at once when a holder has room, queued when all are busy, failed with no_model when nobody holds it.
func (*Router) Sweep ¶
func (rt *Router) Sweep()
Sweep fails running requests silent for longer than the idle timeout.
func (*Router) UpdateHost ¶
UpdateHost replaces a session's runtimes (its llm.models), keeping the in-flight counts of runtimes it still has.
type RouterConfig ¶
type RouterConfig struct {
QueueTimeout time.Duration
MaxParallel int
IdleTimeout time.Duration
Now func() time.Time
// Send delivers a frame to a session: ErrFrameTooLarge when it cannot
// travel, ErrGone (or another error) when the session is gone.
Send func(session string, frame any) error
// Notify receives request state changes; ModelsChanged is called
// when the cluster's models change.
Notify func(LLMEvent)
ModelsChanged func()
DefaultRuntime string
}
RouterConfig wires a Router.
type Session ¶
type Session struct {
ID string
Kind string // "home" | "node"
NodeID string // "" for a home process
NodeName *string
IP string
Host string
WorkerID string
Process string // "supervisor": a node's machine agent (Epic 35)
PID int
OS string
Version string
ConnectedAt time.Time
// contains filtered or unexported fields
}
Session is one authenticated process connection.
type Sink ¶
type Sink interface {
Chunk(data json.RawMessage)
Done(usage json.RawMessage, err LLMError)
}
Sink receives a request's output. Calls come from the router with no lock held, in order; Done is the last call.
type Sweeper ¶
Sweeper removes what is past retention (design-agent.md §7.7), at the hub's start and every hour: expired day folders in every IP folder (a day folder is a UTC date, so an expired one is never being written), and processes/*.json whose last_seen is older than the retention (processes that will not come back: worker ids are new at every start). Sooner, once GoneAge old: a process file that says its process stopped (stopped_at, written by releases before a process removed its own file at its stop), and an orphaned temp file (a write cut short). Each process also removes its own expired files, and the files of its machine's gone processes.
func (*Sweeper) Sweep ¶
Sweep runs once over dir and returns the number of day folders and process files removed. Everything goes through an os.Root and refuses links: the share is writable by every machine, and the sweep must not delete anything outside it.
func (*Sweeper) SweepStatus ¶
SweepStatus removes, from a machine's local status folder (~/.maktaba/cluster/status: each local process's agent status), the files at least GoneAge old whose process no longer runs (its pid is gone), and temp files at least GoneAge old. A file whose pid still runs stays, however old: a live process rewrites its file only when its state changes. Links are never followed or removed.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Command relayfixture is the home side of the extension relay's two-process test (pipeline/tests/cluster/test_relay_two_process.py): the real cluster hub with the real service door, on a scratch Postgres database, reading the node registry (cluster_nodes), rules.relay and the Plex extension's row and token (home_secrets) from it.
|
Command relayfixture is the home side of the extension relay's two-process test (pipeline/tests/cluster/test_relay_two_process.py): the real cluster hub with the real service door, on a scratch Postgres database, reading the node registry (cluster_nodes), rules.relay and the Plex extension's row and token (home_secrets) from it. |