Documentation
¶
Overview ¶
Callers in the database: the assembly side (配置入库 P1, plan docs/plans/2026-11-03-caller-store-p1-plan.md T3).
The config layer owns the model (config.ApplyStoredCallers appends the stored rows and validates them); this file owns the ORDER of the startup / reload merge and the one write transaction a merge may need:
read the stored rows → a failure is fatal, never "no callers"
append + validate → an unusable row fails the start / the reload
config.Validate → the merged configuration must be acceptable
take over superseded → one transaction: superseded_at + disabled_at, orphan the
`caller:<id>` grants, one audit line (a file entry with the
same id has taken the identity over)
Nothing before the last step writes the database, so a merge that fails half way leaves no half-done takeover behind.
Index ¶
- Variables
- func MergeStoredCallers(cfg *config.Config, store *jobstore.Store, mode CallerMergeMode) error
- func NewJobAdopter(hub *wshub.Hub, jobs *job.Service) wshub.Adopter
- func PrepareCallerStore(cfg *config.Config, mode CallerMergeMode) (*jobstore.Store, error)
- type BuildOption
- type CallerMergeMode
- type ConfigSnapshot
- type Core
- func (c *Core) AddCaller(spec config.CallerSpec, actor string) (config.CallerChange, error)
- func (c *Core) Close() error
- func (c *Core) Config() *config.Config
- func (c *Core) DisableCaller(id, actor string) (config.CallerChange, error)
- func (c *Core) EnableCaller(id, actor string) (config.CallerChange, error)
- func (c *Core) ListCallerAudit(limit int) ([]jobstore.ConfigAuditEntry, error)
- func (c *Core) ListCallers() ([]config.CallerView, error)
- func (c *Core) Reload(path string) error
- func (c *Core) ReloadConfigReport() (config.ReloadResult, error)
- func (c *Core) ReloadDetailed(path string) (config.ReloadResult, error)
- func (c *Core) ReloadWith(cfg *config.Config) error
- func (c *Core) ReloadWithReport(cfg *config.Config, path string) (config.ReloadResult, error)
- func (c *Core) RotateCaller(id, actor string) (config.CallerChange, error)
- func (c *Core) Rules() *rule.Store
- func (c *Core) SetCallerCeiling(id string, ceil *config.CallerCeiling, noCeiling bool, actor string) (config.CallerChange, error)
- func (c *Core) SetCallerLimits(id string, lim config.CallerLimits, actor string) (config.CallerChange, error)
- func (c *Core) SetReloadHook(hook func(*config.Config))
- func (c *Core) Skills() *skill.Store
- func (c *Core) Snapshot() ConfigSnapshot
- func (c *Core) Update(mut func(*config.Config) error) error
- func (c *Core) UpdateCallers(fn func(next *config.Config, tx jobstore.CallerTx) error) (*ConfigSnapshot, error)
- func (c *Core) Workflow() *workflow.Engine
- func (c *Core) Xfer() *xfer.Manager
Constants ¶
This section is empty.
Variables ¶
var ErrStoreMarker = errors.New("this configuration has been migrated into the database; " +
"this version cannot read it: restore the backup taken before the migration, or upgrade gofer")
ErrStoreMarker is the refusal a configuration file carrying the P2 store marker gets from this version (D11). P1 cannot read a configuration whose entries live in the database, and continuing would silently run on whatever is left in the file.
Functions ¶
func MergeStoredCallers ¶ added in v0.211.0
MergeStoredCallers appends the stored callers to cfg, validates the result and (on the server path) takes over the rows a file entry supersedes. It mutates cfg: callers of a LIVE config must pass a clone (the reload path does, and startup's cfg is not published yet).
func NewJobAdopter ¶
NewJobAdopter builds the adoption seam that lets a hub starting after a serve restart adopt the `recovering` jobs a PREVIOUS serve process left in the store. It is exported so a harness standing up the same hub+job pair wires exactly what the server wires.
func PrepareCallerStore ¶ added in v0.211.0
PrepareCallerStore is the startup seam: refuse a marked configuration BEFORE opening the database (opening one would create an empty database beside the operator's real one and a future version would migrate it), open the metadata store, merge the stored callers and hand the store to Build (core.WithStore).
An error means the process must not start: a failed read of auth_callers is never read as "this deployment has no stored callers" (that would silently drop every stored identity and, on the next write, orphan nothing while the callers' tokens keep failing).
Types ¶
type BuildOption ¶
type BuildOption func(*buildOptions)
BuildOption customises Build.
func WithAgentDetector ¶
func WithAgentDetector(d agent.Detector) BuildOption
WithAgentDetector injects the agent.Detector that gates materialization of the built-in agent templates (agent.Resolve).
Production callers omit it and get agent.DefaultDetector(). TESTS must inject agent.NoopDetector{} (or a fake): with the real probe, the resolved agent set — and therefore cfg.Agents, the caps report and any agent-name assertion — would depend on which CLIs happen to be installed on the machine running `go test`.
The detector is remembered on the Core and reused by ReloadWith.
func WithBuiltinDefaultProject ¶
func WithBuiltinDefaultProject() BuildOption
WithBuiltinDefaultProject injects the built-in `default` project (the host's default workspace) when the config declares none. Every process that executes jobs opts in (serve, the MCP local backend, a worker): it is where gofer's own delivery jobs run when the session they serve belongs to no project (gofer-vin1), and a worker must therefore be able to run — and advertise — its OWN default workspace. The project is the machine's, so each machine derives it from its own config (WorkspaceDir); a server's `default` is never pushed to a worker (only projects naming a worker runner are). ReloadWith keeps the same choice, which is what re-adds it after a pushed Policy replaces the worker's project set.
func WithConfigPath ¶
func WithConfigPath(path string) BuildOption
WithConfigPath tells the Core which file its write transaction (Core.Update) persists to. serve passes the discovered config path; when empty the save path is resolved lazily to the user-level config (config.UserConfigPath), matching the old registry write-back behaviour.
func WithStore ¶ added in v0.211.0
func WithStore(store *jobstore.Store) BuildOption
WithStore hands Build an already-open metadata store instead of letting it open (and create) one. It is what the serve process uses after core.PrepareCallerStore: the stored callers must be merged into cfg BEFORE the registries and the job service are built from it, so the store has to be open earlier than Build.
A caller that does not pass it keeps the old behaviour (Build resolves the path and opens the store), which is the worker path: a worker never merges stored callers.
type CallerMergeMode ¶ added in v0.211.0
type CallerMergeMode int
CallerMergeMode says whether the merge may write the database.
const ( // CallerMergeServer is the serve process (startup and reload): it may take over a // superseded stored caller. CallerMergeServer CallerMergeMode = iota // CallerMergeReadOnly is a path that must not write the database (standalone mcp): // a superseded row is hidden in memory only, and the next server start does the // takeover (design: the CLI does not write the database). CallerMergeReadOnly )
type ConfigSnapshot ¶
ConfigSnapshot is one atomic (config, revision) generation. Rev is the config generation counter — Build seeds it at 1 and every write transaction (reloadLocked) bumps it by 1, so a worker/consumer can drop any Policy whose Rev is not strictly newer than the one it already applied. A given Rev value therefore identifies exactly ONE config content (B2 verification 5).
type Core ¶
type Core struct {
Projects *project.Registry
Agents *agent.Registry
Runners map[string]runner.Runner
Store *jobstore.Store
Jobs *job.Service
// Mail is the gofer 信箱's business layer (M2): sending a letter, resolving its
// address and parking what cannot be delivered. It is built here because it needs no
// process of its own — it reads and writes the same store and looks sessions up through
// the relay's Find. Always non-nil after Build.
Mail *mail.Service
// Hub is the ws-worker hub singleton (serve mounts it on /v1/workers/connect;
// every type=worker runner references this one instance). Always non-nil.
Hub *wshub.Hub
// RelayNonces and PtyRelays are live-only serve-side PTY relay state shared by
// worker dispatch, worker pty-connect (T5) and browser attach (T7).
RelayNonces *ptyrelay.NonceStore
PtyRelays *ptyrelay.Registry
// contains filtered or unexported fields
}
Core bundles the runtime objects assembled from a loaded config: the project/agent registries, the runner set, the SQLite metadata store and the job service. Both `serve` (HTTP control plane) and `mcp` (stdio MCP server) wire the same Core so the MCP tools reuse the identical job.Service (plan §P8: "MCP 内部复用 job.Service", 不复制执行逻辑).
func Build ¶
func Build(cfg *config.Config, opts ...BuildOption) (*Core, error)
Build assembles the registries, runner set, metadata store and job service from cfg. It is the single wiring point shared by serve and mcp; peer-http runners declared in config are registered too (plan §11.1, P7). It opens the SQLite metadata db (design §11 ResolveDBPath) and returns an error if that fails, since the job service cannot operate without it.
func (*Core) AddCaller ¶ added in v0.211.0
func (c *Core) AddCaller(spec config.CallerSpec, actor string) (config.CallerChange, error)
AddCaller creates one stored caller and answers its token ONCE. The id must be unused by every identity of this deployment — a stored row (enabled, disabled or superseded), a configuration-file caller, or a worker binding — because ids are never reused: a fresh token under a retired id would inherit the old identity's grants.
func (*Core) Close ¶
Close releases the Core's owned resources — currently the SQLite metadata store. Callers (serve/mcp) defer it for graceful shutdown so WAL is checkpointed and the db handle closed cleanly (design §14).
Worker connections close first (wshub.Hub.Shutdown waits until each dropped connection has put its jobs in `recovering` and persisted that). The job service shuts down next (job.Service.Shutdown: admission closed, the jobs this process runs cancelled and waited for, then their background work), so nothing still holds a connection when the store closes. The work / steward loops are not the Core's: they belong to the HTTP server, and serve stops them before this runs.
func (*Core) Config ¶
Config returns the current config pointer (= Snapshot().Cfg). It is the read-only accessor serve/etc use in place of the old bare Cfg field.
func (*Core) DisableCaller ¶ added in v0.211.0
func (c *Core) DisableCaller(id, actor string) (config.CallerChange, error)
DisableCaller switches a stored caller off: it authenticates nothing from the next request on, every permission resolution of it is empty, and no new job of its owner starts (the ceiling of the entry keeps bounding the jobs it already started). Idempotent.
func (*Core) EnableCaller ¶ added in v0.211.0
func (c *Core) EnableCaller(id, actor string) (config.CallerChange, error)
EnableCaller brings a stored caller back. Two facts are checked before the row changes, because enabling the wrong one would silently restore an identity:
- the id must not be claimed by a configuration-file caller or a worker binding — the merge would hide the row again, so the operator would believe the caller is back while it is not (the add path refuses the same collisions);
- a row a file entry took over must have been ROTATED after the takeover (D10): otherwise the token from before the file declared the id would work again.
func (*Core) ListCallerAudit ¶ added in v0.211.0
func (c *Core) ListCallerAudit(limit int) ([]jobstore.ConfigAuditEntry, error)
ListCallerAudit reports the config_audit lines of every caller change, newest first.
func (*Core) ListCallers ¶ added in v0.211.0
func (c *Core) ListCallers() ([]config.CallerView, error)
ListCallers reports every identity of this deployment in the management view: the configuration-file callers first (the operator's own, in file order), then the stored rows in creation order, including the disabled and the taken-over ones (an operator has to see what was taken away, and enable a disabled caller again).
func (*Core) Reload ¶
Reload re-loads the config from path and atomically swaps it into every component that holds a config snapshot — the project/agent registries and the job service (C3 SIGHUP hot-reload). It does NOT restart the process, touch in-flight jobs or reopen the jobstore.
🔴 It holds updateMu from the entry and reads the file INSIDE the lock (D-HIGH-4): a SIGHUP that read the file off-lock could load a stale file A, race a web Update that publishes B, then re-publish A as a newer Rev — disk B, memory A, the web edit lost. Locking the whole stat→load→overlay→reload closes that window.
Fail-safe: if the new config fails to load/validate, the OLD generation is kept (nothing is swapped) and the error is returned so the caller can log and keep serving.
LIMITATION: the runner instances in Core.Runners are built once at assemble time and are NOT rebuilt on reload. Swapping the config makes the peer-runner classification and every allowlist/validation observe the new config, but adding a brand-new runner TYPE (a new peer-http entry) still needs a restart to instantiate its runner. Reload covers adding/removing projects and agents and any config-derived validation.
func (*Core) ReloadConfigReport ¶
func (c *Core) ReloadConfigReport() (config.ReloadResult, error)
ReloadConfigReport re-reads the config file this Core OWNS — the same path its write transaction saves to (WithConfigPath, or the lazily resolved user-level config when none was configured) — and hot-swaps it in, returning the same structured result as ReloadDetailed. It is the manual reload behind POST /v1/config/reload (WEB-04③ V1.1): Windows has no SIGHUP, so an operator who edited the file by hand has no other way to apply it short of a restart.
The path resolution is deliberately the SAME code path as saveConfig, so "the file the console writes" and "the file a reload re-reads" can never be two different files (serve passes -c; a mismatch would make an edit vanish on the next reload).
func (*Core) ReloadDetailed ¶
func (c *Core) ReloadDetailed(path string) (config.ReloadResult, error)
ReloadDetailed is the reporting form of Reload. It keeps the legacy Reload error-only method available to embedders while exposing the generation and restart-only keys needed by HTTP and CLI callers.
func (*Core) ReloadWith ¶
ReloadWith swaps an ALREADY-BUILT config into every component that holds a config snapshot. It is the apply half of Reload, split out so a caller that obtains its config from somewhere other than a server config file (a worker builds one from worker.yaml) reuses the exact same apply path instead of re-implementing it.
Error semantics: the component Reloads are plain atomic.Store calls and CANNOT fail. The only error ReloadWith can return is the nil-config precondition. "A bad config keeps the old one" is achieved by BUILDING the new config completely (load/parse/validate) BEFORE calling this, so a bad config never reaches the apply stage.
The apply is safe against concurrent Submit: every consumer that needs more than one config-derived fact takes ONE snapshot and uses it throughout (job.Service.Submit resolves policy AND the agent argv from that one snapshot), so a submit racing this swap sees either the old config or the new one, never a mix. See Reload for the runner-instance limitation.
func (*Core) ReloadWithReport ¶
ReloadWithReport is the worker-side apply form of ReloadDetailed. path is the worker.yaml path used for the receipt; the config has already been parsed and validated by the caller before entering this method.
func (*Core) RotateCaller ¶ added in v0.211.0
func (c *Core) RotateCaller(id, actor string) (config.CallerChange, error)
RotateCaller replaces a stored caller's token and answers the new one once. Rotation is allowed on a disabled or taken-over row and does not change either state: it only makes the previous token useless (design §「用户生命周期」).
func (*Core) Rules ¶
Rules returns the JOB-06① rule library store (nil when the library was never built). It is the SAME store the job seam resolves bindings against and the one serve injects into httpapi (SetRules), so the CLI/HTTP surface and the injection path can never disagree about what a rule says.
func (*Core) SetCallerCeiling ¶ added in v0.211.0
func (c *Core) SetCallerCeiling(id string, ceil *config.CallerCeiling, noCeiling bool, actor string) (config.CallerChange, error)
SetCallerCeiling replaces (or removes, via noCeiling) a caller's upper bound. A stored caller is written in its row, a file caller through the config write transaction (D12); both are validated by the same rules before anything is written (D16).
func (*Core) SetCallerLimits ¶ added in v0.211.0
func (c *Core) SetCallerLimits(id string, lim config.CallerLimits, actor string) (config.CallerChange, error)
SetCallerLimits replaces a caller's quota overrides (concurrency / rate / burst). Same two paths as SetCallerCeiling; a zero field means "take the server.governance default".
func (*Core) SetReloadHook ¶
SetReloadHook installs a process-local observer for successful reloads. The callback must not perform network I/O; it runs in the serialized config transaction after the new snapshot is published.
func (*Core) Skills ¶
Skills returns the JOB-10 skill library store (nil when the library was never built). It is the SAME store the job seam above resolves bindings against and the one serve injects into httpapi (SetSkills), so the CLI/HTTP surface and the dispatch path can never disagree about what a skill contains.
Nil is a "not wired" answer, not a panic: an HTTP surface without it answers 503 (the same degradation /v1/xfer uses), which is what a caller built before Build wired the library must see.
func (*Core) Snapshot ¶
func (c *Core) Snapshot() ConfigSnapshot
Snapshot returns the current (cfg, rev) generation in a SINGLE atomic load, so the caller never observes a cfg from one generation and a rev from another.
func (*Core) Update ¶
Update is THE single serial config write transaction (B2). It clones the current snapshot, applies mut to the clone (project whole-value add/remove ONLY, per the project applier contract), saves the副本 to disk, then swaps the new generation into every component and marks it for broadcast. The whole clone→mut→save→reload runs under updateMu, so two concurrent writers can never clone the same snapshot / lose an update / mint two configs at one Rev.
Fail-safe: if mut or the save fails the OLD generation is untouched — nothing is swapped, disk is unchanged (save writes a副本, never the live config) and no broadcast happens. The policy broadcast is done by flushPush AFTER updateMu is released (never a network write under the lock, D-HIGH-5).
func (*Core) UpdateCallers ¶ added in v0.211.0
func (c *Core) UpdateCallers(fn func(next *config.Config, tx jobstore.CallerTx) error) (*ConfigSnapshot, error)
UpdateCallers is the caller write transaction (D4): it holds updateMu, clones the live config, lets fn write the caller rows and their audit lines, re-merges the DATABASE callers from the rows the transaction just wrote (so enabling a hidden row takes effect at once, and an unusable row fails here instead of at the next start), validates the candidate and only then publishes it.
It NEVER calls saveConfig: a stored caller does not belong in config.yaml (the file is projected to its own callers by config.Save), so an add on a deployment without a config file must not create one.
func (*Core) Workflow ¶
Workflow returns the Core's workflow engine (the handle serve/httpapi consume to drive job-chain workflows). Always non-nil after Build.