apps

package
v0.0.0-...-de45444 Latest Latest
Warning

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

Go to latest
Published: Jun 17, 2026 License: MIT Imports: 29 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 apps implements daemon-managed installed services (ADR-0009): the on-disk install layout, the package manifest (ensemble-service.yaml), the install record (install.yaml), and the Supervisor that spawns and watches installed services as plain child processes.

The package deliberately does not know about gRPC or the api package — the api layer consumes it through narrow interfaces (SupervisorGate / SpawnTokenChecker seams defined api-side), and the installer engine (a sibling ticket) shares the layout/manifest/record types defined here.

Index

Constants

View Source
const (
	StageResolving   = "resolving"
	StageDownloading = "downloading"
	StageVerifying   = "verifying"
	StageUnpacking   = "unpacking"
	StageInstalling  = "installing"
	StageDone        = "done"
)

Progress stages streamed by Install/Upgrade (string-typed for the same reason supervisor states are).

View Source
const (
	// FrontendChoiceManifest (the zero value) takes the manifest's tier on a
	// fresh install, or keeps the previously-accepted tier on an upgrade.
	FrontendChoiceManifest = ""
	// FrontendChoiceHeadless declines the frontend — install/keep backend-only.
	FrontendChoiceHeadless = "headless"
	// FrontendChoiceUI takes the manifest's launchable tier (used on upgrade to
	// add a UI a prior headless install declined).
	FrontendChoiceUI = "ui"
)

Frontend choices for InstallOptions.Frontend — the operator's install-time pick of the frontend tier, independent of what the manifest offers (ADR-0010 §3: frontend is an install-time presentation choice, not a runtime ceiling). A choice can only ever LOWER the tier (a downgrade is free) or restore the manifest's tier (which re-triggers consent on upgrade via capabilityGrowth); it can never take more frontend than the artifact ships.

View Source
const (
	SettingTypeString  = "string"
	SettingTypeInt     = "int"
	SettingTypeBool    = "bool"
	SettingTypeEnum    = "enum"
	SettingTypeAddress = "address" // an Ensemble "E…" address; format-only, advisory
)

Setting types (ADR-0009 §12). An empty/omitted type means "string".

View Source
const (
	FrontendNone            = "none"             // pure backend (default when absent)
	FrontendDeclarativePage = "declarative_page" // tier 1: a natively-rendered page
	FrontendLaunchedClient  = "launched_client"  // tier 3: ships its own desktop app
)

Frontend tiers (ADR-0010 §3, the closed union of ADR-0011 §1). A service declares the user-facing surface it brings; only launched_client drags a desktop runtime into the package. The discriminator is carried on Capabilities (it is consent-relevant — "this app installs and runs a desktop binary"), so it rides the publish/index/consent/install-record pipeline.

View Source
const DirName = "apps"

DirName is the install tree's directory under the daemon data dir. It is "apps", NOT "services": <data-dir>/services/<name>/ already belongs to the per-service identity keystore (internal/identity/service_keystore.go) and the two trees must never collide.

View Source
const ManifestFileName = "ensemble-service.yaml"

ManifestFileName is the package manifest at the root of every service archive (and therefore at the root of each unpacked release).

View Source
const SettingDefaultSelf = "${self}"

SettingDefaultSelf, used as a SettingDecl.Default, resolves at spawn time to the hosting node's OWN Ensemble address. It lets a service declare an owner/operator field that defaults to "whoever hosts me" — zero-config and footgun-free on a desktop self-host (the owner is bound to the app's own account, never a mistyped or pasted stranger), while a headless operator can still override it by setting the key in the operator overlay. The supervisor performs the resolution (see spawn); the daemon stays opaque to the value.

Variables

This section is empty.

Functions

func LoadOperatorEnv

func LoadOperatorEnv(path string) (map[string]string, error)

LoadOperatorEnv reads the overlay at path into a map. A missing file is not an error — it yields an empty map (no overlay). Malformed lines are skipped.

func MissingRequiredSettings

func MissingRequiredSettings(settings []SettingDecl, overlay map[string]string) []string

MissingRequiredSettings returns the keys of required settings that have no value in the operator overlay and no manifest default. It is advisory — the daemon never blocks a spawn on it (ADR-0009 §12). overlay is the overlay's key set (presence, not value); a declared default suppresses the warning, so a truly mandatory setting should leave `default` empty.

