trunkjet

Reference

On this page

API and SDK examples

Worked examples against the public HTTP API. The field-level contract is spec/api/openapi.json (code-first, generated from lib/api; regenerate with make api). These examples show how the pieces fit together. They do not replace the contract.

Verification. Every bash block on this page runs, in order and unedited, under tools/checks/verify_api_examples.sh. The script extracts the blocks from this file, runs them with set -euo pipefail against a development server, and fails on the first failed assertion. The expect lines are the assertions. The T069 evidence record names the commit, server and exit code of the last verified run. The text blocks show output captured during that run; IDs, digests and trace IDs differ on every run. Nothing on this page is unverified unless a block says so.

The examples use development identities (Authorization: Bearer dev:<subject>). tjetd accepts these only with --dev on a loopback listener. Against a production server, use a session token (tjet login) or a scoped token (example 8) instead.

Conventions of the API

  • Every JSON operation is POST /v1/<group>/<operation> with a JSON body. The only exceptions are the binary upload routes PUT /v1/uploads/{upload_id}/objects[/{object_id}] and a few GET routes for browser login and events.
  • A success is {"result": ..., "meta": {"trace_id", "authority_epoch", "request_id"?, "durability"?}}.
  • A failure is {"error": {"code", "message", "retry", "request_id"?, "details"?}}. Match on code (the ErrorCode enum) and retry (NEVER, SAME_REQUEST, REAUTHORIZE, PREPARE_NEW). Never match on message.
  • Every response carries an x-tjet-trace-id header. On a success it equals meta.trace_id. Refused (4xx) and failed (5xx) requests are logged under that ID, so quote it when you report a problem.
  • u64 values are decimal strings, for example "authority_epoch": "1". Repository paths are {"encoding": "utf8" | "base64", "value": ...}.
  • A mutating operation takes a client-chosen request_id (UUID). Sending the same request again with the same request_id returns the recorded outcome and does not execute it a second time. Reusing the ID with a different body is refused with IDEMPOTENCY_CONFLICT. /v1/operation/get reports the recorded outcome of a request ID. Use it after a lost response (CLI exit 8, OUTCOME_UNKNOWN).
  • Admission control refuses an over-limit request with HTTP 429, RETRY_LATER, a Retry-After header and details.retry_after_ms. Wait at least that long, then resend the identical request with the same request_id.

Setup

The verification script provides TJET_EXAMPLES_SERVER (base URL) and TJET_EXAMPLES_METRICS (the --metrics-listen address). It also runs in a fresh scratch directory with its own XDG_* directories, so the CLI steps never touch your real workspaces or credentials.

B="${TJET_EXAMPLES_SERVER:-http://127.0.0.1:8640}"
# api OPERATION JSON: POST one operation as $AS (a development identity), or with $TOKEN.
api() {
  curl -sS -X POST "$B/v1/$1" -H 'content-type: application/json' \
    -H "authorization: Bearer ${TOKEN:-dev:${AS:-alice}}" -d "$2"
}
rid() { python3 -c 'import uuid; print(uuid.uuid4())'; }
expect() { [ "$1" = "$2" ] || { echo "expected '$2', got '$1'" >&2; exit 1; }; }
REPO_NAME="docs-demo-$(date +%s)"

1. Capabilities and identity

discovery/capabilities lists the API versions, native object format versions, path profiles, chunkers, durability profiles, workspace modes and platform qualification states of this server. Capability availability is reported separately from qualification.

caps=$(api discovery/capabilities '{}')
echo "$caps" | jq -c '.result | {api_versions, object_format_versions, chunkers, durability_profiles, development_mode}'
expect "$(echo "$caps" | jq -r '.result.api_versions[0]')" v1
expect "$(echo "$caps" | jq -r '.result.development_mode')" true

