Skip to content
sproutboatDocs
Esc
↑↓navigate↵open⌘Jpreview
On this page

Build a provider

Deploy to Sproutboat Cloud without the CLI: a full deploy with curl, and how the calls map to the resources of an infrastructure-as-code provider.

This page deploys an app to Sproutboat Cloud with curl and jq, the way the CLI does, and then maps the calls to the resources of a provider for an infrastructure-as-code tool. Each call is described in the API reference.

What a deploy needs

A team API key (see Cloud API) with these grants: app:write, app:read and secret:write. The Deploy preset has them.

The Cloud builds apps from their generated JavaScript: one UTF-8 file of at most 8 MiB that the CLI emits from your project, with the handler, the bindings and the runtime prelude in it. The API does not build from your own TypeScript. To get the file, run the CLI’s emit step in your project, which prints the file’s path as its last line:

SRC=$(npx sproutboat@latest build --standalone --emit-only | tail -n 1)

A provider that deploys code needs the CLI at that step, or has to ask for a source file as input. Pin the CLI (sproutboat@latest, or an exact version): a bare npx sproutboat can resolve an old copy installed on the machine.

The emitted file carries the app’s binding list, and that includes the names of its secrets. A worker only sees env.NAME for a secret listed in sproutboat.jsonc ("secrets": ["GREETING"]) when the file was emitted. Setting a value for a name the build did not declare succeeds, but the worker never sees it.

A full deploy with curl

Set up once. SB_KEY is the team key, taken from your secret store.

set -euo pipefail
export API="https://dash.sproutboat.com"
: "${SB_KEY:?set SB_KEY to your team API key}"
PROJECT="hello-api"

api() { curl --fail-with-body -sS -H "authorization: Bearer $SB_KEY" "$@"; }
sha256() { shasum -a 256 "$1" | cut -d' ' -f1; }

1. Find the team

The team slug names the app’s address, <app>.<team>.sproutboat.app. A key may add routes only under its own team’s name or on a domain the team has verified.

SLUG=$(api "$API/v1/whoami" | jq -r .organization_slug)
HOST="$PROJECT.$SLUG.sproutboat.app"

2. Upload the source

Sources are stored by the SHA-256 of their bytes. Ask which digests the Cloud lacks and upload only those. Uploading the same bytes again is harmless.

SHA=$(sha256 "$SRC")
if api -X POST "$API/v1/sources/missing" -H 'content-type: application/json' \
     -d "$(jq -n --arg s "$SHA" '{sha256: [$s]}')" | jq -e --arg s "$SHA" '.missing | index($s)' >/dev/null; then
  api -X PUT "$API/v1/sources/$SHA" -H 'content-type: application/octet-stream' --data-binary "@$SRC" >/dev/null
fi

3. Upload static assets

Skip this step if the app has no static files. Each file is a blob stored by its own hash; the manifest lists the files and is stored by the hash of its bytes. Upload every missing blob first, then the manifest, which the Cloud refuses with 409 blobs-missing if a blob is not there. What a team has uploaded is its own: “missing” answers cover only the digests that team sent, so a blob or source another team happens to hold is reported missing until you upload it too.

ASSETS=./public
MANIFEST=$(mktemp)
(cd "$ASSETS" && find . -type f | sed 's|^\./|/|' | sort) | while read -r f; do
  case "$f" in *.html) type="text/html; charset=utf-8" ;; *.css) type="text/css; charset=utf-8" ;; *) type="application/octet-stream" ;; esac
  jq -nc --arg k "$f" --arg h "$(sha256 "$ASSETS$f")" --argjson n "$(wc -c < "$ASSETS$f" | tr -d ' ')" --arg t "$type" \
    '{($k): {hash: $h, size: $n, type: $t}}'
done | jq -s '{notFound: "none", runSproutFirst: false, files: add}' > "$MANIFEST"

HASHES=$(jq -c '[.files[].hash]' "$MANIFEST")
for h in $(api -X POST "$API/v1/assets/missing" -H 'content-type: application/json' -d "{\"sha256\": $HASHES}" | jq -r '.missing[]'); do
  f=$(jq -r --arg h "$h" '.files | to_entries[] | select(.value.hash == $h) | .key' "$MANIFEST" | head -n 1)
  api -X PUT "$API/v1/assets/blobs/$h" -H 'content-type: application/octet-stream' --data-binary "@$ASSETS$f" >/dev/null
done

MSHA=$(sha256 "$MANIFEST")
api -X PUT "$API/v1/assets/manifests/$MSHA" -H 'content-type: application/json' --data-binary "@$MANIFEST" >/dev/null

The app refers to the manifest as assets/<sha256 of the manifest>. The manifest format, with notFound, headers, redirects and precompressed br and gz variants, is the AssetManifest schema in the reference.

4. Start the build