func ProbeRuntimes

func ProbeRuntimes(reqs []RuntimeRequirement) error

ProbeRuntimes checks every declared runtime requirement against the host (ADR-0009: declared, never provisioned). The returned error is nil when all requirements resolve, otherwise a human-readable reason suitable for the blocked state verbatim — "dotnet not found on PATH — install it on this machine", not a stack trace.

func Root

func Root(dataDir string) string

Root returns the install tree root for a daemon data dir.

func SaveOperatorEnv

func SaveOperatorEnv(path string, env map[string]string) error

SaveOperatorEnv atomically writes env to path mode 0600 (tmp + rename). An empty map removes the file — no overlay is the absence of the file, so a cleared overlay leaves nothing behind. Keys are validated and values are rejected if they contain a newline (the format has no escape for it).

func SortedEnvKeys

func SortedEnvKeys(env map[string]string) []string

SortedEnvKeys returns env's keys in lexical order.

func ValidEnvKey

func ValidEnvKey(k string) bool

ValidEnvKey reports whether k is a usable overlay key: a POSIX-shaped name ([A-Za-z_][A-Za-z0-9_]*) that is not a reserved spawn-contract var.

func ValidName

func ValidName(name string) bool

ValidName reports whether name is an acceptable service name (the same rule the identity keystore enforces). Exposed for the registry, whose published entry names become installed service names.

func ValidateSettingValue

func ValidateSettingValue(d SettingDecl, v string) error

ValidateSettingValue checks v against d's declared type/constraints. It is used to lint the manifest's own `default` and is available to the CLI/app for pre-save input validation. It is deliberately NOT called on operator overlay values by the daemon — the overlay stays opaque (ADR-0009 §12). Address types are advisory: their shape is not checked here.

Types

type Capabilities

type Capabilities struct {
	Transport          string `yaml:"transport" json:"transport"` // chat | http | rpc
	ACL                string `yaml:"acl" json:"acl"`             // public | contacts | allowlist
	DecidesConnections bool   `yaml:"decides_connections,omitempty" json:"decides_connections,omitempty"`
	HandlesFiles       bool   `yaml:"handles_files,omitempty" json:"handles_files,omitempty"`
	// Frontend is the ADR-0010 tier selector (none|declarative_page|
	// launched_client). It lives in the consent summary because a launched
	// client is consent-relevant (it installs and runs a desktop binary), but
	// it is NOT a runtime ceiling axis — Allows() never reads it, since a
	// registering backend has no frontend. Empty ⇒ none. The launched_client
	// arm's exec detail lives in Manifest.Client.
	Frontend        string   `yaml:"frontend,omitempty" json:"frontend,omitempty"`
	Commands        []string `yaml:"commands,omitempty" json:"commands,omitempty"`
	MaxPayloadBytes int64    `yaml:"max_payload_bytes,omitempty" json:"max_payload_bytes,omitempty"`
	// SubIdentities lets a supervised host register additional service
	// identities under its own `<host>/*` prefix at runtime (ADR-0007 §2) —
	// e.g. one room-host minting a dialable identity per room. It is an
	// install-time host property, shown at consent; the minted sub-identities
	// are ordinary default-deny services bounded by this host's ceiling. A
	// sub-identity's own runtime manifest cannot re-declare it (one level only).
	SubIdentities bool `yaml:"sub_identities,omitempty" json:"sub_identities,omitempty"`
}

Capabilities is the install-time declaration the operator consents to. It is enforced as a CEILING at RegisterService: a supervised process whose runtime manifest exceeds it is rejected — the consent prompt is meaningless if running code can ask for more than was shown (ADR-0009 §2).

func (Capabilities) Allows

func (c Capabilities) Allows(m services.Manifest) error

Allows checks a runtime registration manifest against this install-time ceiling. It returns nil when the registration stays within what the operator accepted, and a human-readable error naming the first violation otherwise (ADR-0009 §2).

type ClientApp

type ClientApp struct {
	Command []string `yaml:"command" json:"command"`
	Runtime Runtime  `yaml:"runtime,omitempty" json:"runtime,omitempty"`
}