me=$(api session/current '{}')
echo "$me" | jq -c .result
expect "$(echo "$me" | jq -r '.result.tenant_roles[0]')" tenant_admin
{"api_versions":["v1"],"object_format_versions":[1],"chunkers":["fixed-4m-v1","gear-v1"],"durability_profiles":["SINGLE_HOST"],"development_mode":true}
{"tenant_id":"5646beec-…","principal_id":"7dae7aca-…","kind":"human","display_name":"alice","tenant_roles":["tenant_admin"]}

2. Create a repository, retry and recover an outcome

RID=$(rid)
body="{\"request_id\":\"$RID\",\"name\":\"$REPO_NAME\",\"path_profile\":\"portable-v1\"}"
created=$(api repository/create "$body")
echo "$created" | jq -c '.result | {repository_id, name, default_stream, genesis_revision}'
REPO=$(echo "$created" | jq -r .result.repository_id)

# Retrying the identical request (e.g. after a timeout) replays the recorded outcome.
again=$(api repository/create "$body")
expect "$(echo "$again" | jq -r .result.repository_id)" "$REPO"

# The same request id with a different body is refused, never executed.
other=$(api repository/create "{\"request_id\":\"$RID\",\"name\":\"$REPO_NAME-x\",\"path_profile\":\"portable-v1\"}")
expect "$(echo "$other" | jq -r .error.code)" IDEMPOTENCY_CONFLICT
expect "$(echo "$other" | jq -r .error.retry)" NEVER

# After a lost response, ask for the recorded outcome instead of guessing.
op=$(api operation/get "{\"request_id\":\"$RID\"}")
echo "$op" | jq -c '.result | {method, state, repository_id: .result.repository_id}'
expect "$(echo "$op" | jq -r .result.state)" COMPLETED
{"repository_id":"5678f8b4-…","name":"docs-demo-…","default_stream":"a35d3d93-…","genesis_revision":"o1_95d6a4f6…"}
{"method":"repository.create","state":"COMPLETED","repository_id":"5678f8b4-…"}

3. Read a stream, its history and a directory

main=$(api stream/get "{\"repository_id\":\"$REPO\",\"stream\":\"main\"}")
echo "$main" | jq -c '.result | {name, head, generation, state}'
HEAD=$(echo "$main" | jq -r .result.head)

log=$(api history/log "{\"repository_id\":\"$REPO\",\"revision\":\"$HEAD\",\"limit\":5}")
echo "$log" | jq -c '.result.revisions[] | {revision, summary, parents}'
expect "$(echo "$log" | jq -r '.result.revisions[0].summary')" "Repository created"

root=$(api read/listEntries "{\"repository_id\":\"$REPO\",\"revision\":\"$HEAD\"}")
expect "$(echo "$root" | jq -r '.result.entries | length')" 0
{"name":"main","head":"o1_95d6a4f6…","generation":"1","state":"active"}
{"revision":"o1_95d6a4f6…","summary":"Repository created","parents":[]}

4. Errors and trace IDs

# No credentials: 401, AUTH_REQUIRED, and a trace id header to quote in a report.
curl -sS -D headers.txt -o body.json -X POST "$B/v1/repository/list" \
  -H 'content-type: application/json' -d '{}'
head -1 headers.txt
grep -i '^x-tjet-trace-id:' headers.txt
expect "$(jq -r .error.code body.json)" AUTH_REQUIRED
expect "$(jq -r .error.retry body.json)" REAUTHORIZE

# A malformed body is INVALID_ARGUMENT. Unknown fields are rejected too.
bad=$(api repository/create '{"name":"x"}')
expect "$(echo "$bad" | jq -r .error.code)" INVALID_ARGUMENT

# A repository the caller cannot see is NOT_FOUND, exactly like a nonexistent one.
hidden=$(AS=bob api repository/get "{\"repository_id\":\"$REPO\"}")
expect "$(echo "$hidden" | jq -r .error.code)" NOT_FOUND