This one call creates the app on the first run and updates it afterwards. A team key cannot upload a compiled module, so the API has no separate “create app” call. The spec carries everything about the app that is not code: its routes, the assets, and any bindings, crons, queue_consumers and services.

hosts_patch adds a route and leaves the app’s other routes alone. Secrets are not allowed in a build’s spec; step 7 sets them.

BUILD=$(api -X POST "$API/v1/apps/$PROJECT/builds" -H 'content-type: application/json' -d "$(
  jq -n --arg s "$SHA" --arg p "$PROJECT" --arg host "$HOST" --arg ref "assets/$MSHA" '{
    source_sha256: $s, kind: "generated",
    build: {v: 1, name: $p, cli: {version: "curl-example"}},
    spec: {hosts_patch: {add: [$host]}, assets_manifest_ref: $ref}
  }')")
BUILD_ID=$(jq -r .id <<<"$BUILD")

The answer is 202 with state: queued, or 200 with state: ready and cached: true when the same source was built before. A refused request comes back as 429 or 503 with a reason; see errors and retries.

5. Wait for the build

Poll the build until it is ready, failed or canceled. A ready build carries the record_generation it wrote.

while :; do
  BUILD=$(api "$API/v1/builds/$BUILD_ID")
  STATE=$(jq -r .state <<<"$BUILD")
  case "$STATE" in ready|failed|canceled) break ;; esac
  sleep 2
done
[ "$STATE" = ready ] || { echo "build $STATE: $(jq -r '.error.message // "no reason given"' <<<"$BUILD")" >&2; exit 1; }
GEN=$(jq -r .record_generation <<<"$BUILD")

To watch the log as it is written, open the event stream instead. It replays the log from the start, then follows it, and ends with a done event:

curl -N -sS -H "authorization: Bearer $SB_KEY" "$API/v1/builds/$BUILD_ID/events"

If the connection drops, reconnect with ?after=<last id seen> to skip what you have. The server closes a stream after 20 minutes whatever happens; reconnect, or go back to polling.

6. Wait until it is live

A finished build writes the app, and then a host applies it. The app is live when apply.state is applied and apply.applied_generation has reached the generation you wait for. failed and fenced are the states the CLI treats as errors.

wait_live() {
  local want=$1 end=$((SECONDS + 120)) app
  while [ $SECONDS -lt $end ]; do
    app=$(api "$API/v1/apps/$PROJECT")
    case "$(jq -r '.apply.state // "none"' <<<"$app")" in
      failed|fenced) echo "not applied: $(jq -r '.apply.error' <<<"$app")" >&2; return 1 ;;
    esac
    jq -e --argjson g "$want" '.apply.state == "applied" and .apply.applied_generation >= $g' <<<"$app" >/dev/null && return 0
    sleep 2
  done
  echo "generation $want was not applied within 120 s" >&2; return 1
}
wait_live "$GEN"
echo "live: https://$HOST"

Until the first apply is attempted, apply is null. The CLI waits up to 120 s and polls every 2 s.

7. Set a secret

Secrets are written after the build, on the existing app, and only reach the worker for names declared in sproutboat.jsonc before the emit step (see What a deploy needs). Each write bumps the generation, so wait for it again. No call returns a secret’s value; GET /v1/apps/$PROJECT/secrets lists names only.

GEN=$(api -X PUT "$API/v1/apps/$PROJECT/secrets/GREETING" -H 'content-type: application/json' \
  -d "$(jq -n --arg v "${GREETING:-hello}" '{value: $v}')" | jq -r .record_generation)
wait_live "$GEN"

To set or delete several at once, send PATCH /v1/apps/$PROJECT/secrets with {"set": {...}, "delete": [...]}.

8. Read the logs

What an app has printed and how its requests ended:

  • The running app’s output, with the logs:read grant. GET /v1/apps/$PROJECT/logs?lines=200 returns the last lines the app’s server holds (oldest first, no times or levels; up to about 16 MiB or 7 days are kept there, and the control plane stores none of it). GET /v1/apps/$PROJECT/tail is a live text/event-stream of ready, event, dropped and closed frames (the shape of a wrangler tail event; a request, a printed line and an error are separate events). A session ends after 10 minutes with closed: open another. The Cloud cuts the query string off request URLs, but not off a URL the app prints itself. Secret values of 8 or more characters are replaced by [redacted], best effort: a secret the app prints only in part, or re-encodes, can remain.
  • The build log, from the event stream in step 5. It is capped at 256 KiB.
  • The app’s last 20 uncaught exceptions, and its last 20 cron and queue triggers, from the events route. This is a counter ring, not a log: an uncaught exception there carries a fixed text, not the error.
  • Request and resource aggregates, from GET /v1/apps/$PROJECT/metrics?range=1h.