ClientApp is the launched-client arm's static shape: a second argv (distinct from the supervised backend Entrypoint.Command) plus its own host-runtime requirements, probed the same way the backend's are. Relative to the release root, like the backend entrypoint. The supervisor never execs this — the app launches it on demand (ADR-0011 §2/§5); the daemon brokers the connection.

type ConsentRequiredError

type ConsentRequiredError struct {
	Name         string
	Version      string
	Capabilities Capabilities
	Grown        []string // upgrade only: the axes that grew vs the accepted set
	Verified     bool
}

ConsentRequiredError reports that an install/upgrade stopped at the consent gate. The artifact is staged; retrying the same call with AcceptCapabilities set completes without re-fetching.

func (*ConsentRequiredError) Error

func (e *ConsentRequiredError) Error() string

type Entrypoint

type Entrypoint struct {
	Command []string `yaml:"command"`
}

Entrypoint is the argv the supervisor execs, relative to the release root.

type EnvView

type EnvView struct {
	Keys            []string
	Settings        []SettingDecl
	MissingRequired []string
}

EnvView is the read side of a service's operator env (the GetServiceEnv RPC): the overlay key names that are SET (values are write-only), the manifest's declared-settings schema (the typed shape — ADR-0009 §12), and any required-but-unset settings (advisory). It is what the CLI/app need to render a typed settings form: Settings supplies the shape, Keys says which are set.

type InstallOptions

type InstallOptions struct {
	// AcceptCapabilities is the operator's consent to the manifest's
	// declared capabilities (install) or to a grown capability set
	// (upgrade). Without it the call fails with *ConsentRequiredError
	// carrying what needs consenting to — the staged artifact is kept so
	// the retry-with-consent doesn't re-download.
	AcceptCapabilities bool
	// Enable marks the service enabled in install.yaml (the supervisor
	// spawns it on the next Refresh).
	Enable bool
	// Frontend is the operator's frontend-tier choice (FrontendChoiceManifest |
	// FrontendChoiceHeadless | FrontendChoiceUI). It overrides what tier is
	// recorded in InstallRecord.Accepted.Frontend — the value every downstream
	// gate (BrokerLaunch, the lobby affordance) reads — without touching the
	// manifest. Empty ⇒ take the manifest tier (install) / keep the prior tier
	// (upgrade).
	Frontend string
}

InstallOptions tune one Install/Upgrade call.

type InstallRecord

type InstallRecord struct {
	Name    string `yaml:"name"`
	Version string `yaml:"version"`
	// Source records where the artifact came from: "registry:<registry-name>",
	// "url:<artifact-url>", or "local:<path>". Anything but registry:* renders
	// as `unverified` in UI/CLI output (ADR-0009 §8).
	Source string `yaml:"source"`
	// SHA256 of the artifact archive as verified at install time (empty for
	// unverified local installs).
	SHA256   string       `yaml:"sha256,omitempty"`
	Accepted Capabilities `yaml:"accepted"`
	Enabled  bool         `yaml:"enabled"`
	// PreviousVersion names the retained rollback release under releases/
	// (one step, per ADR-0009 §3). Empty until the first upgrade.
	PreviousVersion string `yaml:"previous_version,omitempty"`
	// ClientCommand is the launched client's argv (relative to the current
	// release root) when Accepted.Frontend == FrontendLaunchedClient — persisted
	// so the lobby knows an installed app has a launchable face, and how to exec
	// it, without re-reading the release manifest. Empty for non-client tiers.
	ClientCommand []string `yaml:"client_command,omitempty"`

	InstalledAt time.Time `yaml:"installed_at"`
	UpdatedAt   time.Time `yaml:"updated_at"`
}

InstallRecord is install.yaml — the per-service provenance + operator-intent record (ADR-0009 §3). The installer writes it at install/upgrade time; the supervisor reads it (and owns the Enabled flag thereafter). Accepted is the capability set the operator consented to — the ceiling RegisterService is checked against, and the diff base for upgrade re-prompts.

func LoadInstallRecord

func LoadInstallRecord(path string) (*InstallRecord, error)

LoadInstallRecord reads install.yaml from path.

func (*InstallRecord) Save

func (r *InstallRecord) Save(path string) error

Save writes the record atomically (tmp + rename, the routing_table.json / admin_key.hex precedent — a crash mid-write must not leave a torn record).

func (*InstallRecord) Verified

func (r *InstallRecord) Verified() bool

