Captain / Documentation / Part 6. The standard library

Processes, HTTP and hosts

Contents ↓

These are the prelude's root effects for running programs, talking HTTP and reaching another machine. Like every effect they appear in plans, are recorded in the run log, and are answered from the log on replay. A host policy decides which of them may run at all (Host policies).

Each effect has a home frontier. exec, shell, http and observe have none and may be called anywhere; the others belong to LocalMachine, the machine captain run runs on.

exec and shell

Fragment
exec program: Path args: List[Text]
  [unlessFileExists: Path] [creates: Path] [timeout: Duration]
  [output: Symbol] [stdoutLimit: Bytes] [stderrLimit: Bytes] [checkExit: bool]
  -> ExecResult

shell command: Text
  [timeout: Duration] [output: Symbol]
  [stdoutLimit: Bytes] [stderrLimit: Bytes] [checkExit: bool]
  -> ExecResult

The brackets mark optional keywords; they are not Captain syntax. The required keywords come first, in the order shown; the optional ones follow in any order.

exec runs a program with an argument vector and no shell. shell runs a command line with /bin/sh -c, and the plan reports it as weaker still. They are Captain's honest escape hatch: the plan says, per call site, that idempotency is not proven, the observation is untyped and compensation is unknown. Prefer a narrower effect or a tool module when one exists.

captain run starts a process only when it is told it may: an entry that can reach exec, shell or observeProcess, here or on another machine, is refused before anything runs unless the run is given --allow-exec, or --read-only, under which only the reporting programs the observation policy lists run (Host policies).

Keyword Meaning
unlessFileExists:, creates: convergence witnesses: if the path exists, the effect completes without running the program, and the plan shows the call as witnessed
timeout: how long the process may run
output: a declared classification of the output, carried into the plan; the library uses #NonSensitive
stdoutLimit:, stderrLimit: bytes captured per stream, 1 MiB if not given. Overflow kills the process and the outcome is Unknown, never truncated data
checkExit: true by default: a non-zero exit fails the effect. A wrapper that gives exit codes a meaning sets false and reads exitCode
ExecResult member Type Meaning
stdout, stderr Text the captured output
success bool exit status zero
exitCode i32 the exit status; -1 if a signal ended the process

captain inspect lists every program an artifact may exec under tools, with the version a module requires (curl >=7.68.0) or *.

observeProcess

Fragment
observeProcess program: Path args: List[Text] directory: Path
  timeout: Duration stdoutLimit: Bytes stderrLimit: Bytes
  -> ProcessObservation

LocalMachine, VM 7, Unix only. All keywords are required. directory must be absolute; timeout is positive and at most one hour; each limit is 0 to 16 MiB. Unlike exec, it reports what happened instead of failing: a process that cannot start, times out or overflows its output is an observation, not an aborted run. Problems with the request itself, and a policy's refusal, still fail the effect.

ProcessObservation member Type Meaning
state Symbol #Exited, #Signalled, #StartFailed, #TimedOut, #OutputLimit or #IoFailed
exitCode Option[i32] set only for a normal exit; a non-zero exit is still #Exited
signal Option[i32] set only for #Signalled
stdout, stderr Octets the captured bytes, at most the limit; decode with (o utf8Lossy)
message Text a diagnostic for the other states

The process gets its own process group, which is killed on timeout or overflow. It is not a sandbox: a descendant that escapes the group is not contained. The name does not make a command read-only either; the manifest still classes the call as mutating.

observeProcessLiveness

Fragment
observeProcessLiveness pid: i64 -> Result[ProcessLiveness]