api "$API/v1/apps/$PROJECT/logs?lines=100" | jq -r '.lines[]'
curl -sN -H "authorization: Bearer $SB_KEY" "$API/v1/apps/$PROJECT/tail?status=5xx"

9. Delete the app

api -X DELETE "$API/v1/apps/$PROJECT"

A key with app:delete_own may delete only the apps that key created; deleting any app of the team needs app:delete.

Mapping calls to provider resources

  • App (code, routes, assets, bindings): create or update with POST /v1/apps/{project}/builds and wait; read with GET /v1/apps/{project}; delete with DELETE /v1/apps/{project}.
  • Secret: set with PUT /v1/apps/{project}/secrets/{name}; read the names with GET /v1/apps/{project}/secrets; delete with DELETE /v1/apps/{project}/secrets/{name}.
  • Route: add and remove with PATCH /v1/apps/{project}/routes; read routes in GET /v1/apps/{project}.
  • Custom domain: claim with POST /v1/domains, publish the TXT record, then POST /v1/domains/{host}/verify; read with GET /v1/domains/{host}/status; release with DELETE /v1/domains/{host}.

Bindings are not separate resources. KV, D1, R2, queue, Durable Object, rate limit, analytics and service bindings are entries in the app’s spec.bindings, sent with the build. The API has no provisioning call and no id to fetch: for kv, d1, r2 and queue you pick the resource_id (lowercase letters, digits, _ and -, up to 64 characters), each app’s storage is private to it, and the host creates the storage on first use. The CLI uses the binding’s name, lowercased. A service binding names another app of the team, by the app_id that GET /v1/apps returns, in spec.services.

Reading state back. GET /v1/apps/{project} returns the stored spec, so a provider can compare bindings, routes and limits. Secret values are never returned, so keep a hash of each value in the provider’s state to detect a change. record_generation rises with every write.

Changing config without code. PUT /v1/apps/{project} replaces the whole spec of an existing app and needs the module the app already runs, so it suits configuration changes such as limits or crons. Omitted lists become empty there, so send everything you want to keep, or use hosts_patch and secrets_patch.

Errors and retries

Every reason has a schema of its own in the OpenAPI file (ErrorBlobsMissing, ErrorRouteTaken and so on, with the extra fields it carries), and each operation lists the ones it can answer, per status. A generator that reads oneOf can give each reason a type of its own.

  • 400: the request is malformed. reason: invalid with path names the field. Verifying a domain answers txt-missing or txt-unconfirmed with the expected record.
  • 401: the key is missing, wrong, expired or revoked. Do not retry.
  • 403: read reason and need. forbidden means the key lacks that grant. host-not-yours means a route outside the team’s names and verified domains. quota-apps, quota-memory, quota-storage, quota-cpu, quota-wall, quota-rate and quota-ops mean the write is over a free alpha quota (a limits value over its ceiling is refused, never clamped). module-upload-disabled is the one 403 with no reason: the body is {"error": "module-upload-disabled", "message": "..."}, so read error.
  • 404: no such app, build, secret or domain in this team. Another team’s app looks the same.
  • 409: route-taken (another app holds the route), source-missing (upload the source, then start the build), blobs-missing (missing lists up to 100 digests and missing_count says how many), domain-in-use (remove the routes first), host-claimed, claim-changed.
  • 413: too-large. JSON bodies are capped at 256 KiB, or 1 MiB for specs, builds, secrets and route edits; blobs and R2 objects at 64 MiB, sources at 8 MiB and manifests at 4 MiB.
  • 429: wait for Retry-After (the body has the same wait in retry_after_s, or retry_after for upload-rate, busy and rate), then retry. team-queue-full and team-hourly-limit mean the team has too many builds running or started; queue-full means the platform’s build queue is full; quota-builds means the 24-hour build quota is used; quota-upload means the 24-hour budget of new source or asset bytes is used; upload-rate and busy mean uploads are coming too fast or too many are in flight.
  • 503 on a build with reason no-builder or builds-disabled: builds are not available right now. Retry after a few minutes. audit-unavailable and host-unavailable on the data routes also mean retry shortly.

The API takes no idempotency keys: repeating a PUT or PATCH writes again and bumps the generation. Repeating an upload by hash, a build of the same source or a domain claim is safe.

What a provider will not find

  • The Cloud has no rollback route. To go back, build the earlier source again (an identical source is a cache hit and takes no build time), or send the earlier build’s module_sha256 to PUT /v1/apps/{project}. The second route is Uncertain: it follows from the rules of the API and has not been run against a live Cloud.
  • The Cloud has no stream of a running app’s output (step 8).
  • Git push-to-deploy is not part of this version of the API description.
  • Free alpha quotas (apps, what an app may ask for in limits, builds per 24 hours, new upload bytes per 24 hours, storage) surface as quota-* reasons; read GET /v1/limits to show a team its headroom.

Was this page helpful?