Verified reports whether the artifact came through a subscribed registry (signed index + hash pin) rather than a direct URL / local path.

type Installer

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

Installer is everything between "I want this service" and files on disk the Supervisor can run (ADR-0009): resolve → fetch → sha256 → unpack → validate → atomic promote, previous release kept for rollback. It owns no processes and no RPC surface — the api layer orchestrates it together with the Supervisor.

func NewInstaller

func NewInstaller(dataDir string) *Installer

NewInstaller builds an Installer rooted at dataDir.

func (*Installer) Install

Install fetches, verifies, and installs a NEW service. Installing over an existing name is refused — that's Upgrade.

func (*Installer) Records

func (i *Installer) Records() ([]*InstallRecord, error)

Records loads every install.yaml under the apps tree, sorted by name.

func (*Installer) Rollback

func (i *Installer) Rollback(name string) (*InstallRecord, error)

Rollback flips an installed service back to its previous release. The accepted capability set reverts to that release's manifest — the operator accepted those when it was current.

func (*Installer) SweepStaging

func (i *Installer) SweepStaging()

SweepStaging clears the consent cache and stray downloads. Called once at daemon startup — a staging tree only needs to outlive its consent prompt.

func (*Installer) Uninstall

func (i *Installer) Uninstall(name string, keepData bool) error

Uninstall removes an installed service's files. keepData preserves data/ (a future reinstall under the same name resumes both identity and state). Identity is NOT touched here — purging it is registry.Delete (RotateBundle), orchestrated by the api layer per ADR-0009 §6.

func (*Installer) Upgrade

func (i *Installer) Upgrade(ctx context.Context, name string, spec SourceSpec, opt InstallOptions, pf ProgressFunc) (*InstallRecord, error)

Upgrade swaps an installed service to a new artifact. Identity and data/ are untouched (same name = same identity, ADR-0009 §6); the previous release is kept for Rollback. A capability set that GREW versus what the operator accepted requires fresh consent; equal-or-narrower does not.

type LaunchSpec

type LaunchSpec struct {
	Ready      bool
	Reason     string
	Command    []string          // absolute argv: client entrypoint under current/, then its args
	Env        map[string]string // the ENSEMBLE_* spawn contract for the client
	WorkingDir string            // current release root, like a supervised backend's cwd
}

LaunchSpec is everything the app needs to exec a service's launched client (ADR-0010 §3 tier 3 / ADR-0011). Ready=false with a Reason means the client cannot launch right now (a declared runtime is missing, or the installed release won't read); Command/Env are then empty and NO grant was minted.

type LogLine

type LogLine struct {
	Line string
	TS   time.Time
}

LogLine is one captured stdout/stderr line from a supervised child.

type Manifest

type Manifest struct {
	Name         string            `yaml:"name"`
	Version      string            `yaml:"version"`
	Description  string            `yaml:"description,omitempty"`
	Entrypoint   Entrypoint        `yaml:"entrypoint"`
	Runtime      Runtime           `yaml:"runtime,omitempty"`
	Env          map[string]string `yaml:"env,omitempty"`
	Capabilities Capabilities      `yaml:"capabilities"`
	// Client is the launched desktop frontend the service brings (ADR-0010 §3
	// tier 3 / ADR-0011 §1). It is present iff Capabilities.Frontend ==
	// FrontendLaunchedClient: the tier discriminator lives with the consent
	// summary (Capabilities), the exec detail lives here because an argv is not
	// a capability. The app launches this on demand and brokers its daemon
	// connection (the launch MECHANISM is the launcher-fabric ticket); this
	// manifest only declares the static shape.
	Client *ClientApp `yaml:"client,omitempty"`
	// Settings declares the env-var options this service reads — the typed
	// SHAPE of its configuration (ADR-0009 §12), distinct from Env (which
	// supplies static VALUES). The daemon never type-checks operator values
	// against this; it is metadata the CLI/app use to render a typed settings
	// form and a soft missing-required warning. The operator's actual values
	// live write-only in the per-service env overlay (ADR-0009 §11).
	Settings []SettingDecl `yaml:"settings,omitempty"`
}

Manifest is the package manifest (ensemble-service.yaml, ADR-0009 §2).

func LoadManifest

func LoadManifest(releaseDir string) (*Manifest, error)