# On a success the header equals meta.trace_id.
curl -sS -D ok-headers.txt -o ok.json -X POST "$B/v1/session/current" \
  -H 'content-type: application/json' -H 'authorization: Bearer dev:alice' -d '{}'
expect "$(grep -i '^x-tjet-trace-id:' ok-headers.txt | awk '{print $2}' | tr -d '\r')" "$(jq -r .meta.trace_id ok.json)"
HTTP/1.1 401 Unauthorized
x-tjet-trace-id: a2e592b1c07a48eeb860283437e5a2e5

5. Grant a reviewer

Roles are granted per repository with role/put. principal/lookup resolves a subject within the caller's tenant. access/get shows the bindings with their display names.

BOB=$(api principal/lookup '{"subject":"bob"}' | jq -r .result.principal_id)
granted=$(api role/put "{\"request_id\":\"$(rid)\",\"repository_id\":\"$REPO\",\"principal\":\"$BOB\",\"role\":\"reviewer\"}")
expect "$(echo "$granted" | jq -r 'has("result")')" true
api access/get "{\"repository_id\":\"$REPO\"}" | jq -c '.result | {generation, bindings, principal_names}'

6. Write with the CLI, review over the API, land

The raw upload protocol (upload/begin, PUT /v1/uploads/..., upload/seal, revision/prepare, revision/accept) requires canonical native objects (native formats). Use the tjet client, or the Rust tjet-api-client crate together with the format crates, to produce them. This example writes with tjet and does the review step with plain HTTP.

export TJET_SERVER="$B" TJET_DEV_IDENTITY=alice
tjet --json workspace open "$REPO_NAME" ws > open.json
expect "$(jq -r .ok open.json)" true
cd ws
printf 'hello\n' > README.txt
tjet --json add README.txt > /dev/null
tjet --json --no-progress save -m "Add README" --remote > save.json
jq -c '.result.sync | {change_id, revision, durability}' save.json
CHANGE=$(jq -r .result.sync.change_id save.json)
REV=$(jq -r .result.sync.revision save.json)

# The default stream policy needs one approval: land refuses (exit 4, APPROVAL_REQUIRED).
set +e; tjet --json land > land1.json; code=$?; set -e
expect "$code" 4
expect "$(jq -r .error.code land1.json)" APPROVAL_REQUIRED
tjet --json review create > review.json
expect "$(jq -r .result.state review.json)" OPEN
cd ..

# bob approves the exact revision and patch digest he looked at.
DIGEST=$(AS=bob api revision/get "{\"repository_id\":\"$REPO\",\"revision\":\"$REV\"}" | jq -r .result.patch_digest)
approved=$(AS=bob api review/approve "{\"request_id\":\"$(rid)\",\"repository_id\":\"$REPO\",\"change_id\":\"$CHANGE\",\"revision\":\"$REV\",\"patch_digest\":\"$DIGEST\"}")
expect "$(echo "$approved" | jq -r 'has("result")')" true

(cd ws && tjet --json land > land2.json && jq -c '{ok}' land2.json)
expect "$(jq -r .ok ws/land2.json)" true

# The stream head moved; read the landed file back over the API.
HEAD2=$(api stream/get "{\"repository_id\":\"$REPO\",\"stream\":\"main\"}" | jq -r .result.head)
[ "$HEAD2" != "$HEAD" ]
file=$(api read/files "{\"repository_id\":\"$REPO\",\"revision\":\"$HEAD2\",\"paths\":[{\"encoding\":\"utf8\",\"value\":\"README.txt\"}]}")
expect "$(echo "$file" | jq -r '.result.files[0].status')" OK
expect "$(echo "$file" | jq -r '.result.files[0].content_base64' | base64 -d)" hello
{"change_id":"d9875302-…","revision":"o1_3996a6fe…","durability":"SINGLE_HOST"}

7. Changes by label

