6. Run the API and UI
pstack serve exposes the same core over HTTP, with a single-page dashboard. Use it when a human
wants to click, or when something other than a shell needs to drive a deploy. On a real host you do
not run it by hand — pstack init runs it in the control stack,
behind Traefik, at control.<domain> and api.<domain>. Run it directly to develop against it.
Start it
Section titled “Start it”serve is registry-backed and spec-free: it acts on the deployments submitted to
$PSTACK_DATA/deployments/ (section 7), so it needs no preview.yml and
no stack variable to boot. Variables arrive per request.
$ pstack servepstack api http://127.0.0.1:7878 registry: /var/lib/pstack/deployments auth: NONE — bound to loopback only (set PSTACK_TOKEN to expose)init and serve are the two commands that skip spec loading entirely — they operate on the host
and on the registry, so neither should fail because ./preview.yml happens to be absent.
The safety interlock
Section titled “The safety interlock”This API can delete databases. Without a token it binds 127.0.0.1 and refuses to be exposed — the interlock is not a warning you can click past:
$ PSTACK_HOST=0.0.0.0 pstack servepstack: refusing to bind 0.0.0.0 without PSTACK_TOKEN set — this API can destroy infrastructure. Set PSTACK_TOKEN=<secret> to listen off-loopback.$ echo $?3Set a token and it will listen anywhere. Export it rather than inlining it, so the same shell can
authenticate the curl calls below:
$ export PSTACK_TOKEN=$(openssl rand -hex 16)$ PSTACK_HOST=0.0.0.0 pstack servepstack api http://0.0.0.0:7878 registry: /var/lib/pstack/deployments auth: bearer token required for mutating routespstack init generates this token for you and stores it 0600 in the control stack’s .env; it is
a different secret from the DNS-01 credential, with a different blast radius.
The token gates every route, reads included — since 0.10.0 the only things you can reach without
a credential are /api/health and the login page. A browser gets in with a session cookie instead,
which is also what lets the log stream use EventSource (it cannot send headers).
The token itself is root and passes everything. Accounts are weaker than it and differ from
each other: each carries a role, and what each role may reach is
7e.
It is still not multi-tenant — one spec set, one Docker socket, one host. Roles narrow what a
colleague can do to that host; they are not an isolation boundary and do not pretend to be. Put the
API behind your ingress’ auth or an SSH tunnel (ssh -L 7878:127.0.0.1:7878 preview-host) before
anyone but you can reach it.
Drive it with curl
Section titled “Drive it with curl”Against a deployed control stack the API’s own hostname is api.<domain> — the honest name for
external callers (CI, curl, scripts). control.<domain> serves the same container; it is the name a
browser loads. Substitute http://127.0.0.1:7878 when you are driving a local serve.
:id is a registry id, not a compose project name. The server owns the stored spec and resolves
stack: itself, so a client can never ask it to act on an arbitrary Compose project on the host.
$ curl -s https://api.preview.example.com/api/health{ "ok": true, "authEnforced": true, "dataDir": "/data", "version": "0.1.0"}A deployment’s meta plus its resolved spec summary. Spec variables ride on the query string —
stack: pr-${PR} needs ?PR=123, and axes come back as hook names, never hook bodies:
$ curl -s 'https://api.preview.example.com/api/deployments/pr-123?PR=123'{ "id": "pr-123", "kind": "isolated", "createdAt": 1785014255903, "updatedAt": 1785014255903, "stack": "pr-123", "busy": false, "compose": { "file": "compose.yml", "profiles": [ "backend", "frontend" ], "overlays": [] }, "requires": [ "shared-db" ], "axes": [ { "name": "database", "hooks": [ "up", "down", "assert_gone", "assert_live" ] } ]}Mutating without the bearer header gets nowhere:
$ curl -s -X POST https://api.preview.example.com/api/deployments/pr-123/up{ "error": "unauthorized"}With it, you get 202 + a job id — up and down take minutes, so nothing is answered
synchronously:
$ curl -s -X POST -H "Authorization: Bearer $PSTACK_TOKEN" \ 'https://api.preview.example.com/api/deployments/pr-123/up?PR=123'{ "job": { "id": "up-pr-123-1-apeq0d", "stack": "pr-123", "action": "up", "state": "running" }}down takes a body; omit it and verify defaults to true. force is what lifts the kind: shared
guard (section 7):
curl -s -X POST -H "Authorization: Bearer $PSTACK_TOKEN" \ -H 'content-type: application/json' -d '{"verify":true}' \ 'https://api.preview.example.com/api/deployments/pr-123/down?PR=123'Read a job
Section titled “Read a job”Poll the job for state, or stream its log. The job carries the same outcome.steps the CLI renders,
plus any captured outputs (whitespace compacted below; the server pretty-prints one field per
line):
$ curl -s https://api.preview.example.com/api/jobs/up-pr-123-1-apeq0d{ "job": { "id": "up-pr-123-1-apeq0d", "stack": "pr-123", "action": "up", "state": "ok", "startedAt": 1785014255903, "log": [ { "seq": 1, "at": 1785014255903, "level": "step", "message": "→ up: database" }, { "seq": 2, "at": 1785014255938, "level": "step", "message": "→ compose up (backend, frontend)" } ], "outcome": { "ok": true, "steps": [ { "axis": "database", "phase": "up", "ok": true, "code": 0, "skipped": false }, { "axis": "database", "phase": "assert_live", "ok": true, "code": 0, "skipped": false }, { "axis": "(compose)", "phase": "compose", "ok": true, "code": 0, "skipped": false } ], "outputs": { "DATABASE_URL": "postgres://user:pw@db.example.com/pr-123" } }, "endedAt": 1785014255950 }}state is the field to branch on. There are seven, and only the first two are not final:
| State | Final | Means |
|---|---|---|
queued |
no | accepted, not started — waiting for its own stack’s running job, or for a slot under max_jobs (the queue) |
running |
no | executing now |
ok |
yes | every step succeeded |
failed |
yes | a step failed |
cancelled |
yes | a person stopped it mid-run — partial state may exist, and the transcript says so |
leaked |
yes | teardown ran and something survived it. The one to page on |
superseded |
yes | a newer request replaced it before it ever ran. startedAt is null, so there is nothing to check |
leaked is its own state for the same reason exit 2 is its own code. cancelled and superseded
are deliberately not the same state: a cancelled job may have left half a deploy behind, a
superseded one did nothing at all.
A deploy or wake refused because no node has room is failed, with one capacity step
(Node pressure).
A poller must stop on all five final states, not on ok/failed alone. queued and
superseded both arrived in 0.32.0 — a loop written against the older five treats queued as
unrecognised and waits forever on a superseded job that is already finished with.
Use it from a script
Section titled “Use it from a script”There is a client package, so a CI job does not have to hand-roll fetch calls and a job-polling
loop:
import { createClient } from '@samyx/preview-stacks-client';
const pstack = createClient({ baseUrl: process.env.PSTACK_API!, token: process.env.PSTACK_TOKEN });const job = await pstack.deployments.up(`pr-${pr}`, { PR: pr });const done = await pstack.waitForJob(job.id); // returns the finished job, failure includedconst ready = await pstack.waitForReady(`pr-${pr}`, { vars: { PR: pr } });Zero dependencies, and it ships verifyWebhook for the receiving end.
See packages/client/README.md.
pstack api — every route as a command (0.34.0)
Section titled “pstack api — every route as a command (0.34.0)”The CLI carries the whole API. Sixty-nine commands, generated from
packages/pstack/api/openapi.yaml, so they cannot describe a
route the server does not serve:
export PSTACK_API_URL=https://api.preview.example.comexport PSTACK_TOKEN=… # the host's, or one from `pstack api tokens create`
pstack api --help # the groupspstack api deployments --help # the commands in onepstack api deployments listpstack api deployments up --id pr-123pstack api jobs get --job-id up-pr-123-1-apeq0dpstack api settings set-max-jobs --value 8Parameters are flags, typed and validated from the schema: --value is an integer, --action is
one of start|stop|restart, and a missing required flag is refused before anything is sent. Every
command takes --json for the raw response, and a non-2xx is a non-zero exit, so
pstack api … || rollback works.
A request body is --data '<json>'. When a body is flat — every field a scalar — each field is
also its own flag, which is why settings set-max-jobs --value 8 works but
deployments put takes --data '{"spec":"…"}': its body carries env, a map, and there is no sane
flag shape for one.
PSTACK_API_URL has no default, the same refusal pull config makes: a guess would talk to the
wrong host. pstack api --help needs neither variable — asking what the commands are does not
depend on having a host.
The host serves the document these commands come from, unauthenticated, in both formats:
curl -s https://api.preview.example.com/api/openapi.yaml # the file, byte for bytecurl -s https://api.preview.example.com/api/openapi.json # the same, key order preservedpstack api host openapi # or through the CLIIt is embedded in the binary, so what a host serves always matches the routes that host answers —
and it is the same file pstack api was generated from, so the commands and the description cannot
disagree. ETag is the version; the body only changes when the binary does.
Three routes are deliberately absent: the two SSE streams and the WebSocket terminal. A command
runs one request and prints the answer, so each would buffer an endless response. Use
curl -N for the streams, and the UI for the terminal.
Stop a running job
Section titled “Stop a running job”$ curl -s -X POST -H "Authorization: Bearer $PSTACK_TOKEN" \ https://api.preview.example.com/api/jobs/up-pr-123-1-apeq0d/cancel{ "cancelled": "up-pr-123-1-apeq0d", "stack": "pr-123", "action": "up", "by": "alice", "warning": "Nothing was undone. Whatever this job created or destroyed before it stopped is still that way — run verify to see what exists."}The command in flight is killed (SIGTERM) and every later hook is refused — a teardown is
best-effort and keeps going past failures, so without that second half pressing stop would leave the
remaining axes running. Nothing is rolled back. Run verify afterwards; that is the whole point
of having it. A job that has already finished answers 409, not 404: the id is fine, the request is
out of date.
The SSE stream replays the buffered log from the beginning, then streams live, then closes with a terminal frame — so attaching late still gets the whole story:
$ curl -sN https://api.preview.example.com/api/jobs/down-pr-123-3-a3zn01/streamdata: {"seq":1,"at":1785014283186,"level":"step","message":"→ compose down (all profiles)"}
data: {"seq":2,"at":1785014283193,"level":"step","message":"→ down: database"}
data: {"seq":3,"at":1785014283206,"level":"step","message":"→ verify (asserting resources are gone)"}
data: {"done":true,"state":"ok"}Stop, start or restart one container
Section titled “Stop, start or restart one container”Not the stack and not the service — one container out of a replica set:
$ curl -s -X POST -H "Authorization: Bearer $PSTACK_TOKEN" \ 'https://api.preview.example.com/api/deployments/pr-123/containers/pr-123-worker-1/restart?PR=123'{ "container": "pr-123-worker-1", "service": "worker", "action": "restart", "by": "alice", "note": "Docker has started it. Whether it comes back healthy is what readiness reports."}start · stop · restart. Synchronous, unlike a deploy: one docker restart takes seconds, and
putting it behind the per-stack job lock would make it collide with a deploy for no benefit.
?grace=<seconds> (1–120, default 10) is how long docker waits before SIGKILL on a stop or restart.
The container name is checked against what this deployment owns, and anything else is a 404 — the
same boundary the terminal has, for a bigger reason: docker stop traefik would take down every
preview on the host, and pstack-control is the thing being asked.
A stop cancels the readiness watch (a watch left running would report the stack failed about a
container you meant to stop); a start or restart (re)starts it, so whether it came back healthy is
answered without asking. Each verb also emits its own event — container.started / stopped /
restarted, carrying by.
Wait for it to actually be serving
Section titled “Wait for it to actually be serving”A green up means the commands ran: compose up -d returns as soon as the containers are
created. It returns exactly the same way when the app boots, throws, and exits two seconds later.
So a CI step that posts the preview URL right after the job is racing the thing it is advertising.
readiness is the second half. A watch starts on every successful up; poll it, or hand it a
wait and let it answer when there is an answer:
$ curl -s -H "Authorization: Bearer $PSTACK_TOKEN" \ 'https://api.preview.example.com/api/deployments/pr-123/readiness?wait=60&PR=123'{ "id": "pr-123", "stack": "pr-123", "state": "ready", "containers": [ { "name": "pr-123-app-1", "service": "app", "state": "running", "health": "healthy", "hasHealthcheck": true, "exitCode": 0, "restartCount": 0, "ready": true, "failed": false }, { "name": "pr-123-migrate-1", "service": "migrate", "state": "exited", "health": null, "hasHealthcheck": false, "exitCode": 0, "restartCount": 0, "ready": true, "failed": false } ], "startedAt": 1785014256010, "endedAt": 1785014271044, "reachable": true, "timeoutMs": 180000}state is watching · ready · failed · timedout. ?wait=<seconds> (max 60) returns the
moment it leaves watching, or hands back watching when the wait expires — so the CI loop is
“re-issue while watching”, with no edge to miss:
until [ "$(curl -sf -H "Authorization: Bearer $PSTACK_TOKEN" \ "$API/api/deployments/pr-$PR/readiness?wait=60&PR=$PR" | jq -r .state)" != watching ]; do :; doneTwo things it is careful about. A container without a healthcheck is “ready” when it is merely
running — nothing here knows what serving means for that image, so hasHealthcheck: false says so
rather than implying a probe passed. And a container that exited 0 is ready, not failed: one-shot
migrations are supposed to finish. failed is an exit with a non-zero code, a crash loop (3+
restarts — with a restart: policy no single sample of state can tell a loop from a slow start,
but the counter can), a dead container, or an unhealthy healthcheck; reason names which.
Reading this endpoint for a stack that has no watch starts one, and that watch is silent — a
page view must not put “did not become ready in time” in a notifier about a deploy nobody ran. Only
a watch started by an actual up emits events.
Add ?refresh=1 to re-run a watch that already settled, ?timeout=<seconds> to override the
deadline (default 180s, or the host’s PSTACK_READINESS_TIMEOUT_MS; floored at 5s — an unusable
value defers to the host default rather than silently shortening the watch). The same convergence is pushed to notifiers as healthcheck.*, container.*
and stack.* events — see webhook-events.md.
Probe a preview without a token (0.34.0)
Section titled “Probe a preview without a token (0.34.0)”A CI job that polls https://app-pr-123.example.com right after a deploy is often not waiting on
the app at all — under HTTP-01 it is waiting on that hostname’s certificate, which Let’s Encrypt
issues on the first HTTPS request and which every new stack needs separately. The probe asks the
same question on a hostname whose certificate has been warm since init ran:
curl -s -o /dev/null -w '%{http_code}\n' https://api.preview.example.com/api/probe/pr-123# → 200No token. That is the point: the thing polling is usually a shell loop in a pipeline that has no business holding a credential which can start privileged containers.
The status is the container’s own, so a 404 means the app answered and does not serve / —
which is still “it is serving”. x-pstack-probe says what kind of answer it is:
| Header | Status | Means |
|---|---|---|
upstream |
the app’s | the container answered |
unknown |
404 | no such deployment |
asleep |
503 | sleeping — and left that way; the probe never wakes anything |
no-target |
503 | nothing to dial: no router, no port, or not on preview-ingress |
unresolved |
503 | the spec needs request variables, which this route does not take |
unreachable |
502 | the dial failed or took longer than 3s |
busy |
503 | too many probes in flight (4 at once) |
?service=web picks one when a stack publishes several; without it the alphabetically first router
with an address wins, the same one every time.
What it deliberately cannot do, because it has no auth: return a body — not the app’s, not an
error message, ever; forward the upstream’s headers; follow a redirect; or fetch any path but /.
It does disclose whether a deployment id exists and whether it is up, which is the question being
asked. PSTACK_PROBE=off removes the route on a host that does not want even that.
One job per stack, and a queue of one
Section titled “One job per stack, and a queue of one”A stack still runs exactly one job at a time — a down deleting the database branch an up just
created is the kind of corruption that is very hard to diagnose afterwards. What changed is what
happens to the SECOND request: it is queued rather than refused.
$ curl -s -w " [%{http_code}]\n" -X POST -H "Authorization: Bearer $PSTACK_TOKEN" \ 'https://api.preview.example.com/api/deployments/pr-777/up?PR=777'{ "job": { "id": "up-pr-777-8-a1b2c3", "state": "queued", "stack": "pr-777", … }} [202]The queue is one deep, and the newest wins. A third request replaces the queued one rather than
stacking behind it, so five pushes in a minute run the first deploy and then exactly one more
carrying the newest spec. The replaced job is not forgotten: it reaches superseded under its own
id, so a script polling the id it was given always gets an answer.
down does not wait. A teardown cancels whatever is running, drops anything queued, and starts
immediately — the one thing you never want stuck behind a deploy. Cancelling mid-flight leaves
partial state, and the job’s transcript says so.
POST /api/deployments/:id/cancel stops everything for one stack: the running job and the queued
one together.
Across stacks, the max_jobs setting (default 4) bounds how many run at once. Beyond it a job
waits for a slot rather than being refused — twenty PRs deploying at nine in the morning would
otherwise put twenty docker compose up on one Docker socket.
That cap is changeable while the server runs — PUT /api/settings/max_jobs (maintainer), no
restart — and PSTACK_MAX_JOBS is now its default rather than the authority
(Runtime settings). Raising it dispatches whatever was already waiting, on
that request. Lowering it cancels nothing: jobs already running run to completion, and the new
cap applies to the next job that starts. An operator who types 1 while four jobs are in flight has
not stopped three of them.
Jobs are in-memory, capped at 50 — a restart loses history, not correctness, and it loses the
queue too. Truth about what exists lives in Docker and in each axis’s assert_* probe.
The UI
Section titled “The UI”Open https://control.<domain>/ (or http://127.0.0.1:7878/ against a local serve). The UI is a
single HTML document embedded in the bundle, not a directory of static files: /api/* is the API,
and every other path serves that one document — so a deep link like /deployments/pr-123 renders
instead of 404ing, and there is no filesystem lookup and therefore no path traversal to contain. No
build step; Vue 3 comes from unpkg, so first load needs internet.
The UI calls the API with relative /api/… paths. That is deliberate: loaded from
control.<domain> it talks to control.<domain>/api/… — same origin, so no CORS preflight, no
cross-origin cookie rules, and nothing to reconfigure when the hostnames change. api.<domain> exists
for callers that are not the UI.
It does what the CLI does, with a live log: enter a deployment id, Load, then up / down /
verify, watching the job stream and the step table. Also worth knowing:
- The token goes in the header field and is kept in
localStorage. WhenauthEnforcedis false the header says so. - The axis list flags an axis with
upand noassert_goneas unverifiable — the same warningvalidateprints, where you are about to press the button. - Untick “verify after down” and the UI tells you teardown will not check for leaks. Same trap as
--no-verify. - The step table uses four marks where the CLI report uses three:
✓ok,?unverifiable,!leaked,✗otherwise failed. The CLI folds!into✗and puts the count in the summary line.
packages/pstack/ui/README.md documents the UI’s internals and the exact routes it consumes.
Act on several deployments at once
Section titled “Act on several deployments at once”The advanced UI’s Deployments list has a checkbox per row. Tick some — or tick the header box to select every row the current filters show — and a bar offers Deploy, Verify, Sleep, Wake, Tear down and Tear down and forget.
- Each deployment gets its own request and its own job, exactly as if you had pressed the button on its page. The results list under the bar links each job, or says why one was refused or skipped.
- Shared deployments are skipped by tear down: their page asks for the stack name typed out, and a select-all must not be a way around that. The bar says how many are shared.
- Rows that need variables are skipped for every action; sleep and wake skip rows where they mean nothing (already asleep, not asleep, no compose section).
- The two teardowns ask for a second click, naming how many will go. Teardown here always checks for leftovers.
Tear down and forget (here and on a deployment’s Danger tab) is down with forget: true: one
job that tears the stack down and, only if the teardown finished clean, forgets the deployment.
Anything left behind keeps the record, so the leak stays visible.
Jobs and deployments link both ways: a job’s stack opens its deployment (or Control, for the control plane’s own jobs), and a deployment’s Jobs link opens the jobs list filtered to it.
Copy a variable list out, paste one back
Section titled “Copy a variable list out, paste one back”Three places in the advanced UI hold a list of NAME / value pairs: the Variables & secrets
page (host-level ${vars.NAME} and ${secrets.NAME}), the submit form, and a deployment’s Config
tab. All of them carry the same two controls — copy the list out, paste one back — in .env, CSV or
TSV.
- Copying renders the list in the format you pick.
.envquotes only what needs it (a space, a#, a quote, a newline); CSV and TSV always write aname,valueheader row, so a variable really callednamesurvives the round trip rather than being eaten as a label. - Pasting parses as you type and shows what it read before any button that changes anything
appears: the pairs, and every line it could not read, with the line number, the text and the
reason. A paste that half-worked in silence is how a deployment loses the one variable its stack
name is built from. The format is detected —
.envshape first, then a quote-aware split on comma and tab — and there is a manual override for the input that reads as the wrong one. - Merge adds and overwrites by name. Replace all is offered only in the deployment’s variable editor, which owns its whole list; on the Variables page a replace would have to delete every name the paste happened to omit, and that is not a thing to put behind a two-word button.
- A name a spec cannot reference comes back as a problem instead of a row:
foo-baris a legal thing to type into the editor, but${foo-bar}is not something the interpolator can resolve, so importing it would add a variable that could never do anything.
What an export does with a secret: it writes the name, an empty value, and never the mask.
# Secret VALUES are not included: this server has no route that returns one.# Each name is listed with an empty value for you to fill in.DB_PASSWORD=STRIPE_KEY=There is no other honest option. A secret’s value has no read path at all — GET /api/host-vars
returns names and timestamps — so there is nothing to copy. Omitting the names would make the file
quietly incomplete wherever it lands. And writing •••••••• would produce a file that deploys,
with the mask as the password. An empty value is not a value: pstack treats an empty variable as
undefined and refuses to resolve a spec that needs it, so a pasted secret line that was never
filled in fails loudly at deploy time instead of running against a wrong credential.
That leaves one loop, and it is closed on the way back in: on the Variables page an entry with no value is skipped. Copy this page’s secrets, paste them straight back, and nothing changes — the preview counts them, names them, and refuses to apply if that is all there was. CSV and TSV have nowhere to put a comment, so the warning about withheld values is on the page itself and not only inside the copied text.