LoadManifest reads and validates the manifest from a release root dir.

func ParseManifest

func ParseManifest(data []byte) (*Manifest, error)

ParseManifest decodes and validates manifest bytes.

func (*Manifest) ClientRuntimeRequirements

func (m *Manifest) ClientRuntimeRequirements() []RuntimeRequirement

ClientRuntimeRequirements returns the launched client's host-runtime probes, or nil when the service brings no launched client. The launcher fabric probes these at launch (ProbeRuntimes) the way the supervisor probes the backend's before spawn — a missing client runtime is a clean blocked state, not a launch-time crash.

func (*Manifest) FrontendKind

func (m *Manifest) FrontendKind() string

FrontendKind returns the declared frontend tier, normalising the absent/empty declaration to FrontendNone so callers switch on one canonical value.

func (*Manifest) Validate

func (m *Manifest) Validate() error

Validate checks the manifest's structural rules.

type Paths

type Paths struct {
	Dir           string // <data-dir>/apps/<name>
	ReleasesDir   string // …/releases
	CurrentLink   string // …/current (symlink)
	DataDir       string // …/data
	LogsDir       string // …/logs
	LogFile       string // …/logs/service.log
	InstallRecord string // …/install.yaml
	OperatorEnv   string // …/operator-env
}

Paths is the resolved on-disk layout for one installed service (ADR-0009 §3):

<data-dir>/apps/<name>/
  releases/<version>/   unpacked archives; current + previous kept
  current               symlink to releases/<version>, flipped atomically
  data/                 service-owned persistent state (survives upgrades)
  logs/service.log      supervisor-captured stdout+stderr
  install.yaml          provenance + accepted capabilities + enabled flag
  operator-env          operator-only env overlay (0600; never an artifact)

func ServicePaths

func ServicePaths(dataDir, name string) Paths

ServicePaths resolves the layout for name under dataDir. It does not touch the filesystem.

func (Paths) ReleaseDir

func (p Paths) ReleaseDir(version string) string

ReleaseDir returns the unpack destination for one version.

type Progress

type Progress struct {
	Stage      string
	Message    string
	BytesDone  int64
	BytesTotal int64
}

Progress is one install/upgrade progress tick.

type ProgressFunc

type ProgressFunc func(Progress)

ProgressFunc receives progress ticks; may be nil.

type Runtime

type Runtime struct {
	Requires []RuntimeRequirement `yaml:"requires,omitempty"`
}

Runtime declares (never provisions) what the host machine must already provide. The supervisor probes these before each spawn; a missing requirement parks the service in the blocked state with a human-readable reason instead of crash-looping (ADR-0009 §2).

type RuntimeRequirement

type RuntimeRequirement struct {
	Binary     string `yaml:"binary"`
	MinVersion string `yaml:"min_version,omitempty"`
}

RuntimeRequirement is one probe: a binary that must resolve on PATH, with an optional minimum version checked via `<binary> --version`.

type SettingDecl

type SettingDecl struct {
	Key         string   `yaml:"key" json:"key"`
	Label       string   `yaml:"label,omitempty" json:"label,omitempty"`
	Description string   `yaml:"description,omitempty" json:"description,omitempty"`
	Type        string   `yaml:"type,omitempty" json:"type,omitempty"` // string|int|bool|enum|address ("" = string)
	Default     string   `yaml:"default,omitempty" json:"default,omitempty"`
	Required    bool     `yaml:"required,omitempty" json:"required,omitempty"`
	Secret      bool     `yaml:"secret,omitempty" json:"secret,omitempty"` // orthogonal to type; drives masking
	Enum        []string `yaml:"enum,omitempty" json:"enum,omitempty"`     // allowed values when type=enum
	Min         *int64   `yaml:"min,omitempty" json:"min,omitempty"`       // type=int lower bound, when set
	Max         *int64   `yaml:"max,omitempty" json:"max,omitempty"`       // type=int upper bound, when set
}

SettingDecl declares one env-var option a service reads — the typed shape of the option, NOT its value. The daemon stays opaque to values (the overlay is a dumb string store, ADR-0009 §11); the only consumers of this declaration are the CLI and app, which render a typed form from it (ADR-0009 §12).

func (SettingDecl) TypeOrDefault

func (d SettingDecl) TypeOrDefault() string

