Documentation
¶
Overview ¶
Package flows is muster's BROWSER-FLOW queue: a closed catalogue of named flows, an owner-scoped job table (migration 0012), and the per-(owner, host) runner tokens a host-side runner drains it with.
The shape, end to end:
owner (browser session, or a personal mst_ token) ── enqueue ──► flow_jobs (queued)
host runner (mfr_ runner token, outbound long-poll) ── claim ──► running (leased)
── report ─► done | failed | needs_operator
muster never reaches into a host and never holds a browser credential: the runner dials OUT, claims a job addressed to its own host, re-validates it against its OWN copy of the catalogue, runs a fixed argv, and reports.
🔴 THE CATALOGUE IS COMPILED IN, NOT API-WRITABLE. A flow is a name, a class and a parameter schema; nothing a caller sends can widen it. Every parameter has a length cap and a pattern, and unknown parameters are refused, so a job's params are data the runner hands to a fixed executable as argv — never a URL, a selector or a script.
🔴 WHO MAY ENQUEUE is decided in internal/api, not here: a browser session or the owner's personal API token. The shared hook and service tokens are refused by construction (the routes sit behind requireAPIToken, which admits only mst_ tokens), because the hook token acts as the admin and is held by every hook script on every host.
Index ¶
- Constants
- Variables
- func AgentTextRefusal(text string, words []string) string
- func HashRunnerToken(token string) string
- func HiddenCharRefusal(v string) string
- func Names() []string
- func NewRunnerToken() (string, error)
- func NormalizeAgentText(v string) string
- func OutboundTextRefusal(text string, words []string) string
- func RunnerTokenShapeOK(token string) bool
- func StripSecretShaped(text string) (string, int)
- func UnescapeVisible(s string) (string, bool)
- func ValidHost(host string) error
- func ValidInstance(instance string) error
- func VisibleEscape(v string) string
- type Class
- type Flow
- type FlowRequest
- type Job
- type Outcome
- type PGStore
- func (s *PGStore) AuthenticateRunner(ctx context.Context, token string) (RunnerToken, error)
- func (s *PGStore) Cancel(ctx context.Context, id int64) (Job, error)
- func (s *PGStore) Claim(ctx context.Context, host string, instances []string, runnerTokenID int64) (Job, bool, error)
- func (s *PGStore) CreateRunnerToken(ctx context.Context, host string) (string, RunnerToken, error)
- func (s *PGStore) DecideRequest(ctx context.Context, id int64, approve bool, by string) (FlowRequest, *Job, error)
- func (s *PGStore) Enqueue(ctx context.Context, r Request, via, by string) (Job, error)
- func (s *PGStore) FileRequest(ctx context.Context, agentID, ownerID int64, agentName string, r Request, ...) (FlowRequest, error)
- func (s *PGStore) Get(ctx context.Context, id int64) (Job, error)
- func (s *PGStore) Heartbeat(ctx context.Context, id int64, host string) (Job, error)
- func (s *PGStore) List(ctx context.Context, limit int) ([]Job, error)
- func (s *PGStore) ListRequests(ctx context.Context, limit int) ([]FlowRequest, error)
- func (s *PGStore) ListRunnerTokens(ctx context.Context) ([]RunnerToken, error)
- func (s *PGStore) Report(ctx context.Context, id int64, host string, res Result) (Job, error)
- func (s *PGStore) RequestForAgent(ctx context.Context, agentID, id int64) (FlowRequest, error)
- func (s *PGStore) RevokeRunnerToken(ctx context.Context, id int64) (bool, error)
- func (s *PGStore) WithAgentDenyWords(words []string) *PGStore
- type Param
- type Request
- type RequestStatus
- type Result
- type RunnerToken
- type Status
- type Store
Constants ¶
TTL bounds. A queued job not claimed within its TTL becomes `expired`, but time it spends blocked behind another job on the same browser does not count, up to MaxTTLPause (90 min) per blocker (store.go). So a queued job runs within its TTL plus its blocked time; behind a chain of dispatches that can be hours. That is intended, because a dispatch chain is queued, not refused. A send composed for a specific moment (a Muse message meant for "now") should therefore be enqueued with a short TTL on an idle instance.
const LeaseDuration = 2 * time.Minute
LeaseDuration is how long a claim (or a heartbeat) holds a job. A runner heartbeats well inside it; a runner that goes silent loses the job when it lapses — a READ job is queued again, a WRITE job goes to needs_operator.
const MaxOutputBytes = 65536
MaxOutputBytes caps a job's stored output (the 0012 CHECK); a longer report is truncated at a UTF-8 boundary, never refused.
const MaxPendingPerOwner = 20
MaxPendingPerOwner bounds an owner's queued + running jobs. One browser runs one flow at a time, so a deep queue is only ever a stuck runner or a loop.
const MaxPendingRequestsPerAgent = 3
MaxPendingRequestsPerAgent bounds an agent's undecided requests — the connector store's per-agent shape (connectors.MaxPendingGrantsPerAgent).
const MaxReasonRunes = 300
MaxReasonRunes caps an agent's stated reason.
const MaxTTLPause = 90 * time.Minute
MaxTTLPause is the PER-BLOCKER ceiling on the ttl credit a queued job earns while it waits behind one running job on its browser instance (round-2 F-A, round-3). Sized from the longest LEGITIMATE hold of one instance, a muse dispatch: the pacing gap waited inside the job (10 min, the muse wrapper's default MUSE_MIN_SEND_GAP_MIN) + MaxWaitSeconds (60 min) + the runner's 240 s slack = 74 min, plus 16 min of headroom = 90 min.
It caps EACH blocking interval, never a job's lifetime total: a job behind two long dispatches is credited both holds. While a job is blocked its deadline is expires_at + ttl_paused (credit from earlier blockers) + the time the CURRENT blocker has held it, at most MaxTTLPause. So a job only expires while blocked if its ttl ran out before this block began, or if the blocker has run longer than MaxTTLPause — a wedged runner heartbeating forever. Then the queue behind it clears within MaxTTLPause + the jobs' remaining ttl of the block starting, and the owner's MaxPendingPerOwner self-clears.
const MaxWaitSeconds = 3600
MaxWaitSeconds bounds muse.send's wait. The runner's job timeout is wait+240s, and it heartbeats inside the lease the whole time.
const RequestTTL = time.Hour
RequestTTL is how long a request waits for its owner's decision before it expires (and can no longer be approved).
const RunnerTokenPrefix = "mfr_"
RunnerTokenPrefix starts every runner token, so the runner door can refuse every other credential (the hook token, a personal token) before a database read.
const SecretRemoved = "[removed]"
SecretRemoved is what StripSecretShaped puts where it removed something.
Variables ¶
var ( // ErrNotFound: no such job FOR THIS PRINCIPAL. Another owner's job is // indistinguishable from one that does not exist (row-level security). ErrNotFound = errors.New("flows: job not found") // ErrState: the job exists but is not in a state that allows this. ErrState = errors.New("flows: the job is not in a state that allows this") // ErrPendingCap: the owner already has MaxPendingPerOwner unfinished jobs. ErrPendingCap = errors.New("flows: too many unfinished jobs") // ErrBadRunnerToken: unknown, revoked, or its owner is disabled. ErrBadRunnerToken = errors.New("flows: unknown or revoked runner token") )
Errors the API maps to status codes.
var ErrInvalid = errors.New("invalid flow request")
ErrInvalid wraps every validation refusal: the caller answers 400 with its message.
var ErrTooManyPendingRequests = errors.New("flows: too many pending flow requests from this agent")
ErrTooManyPendingRequests: the agent already has MaxPendingRequestsPerAgent undecided requests.
Functions ¶
func AgentTextRefusal ¶
AgentTextRefusal reports why agent-composed free text is refused, or "". words are the deployment's OWN infrastructure names (cluster, host and project names — MUSTER_FLOW_AGENT_DENY_WORDS): they are configuration, not source, because this repository is public and may not name them.
func HashRunnerToken ¶
HashRunnerToken is the stored form of a runner token.
func HiddenCharRefusal ¶
HiddenCharRefusal reports why v is refused for carrying a character its approver could not see, or "". v is expected to be NFKC already.
func NewRunnerToken ¶
NewRunnerToken mints RunnerTokenPrefix + 43 base64url characters (256 bits).
func NormalizeAgentText ¶
NormalizeAgentText is the form an agent-composed value is screened, stored, shown and sent in: NFKC, so compatibility look-alikes (full-width letters, ligatures, the many Unicode spaces) are folded to the plain characters the ASCII deny patterns and the owner's eyes both read.
func OutboundTextRefusal ¶ added in v0.215.0
OutboundTextRefusal is AgentTextRefusal for an officer's OUTBOUND draft (internal/plugins outbound.go): public host names and URLs pass, so a post can link to the project; internal host names, IP addresses, secrets, infrastructure words and the deployment's own names are refused as ever. 🔴 Only an outbound draft of a plugin bound to an officer is screened by this; every other agent text keeps AgentTextRefusal.
func RunnerTokenShapeOK ¶
RunnerTokenShapeOK reports whether token is shaped like one NewRunnerToken mints. A FILTER, not authentication: the hash lookup is the property.
func StripSecretShaped ¶ added in v0.113.0
StripSecretShaped is text with every credential-shaped or long token-shaped run (secretShapedDeny: the screen's secret patterns, and only those) replaced by SecretRemoved, and how many runs it replaced.
func UnescapeVisible ¶
UnescapeVisible inverts VisibleEscape. ok is false on anything VisibleEscape cannot have produced.
func ValidInstance ¶
ValidInstance reports whether instance is a legal browser instance label.
func VisibleEscape ¶
VisibleEscape renders v so that NOTHING in it is left to the eye's guess: printable ASCII is itself (a backslash is doubled), newline and tab are the two-character escapes \n and \t, and every other code point — every non-ASCII letter included, since a look-alike letter reads as the ASCII one — is \u{HEX}. The mapping is one-to-one, so the card can be decoded back to the exact bytes (UnescapeVisible); the approval test does exactly that.
Types ¶
type Class ¶
type Class string
Class is whether a flow only reads from the operator's accounts or writes to them. It decides what a lost lease means: a read is safe to run again, a write may already have been delivered and must go to a human.
type Flow ¶
type Flow struct {
Name string
Class Class
Params []Param
// Help is the one-line description of what the flow does.
Help string
}
Flow is one catalogue entry.
type FlowRequest ¶
type FlowRequest struct {
ID int64 `json:"id"`
OwnerID int64 `json:"ownerId"`
// AgentID is nil once the agent has been deleted: the request stays, as
// the record of what was asked and decided (0014: ON DELETE SET NULL).
AgentID *int64 `json:"agentId,omitempty"`
AgentName string `json:"agentName"`
Flow string `json:"flow"`
Host string `json:"host"`
Instance string `json:"instance"`
Params map[string]string `json:"params"`
Reason string `json:"reason"`
Status RequestStatus `json:"status"`
JobID *int64 `json:"jobId,omitempty"`
CreatedAt time.Time `json:"createdAt"`
ExpiresAt time.Time `json:"expiresAt"`
DecidedAt *time.Time `json:"decidedAt,omitempty"`
}
FlowRequest is one row of flow_requests.
type Job ¶
type Job struct {
ID int64 `json:"id"`
OwnerID int64 `json:"ownerId"`
Flow string `json:"flow"`
Class Class `json:"class"`
Host string `json:"host"`
Instance string `json:"instance"`
Params map[string]string `json:"params"`
Status Status `json:"status"`
RequestedVia string `json:"requestedVia"`
RequestedBy string `json:"requestedBy"`
Attempts int `json:"attempts"`
CreatedAt time.Time `json:"createdAt"`
ExpiresAt time.Time `json:"expiresAt"`
ClaimedAt *time.Time `json:"claimedAt,omitempty"`
LeaseUntil *time.Time `json:"leaseUntil,omitempty"`
FinishedAt *time.Time `json:"finishedAt,omitempty"`
ExitCode *int `json:"exitCode,omitempty"`
Output string `json:"output"`
Detail string `json:"detail"`
}
Job is one row of flow_jobs.
type Outcome ¶
type Outcome string
Outcome is what a runner may report. A job is never reported back to queued: re-running is the server's decision (a lost READ lease), never the runner's.
type PGStore ¶
type PGStore struct {
// contains filtered or unexported fields
}
PGStore is Store over Postgres (migration 0012).
func (*PGStore) AuthenticateRunner ¶
AuthenticateRunner resolves a runner token to its record and stamps its use. A revoked token, an unknown one and one whose owner is disabled are all ErrBadRunnerToken.
func (*PGStore) Cancel ¶
Cancel withdraws a queued job, or dismisses one that needs the operator. A running job cannot be cancelled from here: the runner owns it until it reports or its lease lapses (stop the runner unit to stop it now).
func (*PGStore) Claim ¶
func (s *PGStore) Claim(ctx context.Context, host string, instances []string, runnerTokenID int64) (Job, bool, error)
Claim — see Store. 🔴 TWO GUARDS AGAINST A SECOND RUNNING JOB ON ONE BROWSER: the NOT EXISTS here (the common case, no error), and the 0012 partial unique index, which makes the loser of a true race fail with a unique violation — reported as "nothing to take", never as a second job.
func (*PGStore) CreateRunnerToken ¶
CreateRunnerToken mints a token for host, owned by ctx's principal, and returns it ONCE.
func (*PGStore) DecideRequest ¶
func (s *PGStore) DecideRequest(ctx context.Context, id int64, approve bool, by string) (FlowRequest, *Job, error)
DecideRequest approves or denies one of the caller's pending, unexpired requests. Approval creates the job (queued in the caller's own queue, DefaultTTL from now) in the SAME transaction, so an approved request always has its job and a job never exists without its approval. via/by are the job's audit facts.
func (*PGStore) Enqueue ¶
Enqueue validates r against the catalogue and queues it, owned by ctx's principal. via and by are the audit facts (the door, and a label for who).
func (*PGStore) FileRequest ¶
func (s *PGStore) FileRequest(ctx context.Context, agentID, ownerID int64, agentName string, r Request, reason string) (FlowRequest, error)
FileRequest records an agent's request, owned by the agent's owner. It validates against the catalogue AND screens agent-composed free text.
func (*PGStore) Heartbeat ¶
Heartbeat extends a running job's lease. host is the runner token's host: a runner can only touch jobs addressed to its own host.
⚠ A LAPSED LEASE THAT NO SWEEP HAS ACTED ON YET IS STILL EXTENDED (as a Report is still accepted): whichever arrives first — the runner, or a sweep run by some read — decides. Once a sweep has moved the job, both answer ErrState and the runner's late result is not recorded.
func (*PGStore) ListRequests ¶
ListRequests returns the caller's newest requests.
func (*PGStore) ListRunnerTokens ¶
func (s *PGStore) ListRunnerTokens(ctx context.Context) ([]RunnerToken, error)
ListRunnerTokens lists the caller's runner tokens, newest first.
func (*PGStore) RequestForAgent ¶
RequestForAgent returns one of AGENT agentID's own requests.
func (*PGStore) RevokeRunnerToken ¶
RevokeRunnerToken revokes one of the caller's runner tokens, reporting whether the caller has such a token at all.
func (*PGStore) WithAgentDenyWords ¶
WithAgentDenyWords sets the deployment's own infrastructure names that an agent-composed message may not contain (MUSTER_FLOW_AGENT_DENY_WORDS).
type Param ¶
type Param struct {
Name string
Required bool
// MaxLen is in characters (runes), and is always set.
MaxLen int
// Pattern must match the WHOLE value. Nil means "free text": any printable
// characters, newlines and tabs, no other control characters.
Pattern *regexp.Regexp
// Help is the one-line description the /flows form and the CLI show.
Help string
// ID marks a CLOSED identifier (a task id: digits only, by its Pattern). It
// is the one kind of parameter that is not prose somebody composed, so it
// is the one kind the agent-text screen (requests.go) skips. Every other
// parameter — whatever its pattern — is screened; a new parameter is
// therefore screened by default.
ID bool
// Max, when set, is an inclusive NUMERIC upper bound: the value (which its
// Pattern must already confine to decimal digits) may not exceed it. A
// pattern alone cannot say "at most 3600" without spelling every range.
Max int
}
Param is one parameter a flow takes. Every value is a string on the wire and in the job row; the runner turns it into argv.
type Request ¶
type Request struct {
Flow string
Host string
Instance string
Params map[string]string
// TTL is how long the job may wait to be claimed; zero means DefaultTTL.
TTL time.Duration
}
Request is what an enqueuer asks for, before validation.
type RequestStatus ¶
type RequestStatus string
RequestStatus is a request's state. The set is closed (the 0014 CHECK).
const ( RequestPending RequestStatus = "pending" RequestApproved RequestStatus = "approved" RequestDenied RequestStatus = "denied" RequestExpired RequestStatus = "expired" )
type Result ¶
type Result struct {
Outcome Outcome `json:"outcome"`
ExitCode *int `json:"exitCode"`
Output string `json:"output"`
Detail string `json:"detail"`
}
Result is a runner's report.
type RunnerToken ¶
type RunnerToken struct {
ID int64 `json:"id"`
OwnerID int64 `json:"ownerId"`
Host string `json:"host"`
CreatedAt time.Time `json:"createdAt"`
RevokedAt *time.Time `json:"revokedAt,omitempty"`
LastUsed *time.Time `json:"lastUsedAt,omitempty"`
}
RunnerToken is one minted runner token's record; the token itself is never stored.
type Store ¶
type Store interface {
Enqueue(ctx context.Context, r Request, via, by string) (Job, error)
List(ctx context.Context, limit int) ([]Job, error)
Get(ctx context.Context, id int64) (Job, error)
Cancel(ctx context.Context, id int64) (Job, error)
// Claim takes the oldest queued, unexpired job for host on one of
// instances, unless that (owner, host, instance) already has a running job.
// ok is false when there is nothing to take.
Claim(ctx context.Context, host string, instances []string, runnerTokenID int64) (Job, bool, error)
Heartbeat(ctx context.Context, id int64, host string) (Job, error)
Report(ctx context.Context, id int64, host string, res Result) (Job, error)
// Agent requests (0014; requests.go): filed by an agent, decided by its
// owner in a browser session.
FileRequest(ctx context.Context, agentID, ownerID int64, agentName string, r Request, reason string) (FlowRequest, error)
RequestForAgent(ctx context.Context, agentID, id int64) (FlowRequest, error)
ListRequests(ctx context.Context, limit int) ([]FlowRequest, error)
DecideRequest(ctx context.Context, id int64, approve bool, by string) (FlowRequest, *Job, error)
AuthenticateRunner(ctx context.Context, token string) (RunnerToken, error)
CreateRunnerToken(ctx context.Context, host string) (string, RunnerToken, error)
ListRunnerTokens(ctx context.Context) ([]RunnerToken, error)
RevokeRunnerToken(ctx context.Context, id int64) (bool, error)
}
Store is the flow queue and the runner-token table.
🔴 EVERY METHOD RUNS UNDER THE CALLER'S PRINCIPAL, AND BOTH TABLES ARE UNDER FORCED ROW-LEVEL SECURITY (0012). An enqueue lands owned by the caller; the runner door acts as the runner token's OWNER, so Claim/Heartbeat/Report can only ever see that owner's jobs. AuthenticateRunner is the one exception: it must find a token by its hash before anyone is known, so the API calls it under authz.System (a System-ledger entry), and only the token's owner and host are handed on.