LocalMachine, VM 7. Probes one process ID with signal 0, sending nothing. ProcessLiveness has pid: i64, state: Symbol (#Present, #Absent, #PermissionDenied or #Unavailable), errno: i32 and message: Text. An ID outside 1 to 2147483647 fails with #ProcessIdConfig without probing. The answer is evidence at that moment, not a lock: process IDs are reused, and #PermissionDenied does not mean the process is gone. The read-only policy admits it.

http

Fragment
http get: Url [bearer: Secret] [query: Shape] [pathSuffix: Text] [pathTail: Text]
  [pinnedIdentity: Text] [timeout: Duration] -> HttpResponse
http post: Url [bearer: Secret] [body: value] [pathSuffix: Text] [pathTail: Text]
  [pinnedIdentity: Text] [timeout: Duration] -> HttpResponse
http delete: Url [bearer: Secret] [pathSuffix: Text] [pathTail: Text]
  [pinnedIdentity: Text] [timeout: Duration] -> HttpResponse
Keyword Meaning
bearer: a Secret sent as Authorization: Bearer ...; its bytes never enter the program
query: a labelled shape, #( tag_name: t ), sent as ?tag_name=...
body: any portable value, serialised as JSON by the rules below
pathSuffix:, pathTail: text appended to the URL's path as one more segment
pinnedIdentity: SHA256:<base64> of the server's public key; HTTPS only
timeout: 30 seconds if not given

HttpResponse has status: i32 and body: Text. A non-2xx status is a response, not a failure: check (r status). HTTPS requests are made by the system curl, with the response body limited to 8 MiB; plain http:// is spoken directly. The read-only policy refuses http, and the SSH transport does not carry it.

The body

http post: serialises its body: value itself, in the host, by rules older than Writing JSON and kept as they were, since a released generation's meaning never changes (DR-0036, Appendix B):

Value Body
bool, i32, i64, Decimal the number or true/false; a decimal's digits at its scale
Text, Symbol, tagged values a string; a symbol's name; Text that is not valid UTF-8 has U+FFFD put in its place
List[T], a struct an array; an object of the fields, in declared order
an enum variant an object of its fields, without the variant's name; a variant with no fields is {}
Option[T] Some is {"v":…}, None is {}
quantities, Rate, Octets, Instant, Date none: the request is not made, and the effect fails with "… has no JSON form"

Strings escape ", \ and newline, tab and carriage return short, and every other control character, backspace and form feed included, as \u00xx. A Text body is sent as a JSON string, quoted, not as the text itself. A Json document cannot be a body: it crosses no effect in generation 8, so pass the struct or list it was built from. A later generation may let http post: take a document.

Other machines

Fragment
observe serverAt: Address -> Server

observe serverAt: binds a Server value (publicAddress: Address) from an address. It is a binding, not a probe: it performs no I/O, but it appears in the plan. The Server is what a frontier transition needs:

Fragment
server := observe serverAt: address.
uptime := on host: server using: #Ssh do: [
  r := exec program: "uptime"#path args: #() timeout: 10s.
  (r stdout).
].

Inside the block the frontier is SshHost, and the SSH transport (the system OpenSSH client) carries exec, shell and installFileText (see Files). Any other effect declared on SshHost, such as those of Host::Debian, checks and plans, but the command-line executor refuses to run it: it is a declaration without a definition. Frontiers explains blocks, captures and transitions.

Platform-internal effects

The prelude also declares six effects used only by the Gump:: modules to form and manage a Gump cluster: collectGumpBootstrap, bindGumpHandoff, initializeGumpBootstrap, prepareGumpInitialization, queryGumpManagementStatus and queryGumpCaptainSnapshot. They are not a general interface and are not documented here.

Example

A module that observes, and what captain inspect says about it. Nothing here is run: inspecting reads the program, not the machine.

probe.capt
module Example::Probe.

;; The commit checked out in a directory, or why there is none.
export head of: Path -> Text [
  seen := observeProcess program: "git"#path
    args: #( "rev-parse", "HEAD" )
    directory: of
    timeout: 10s
    stdoutLimit: 4KiB
    stderrLimit: 4KiB.
  ((seen state) = #Exited) ifTrue: [
    (seen exitCode) ifSome: [ :code |
      (code = 0) ifTrue: [ ret (((seen stdout) utf8Lossy) trimmed) ].
    ] ifNone: [].
  ].
  ret (Text from: (seen state)) append: (": " append: (seen message)).
].

export kernel -> Text [
  r := exec program: "uname"#path args: #( "-sr" )
    timeout: 5s stdoutLimit: 4KiB stderrLimit: 4KiB.
  ret ((r stdout) trimmed).
].

export status of: Url -> i32 [
  r := http get: of bearer: (Secret named: #ApiToken) timeout: 10s.
  ret (r status).
].
Terminal
$ captain inspect probe.capt
package  Example::Probe 0.0.0
sha256   [..]
compiler 0.1.0   vm 7   stripped

exports
  head of: Path -> Text  (mutating)  [observeProcess program:args:directory:timeout:stdoutLimit:stderrLimit:]
  kernel -> Text  (mutating)  [exec program:args:]
  status of: Url -> i32  (mutating)  [http get:]

effects
  observeProcess program:args:directory:timeout:stdoutLimit:stderrLimit:  @ LocalMachine  → ProcessObservation  (declared)
  exec program:args:  @ (any frontier)  → ExecResult  (declared)
  http get:  @ (any frontier)  → HttpResponse  (declared)

secrets
  #ApiToken

frontiers
  LocalMachine  (local)

tools
  uname  *
...

git is not listed under tools: that list is built from exec calls and requires lines, not from observeProcess.