TypeOrDefault returns the declared type, defaulting to "string".

type SourceSpec

type SourceSpec struct {
	// Raw is one of: an http(s) URL to a .tar.gz artifact, a daemon-local
	// path (archive file or unpacked dir — the dev loop), or a forge release
	// spec "owner/repo@tag" (requires Forge).
	Raw string
	// Forge is the forge base URL (e.g. https://forge.example.com) for
	// owner/repo@tag specs.
	Forge string
	// ForgeKind selects the release-API adapter: "gitea" (default) or
	// "github".
	ForgeKind string
	// SHA256 is the expected artifact hash; empty means unverified (the
	// hash is computed and recorded, but nothing attests it).
	SHA256 string
	// Label overrides the install.yaml Source provenance when set. The
	// registry resolver uses it ("registry:<addr>/<name>@<version>") so the
	// record reflects WHO blessed the artifact, not just where the bytes
	// came from — InstallRecord.Verified keys off this prefix.
	Label string
}

SourceSpec is the raw "where from" of an install/upgrade as it arrives over the API: a spec string plus optional forge hints. Resolution to bytes happens daemon-side. Registry-based name resolution (the next ticket) slots in as another spec form without touching the callers.

type State

type State string

State is a supervised service's lifecycle state (ADR-0009 §4). States are strings on purpose — they ride the JSON DaemonEvent path and proto as-is, dodging the enum-marshals-as-number trap.

const (
	StateStopped  State = "stopped"  // not running, operator intent = disabled (or never started)
	StateStarting State = "starting" // spawned, inside the readiness window
	StateRunning  State = "running"  // RegisterService completed; the stream is the liveness signal
	StateBackoff  State = "backoff"  // crashed or failed readiness; waiting to respawn
	StateBlocked  State = "blocked"  // a declared runtime is missing; no spawn attempts
	StateErrored  State = "errored"  // gave up after maxFailures consecutive failures
	StateStopping State = "stopping" // graceful stop in flight
)

type Status

type Status struct {
	Name      string
	Version   string
	State     State
	Reason    string // human-readable, set for blocked/errored/backoff
	PID       int    // 0 when not running
	Restarts  int    // consecutive failures in the current crash cycle
	Enabled   bool
	StartedAt time.Time // last successful spawn; zero if never
}

Status is the supervisor's snapshot of one installed service.

type Supervisor

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

Supervisor owns the lifecycle of every installed service under <data-dir>/apps (ADR-0009 §1): runtime probe → spawn with the env contract → readiness window → restart with backoff → give-up. It is fully async from the daemon's own lifecycle — a crash-looping service costs one goroutine and a log line, never daemon stability.

func NewSupervisor

func NewSupervisor(dataDir, socketPath string, notify func(Status)) *Supervisor

NewSupervisor builds a Supervisor rooted at dataDir whose children dial socketPath. notify (nil-ok) receives a Status on every state change.

func (*Supervisor) AuthorizeRegister

func (s *Supervisor) AuthorizeRegister(name, token string, m services.Manifest) error

AuthorizeRegister gates a RegisterService. Three cases:

  • The name is a directly-installed service → claimable only by the supervisor's own child carrying that name's current spawn token, within the install-time accepted capability ceiling (ADR-0009 §2/§5).
  • The name is NOT installed but the caller presents a live spawn token → the caller is a supervised child, and it may register ONLY a sub-identity under its OWN prefix `<host>/<sub>` (ADR-0007 §2): the host must have declared sub_identities at install, and the sub-identity stays within the host's ceiling. Anything else from a tokened child is refused — a spawn token authorises its own name and its namespace, nothing more.
  • No installed name and no spawn token → an external, admin-signed registration (the operator is already maximally privileged); pass through.

func (*Supervisor) BrokerLaunch

func (s *Supervisor) BrokerLaunch(name string) (LaunchSpec, error)

BrokerLaunch resolves name's launched client into a LaunchSpec (ADR-0010 §3 / ADR-0011). It verifies the service declares a launched_client frontend, probes the client's declared runtimes, and — only when ready — mints a scoped launch grant and assembles the absolute argv plus the ENSEMBLE_* env contract. A missing runtime (or an unreadable release) is a ready=false spec with a verbatim reason, not an error; an error is reserved for "this service has no launchable client", a caller/UI mistake worth surfacing as a failure.