created=$(api change/create "{\"request_id\":\"$(rid)\",\"repository_id\":\"$REPO\",\"change_id\":\"$(rid)\",\"target_stream\":\"main\",\"title\":\"Docs example\",\"labels\":[\"docs\"]}")
expect "$(echo "$created" | jq -r .result.state)" OPEN
listed=$(api change/list "{\"repository_id\":\"$REPO\",\"label\":\"docs\"}")
echo "$listed" | jq -c '.result.changes[] | {title, state, labels, owner_display_name}'
expect "$(echo "$listed" | jq -r '.result.changes | length')" 1

8. Scoped tokens for agents and CI

A scoped token names 1 to 64 repositories, optional path prefixes and capabilities. With no capabilities given it gets the default agent set. The default TTL is 2 hours and the maximum is 24 hours. A token never carries more than its sponsor holds, and a scoped token cannot issue tokens. The secret appears once, in result.secret. Pass it to tools through TJET_TOKEN, --token-fd or --token-stdin, never as a command-line argument.

issued=$(api token/issue "{\"request_id\":\"$(rid)\",\"name\":\"docs-ci\",\"repositories\":[\"$REPO\"],\"ttl_seconds\":600}")
echo "$issued" | jq -c '.result | {token_id, capabilities, expires_at_ms}'
SECRET=$(echo "$issued" | jq -r .result.secret)
TOKEN_ID=$(echo "$issued" | jq -r .result.token_id)

expect "$(TOKEN=$SECRET api stream/get "{\"repository_id\":\"$REPO\",\"stream\":\"main\"}" | jq -r .result.name)" main
expect "$(TOKEN=$SECRET api token/issue "{\"request_id\":\"$(rid)\",\"name\":\"x\",\"repositories\":[\"$REPO\"]}" | jq -r .error.code)" ACCESS_DENIED

api token/revoke "{\"token_id\":\"$TOKEN_ID\"}" > /dev/null
expect "$(TOKEN=$SECRET api stream/get "{\"repository_id\":\"$REPO\",\"stream\":\"main\"}" | jq -r .error.code)" AUTH_REQUIRED
{"token_id":"9377a689-…","capabilities":["repo_read_metadata","path_list","path_read","path_write_draft","review_comment"],"expires_at_ms":1792444461441}

9. Metrics

GET /metrics is served only on the separate --metrics-listen listener, in Prometheus text format. Labels carry aggregates only: route templates, status classes and error codes, never repository IDs or paths.

M="${TJET_EXAMPLES_METRICS:-127.0.0.1:9640}"
curl -sS "http://$M/metrics" > metrics.txt
grep -E '^tjet_http_request_seconds_count\{route="/v1/repository/create"' metrics.txt
grep -E '^tjet_api_errors_total\{code="IDEMPOTENCY_CONFLICT"\}' metrics.txt

Rust SDK (tjet-api-client)

client/api-client is the typed Rust client over the same operation registry (tjet_api::Operation). It sends each operation with its request identity and surfaces an unknown outcome as a distinct error, which you resolve with operation/get or a retry with the same request ID. On a RETRY_LATER refusal it honours retry_after_ms. The tjet client is built on it. See its crate documentation (cargo doc -p tjet-api-client --open). This page has no separately compiled Rust example; the CLI end-to-end tests (client/cli/tests/) exercise the client against a real server.

Running the verification yourself

# start an isolated development server, run this page and the SDK examples, stop the server:
tools/checks/verify_api_examples.sh --serve 127.0.0.1:8741 127.0.0.1:8742
# or against a development server you started (loopback, --dev, with --metrics-listen):
tools/checks/verify_api_examples.sh --pages api http://127.0.0.1:8740 127.0.0.1:8741

The script refuses a server that does not report development_mode: true. It creates repositories (named docs-demo-<unix time> and sdk-demo-<unix time>) on every run, and nothing removes them. Do not run it against a server whose data you care about.