func (*Supervisor) FollowLogs

func (s *Supervisor) FollowLogs(name string) (<-chan LogLine, func(), error)

FollowLogs subscribes to name's live log lines. Cancel must be called.

func (*Supervisor) GetEnv

func (s *Supervisor) GetEnv(name string) (EnvView, error)

GetEnv returns a service's operator-env read view: the overlay's set key names (sorted, values never returned — the overlay carries secrets) plus the declared-settings schema and missing-required keys from the current release's manifest. A manifest that is unreadable (e.g. mid-install) degrades to keys-only rather than failing the listing.

func (*Supervisor) LookupLaunchGrant

func (s *Supervisor) LookupLaunchGrant(token string) (string, bool)

LookupLaunchGrant returns the service a live launch grant authorises, or ("", false) when the token is unknown or expired. The client↔service transport (ADR-0011 §5) calls this to bind an attaching launched client to its service; an expired grant is dropped on lookup.

func (*Supervisor) NotifyRegistered

func (s *Supervisor) NotifyRegistered(name string)

NotifyRegistered tells the supervisor name completed RegisterService — the readiness signal (ADR-0009 §4). Unsupervised names no-op.

func (*Supervisor) NotifyUnregistered

func (s *Supervisor) NotifyUnregistered(name string)

NotifyUnregistered tells the supervisor name's register stream dropped — the liveness signal. A running child whose stream drops without exiting is unhealthy and gets restarted.

func (*Supervisor) Refresh

func (s *Supervisor) Refresh()

Refresh re-scans <data-dir>/apps, picking up installs, upgrades, and uninstalls. The installer calls this after mutating the tree; it is also how Start discovers the initial set. Unknown junk in the tree is skipped with a log line, never fatal.

func (*Supervisor) SetEnv

func (s *Supervisor) SetEnv(name string, set map[string]string, unset []string, replace bool) ([]string, bool, error)

SetEnv mutates an installed service's operator env overlay (ADR-0009 §11) and applies it: when replace is false the change merges into the existing overlay (set overwrites, unset removes); when replace is true the overlay becomes exactly set. The merged result is persisted 0600 to the service's install dir, then — if the service is currently enabled and the supervisor is live — the child is restarted in place so the new environment takes effect (the persisted enabled intent is untouched). Returns the resulting overlay key names (sorted, never values) and whether a restart happened.

func (*Supervisor) SetSelfAddr

func (s *Supervisor) SetSelfAddr(fn func() string)

SetSelfAddr wires the provider that resolves the hosting node's own Ensemble address, used to materialise ${self} setting defaults at spawn (see SettingDefaultSelf). The daemon sets this once after construction; a nil provider (or one returning "") simply leaves such settings unset.

func (*Supervisor) Start

func (s *Supervisor) Start()

Start scans the install tree and launches every enabled service. Call it only after the gRPC API is serving — readiness is a successful RegisterService, which needs a listening socket (ADR-0009 §4).

func (*Supervisor) StartService

func (s *Supervisor) StartService(name string) error

StartService enables + launches an installed service (persisting the intent), clearing any errored give-up. The installer's StartService RPC lands here.

func (*Supervisor) Statuses

func (s *Supervisor) Statuses() []Status

Statuses snapshots every supervised service, sorted by name.

func (*Supervisor) Stop

func (s *Supervisor) Stop()

Stop tears every child down (SIGTERM → deadline → SIGKILL each) and waits for the loops to exit. Called from Daemon.Stop BEFORE the gRPC server shuts down, so children can unregister cleanly instead of holding GracefulStop hostage with their bidi streams.

func (*Supervisor) StopService

func (s *Supervisor) StopService(name string) error

StopService stops a service and persists Enabled=false so a daemon restart leaves it down.

func (*Supervisor) TailLogs

func (s *Supervisor) TailLogs(name string, n int) ([]LogLine, error)

TailLogs returns up to n recent log lines for name, oldest first.

func (*Supervisor) ValidToken

func (s *Supervisor) ValidToken(token string) bool

ValidToken reports whether token is a currently-live spawn token for any supervised child. The admin stream interceptor consults this to admit a supervised child's RegisterService through admin gating (ADR-0009 §5); name-binding is enforced separately by AuthorizeRegister.

Jump to

Keyboard shortcuts

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