The authenticated Box request helper, Box-shaped errors, retry classification, and marker / offset pagination.

Errors. A non-2xx response becomes err(HttpError) with a readable message built from Box's {type: "error", status, code, message, request_id, help_url, context_info} body, e.g. "box: HTTP 404 not_found: Could not find the specified resource (request_id 7a1b2c)".

Retry. box never waits between attempts (Hot has no in-run sleep). A connection failure on an idempotent method (GET, HEAD, PUT, DELETE, OPTIONS) is retried once, immediately (opts.retry: false turns that off). Everything else, including 429 and 5xx, comes back as err(HttpError) with retry-after set from the Retry-After header. Check it with is-retryable and let Hot back off: give the handler, schedule or task a retry policy and fail the run (see https://hot.dev/docs/retries).

401 handling. When a cached token is rejected with 401, it is evicted and the call is retried once with a fresh token.

Credential safety. The bearer token is only sent to https hosts under box.com, boxcloud.com and box.net (the long-poll realtime servers), and to the host of a box.api-root / box.upload-root override, over http only when that override is itself http; any other URL is refused.

Values

BOX_HOSTS

BOX_HOSTS: Vec [
  "box.com",
  "boxcloud.com",
  "box.net"
]

BOX_HOST_SUFFIXES

BOX_HOST_SUFFIXES: Vec [
  ".box.com",
  ".boxcloud.com",
  ".box.net"
]

IDEMPOTENT_METHODS

IDEMPOTENT_METHODS: Vec [
  "GET",
  "HEAD",
  "PUT",
  "DELETE",
  "OPTIONS"
]

MAX_IMMEDIATE_RETRIES

MAX_IMMEDIATE_RETRIES: Int 1

MAX_PAGES

MAX_PAGES: Int 10000

RETRY_STATUSES

RETRY_STATUSES: Vec [
  202,
  408,
  429,
  500,
  502,
  503,
  504
]

Functions

api-params

fn (opts: Map): Map

Strip box's own keys (::box::auth/CREDENTIAL_KEYS: credentials, as-user, retry, ...) from an opts Map, leaving only API parameters.

Example

::box::api/api-params({fields: "id", as-user: "123", retry: false})  // {fields: "id"}

body-excerpt

fn (body: Any): Str

A short (at most 300 characters) printable form of a response body, for error messages.

Example

::box::api/body-excerpt("upstream failed")  // "upstream failed"
::box::api/body-excerpt(null)  // ""

box-error-details

fn (body: Any): Map

Extract Box's error fields from a response body (pure): {code, message, request-id, help-url, context-info}. Handles the API shape {type: "error", status, code, message, request_id, help_url, context_info} and the OAuth shape {error, error_description}. Fields are null when absent.

Example

details ::box::api/box-error-details({type: "error", status: 404, code: "not_found", message: "Not found", request_id: "7a1"})
details.code  // "not_found"
details.request-id  // "7a1"

build-http-request

fn (method: Str, url: Str, headers: Map, body: Any, token: Str?, as-user: Str?): ::hot::http/HttpRequest

Build the outgoing HttpRequest (pure). token (nullable) becomes the Bearer header and as-user (nullable) the As-User header. Map/Vec bodies are JSON-encoded with a JSON Content-Type; Str/Bytes bodies are sent verbatim (set Content-Type in headers); "" or null sends no body. Caller headers win.

Example

req ::box::api/build-http-request("POST", "https://api.box.com/2.0/folders", {}, {name: "Docs"}, null, "123")
req.headers  // {As-User: "123", Content-Type: "application/json"}
req.body  // "{\"name\":\"Docs\"}"

collect-marker

fn (fetch: Fn): Vec
fn (fetch: Fn, limit: Int?): Vec

Follow next_marker and collect every entry, or at most limit (null for no limit). fetch is (marker: Str?) -> Map (null for the first page) returning the decoded list response. The first failing page's Err is returned.

hooks ::box::api/collect-marker((m) { ::box::webhooks/list-webhooks({marker: m, limit: 200}) }, null)

collect-offset

fn (fetch: Fn, page-size: Int): Vec
fn (fetch: Fn, page-size: Int, limit: Int?): Vec
fn (fetch: Fn, page-size: Int, limit: Int?, max-offset: Int?): Vec

Follow offset paging and collect every entry, or at most limit. fetch is (offset: Int) -> Map returning a response with entries (and usually total_count); page-size is the limit each call sends. max-offset stops before an offset Box would reject (search rejects offsets above 10000).

Example

::box::api/collect-offset((offset) { {entries: [offset], total_count: 3} }, 1)  // [0, 1, 2]

// At most two entries
::box::api/collect-offset((offset) { {entries: [offset], total_count: 3} }, 1, 2)  // [0, 1]

credential-opts

fn (opts: Map): Map

Keep only box's own keys (credentials, as-user, retry) from an opts Map, e.g. to pass them on to a follow-up call.

Example

::box::api/credential-opts({fields: "id", as-user: "123", retry: false})  // {as-user: "123", retry: false}

error-code

fn (error: Result): Str?

The Box code (or OAuth error-code) carried by an error, or null.

Example

::box::api/error-code(err({code: "not_found"}))  // "not_found"
::box::api/error-code(err("request failed"))  // null

error-message-for

fn (status: Int, details: Map, body: Any): Str

The readable message for an error response (pure): box: HTTP <status> <code>: <message> (request_id <id>).

Example

::box::api/error-message-for(404, {code: "not_found", message: "Not found", request-id: "7a1"}, null)  // "box: HTTP 404 not_found: Not found (request_id 7a1)"

has-code

fn (error: Result, code: Str): Bool

True when error (an HttpError, a Result.Err holding one, or a TokenError) carries the given Box code, e.g. "item_name_in_use".

Example

::box::api/has-code(err({code: "item_name_in_use"}), "item_name_in_use")  // true
::box::api/has-code(err({code: "not_found"}), "item_name_in_use")  // false

is-box-url

fn (url: Str): Bool

True when url may receive Box credentials (pure apart from the root overrides): https:// on box.com, boxcloud.com, box.net or a subdomain, or the host of the box.api-root / box.upload-root override. http:// is accepted only on the host of an override that is itself http:// (a local test server), so an https override never downgrades.

Example

::box::api/is-box-url("https://api.box.com/2.0/users/me")  // true
::box::api/is-box-url("http://api.box.com/2.0/users/me")  // false
::box::api/is-box-url("https://example.com/")  // false

is-connection-failure

fn (message: Str): Bool

True when a transport error message is a connection or read failure (worth trying again), not a size-limit or URL error.

Example

::box::api/is-connection-failure("request failed: connection reset")  // true
::box::api/is-connection-failure("response exceeds http.max-response-bytes")  // false

is-retryable

fn (error: Result): Bool

True when a failed call is worth retrying later: an HttpError (or a Result.Err holding one, or a raw response) with status 202, 408, 429 or 5xx; a TokenError from the token endpoint with one of those statuses, or with error-code: "refresh_in_progress" (another run is refreshing the same account's single-use refresh token); or a connection failure. False for successes and permanent errors (400, 401, 403, 404, 409, invalid_grant, ...).

box does not wait and retry for you. Give the handler, schedule or task a retry policy (see https://hot.dev/docs/retries) and fail the run when this returns true; retry-after on the HttpError says how long Box asked you to wait.

sync-box
meta {
  schedule: "every 15 minutes",
  retry: {attempts: 5, delay: 2000, backoff: "exponential", max_delay: 60000, jitter: true}
}
fn (event) {
  page ::box::folders/list-items("0")
  cond {
    ::box::api/is-retryable(page) => { fail(`box: retrying later: ${err-message(page)}`) }
    is-err(page) => { println(`box: giving up: ${err-message(page)}`) }
    => { length(page.entries) }
  }
}

A connection failure on a non-idempotent call (an upload, a commit, creating a collaboration) may still have reached Box; retrying it can duplicate the write.

is-retryable-status

fn (status: Int): Bool

True for statuses Box asks clients to retry later: 202 (not ready), 408, 429, 500, 502, 503, 504.

Example

::box::api/is-retryable-status(429)  // true
::box::api/is-retryable-status(404)  // false

is-retryable-transport

fn (method: Str, message: Str): Bool

True when a transport failure may be retried immediately: an idempotent method (GET, HEAD, PUT, DELETE, OPTIONS) and a connection failure.

Example

::box::api/is-retryable-transport("GET", "request failed: connection reset")  // true
::box::api/is-retryable-transport("POST", "request failed: connection reset")  // false

json

fn (method: Str, url: Str): Any
fn (method: Str, url: Str, headers: Map, body: Any): Any
fn (method: Str, url: Str, headers: Map, body: Any, token: Str): Any
fn (method: Str, url: Str, headers: Map, body: Any, opts: Map): Any

Like request, but unwraps: the decoded JSON body on 2xx, or an Err carrying HttpError (credential failures carry ::box::auth/TokenError). The shape used by every box endpoint function.

Example

me ::box::api/json("GET", "https://api.box.com/2.0/users/me")
me.login

// One call as a managed user
file ::box::api/json("GET", "https://api.box.com/2.0/files/12345", {}, "", {as-user: "123"})
file.name

marker-page

fn (response: Map): Page

Turn a marker-paged response into a Page (pure). A blank next_marker means the last page.

Example

page ::box::api/marker-page({entries: [{id: "1"}], next_marker: "abc"})
page.next-marker  // "abc"
length(page.items)  // 1

next-offset-for

fn (response: Map, offset: Int, page-size: Int): Int?

The offset of the next page after response (pure), or null on the last page: null when the page was empty, when offset + entries reached total_count, or (with no total_count) when the page was shorter than page-size.

Example

::box::api/next-offset-for({entries: [1, 2], total_count: 5}, 0, 2)  // 2
::box::api/next-offset-for({entries: [1, 2], total_count: 2}, 0, 2)  // null

parse-int

fn (value: Any): Int?

Parse an Int from an Int or a decimal-digit Str (surrounding whitespace allowed); null for anything else. Guards the parse so bad input never halts a run.

Example

::box::api/parse-int(" 42 ")  // 42
::box::api/parse-int("Wed, 21 Oct")  // null

plain-payload

fn (value: Result): Any

The payload of a Result.Err (or the value itself), with type tags removed so an HttpError / TokenError reads like a Map.

Example

::box::api/plain-payload(err({status: 404}))  // {status: 404}
::box::api/plain-payload(err("request failed"))  // "request failed"

query-value

fn (value: Any): Str

Encode one query value the way Box expects (pure): Vecs are comma-joined (fields, ancestor_folder_ids, ...), Bools are true/false, Maps are JSON (mdfilters takes a JSON array), everything else is Str.

Example

::box::api/query-value(["id", "name"])  // "id,name"
::box::api/query-value(true)  // "true"

request

fn (method: Str, url: Str): ::hot::http/HttpResponse
fn (method: Str, url: Str, headers: Map, body: Any): ::hot::http/HttpResponse
fn (method: Str, url: Str, headers: Map, body: Any, token: Str): ::hot::http/HttpResponse
fn (method: Str, url: Str, headers: Map, body: Any, opts: Map): ::hot::http/HttpResponse

Make an authenticated request to Box and return the raw HttpResponse (non-2xx included), or an Err for credential and transport failures.

  • headers - extra headers (they win over the defaults)
  • body - a Map/Vec (sent as JSON), Str/Bytes (sent verbatim), or ""
  • opts - per-call credentials (token, account, refresh-token + on-refresh, jwt-config, client-id + client-secret + enterprise-id / user-id, ...), as-user, and retry (false disables the one immediate retry of a failed connection). A Str is an explicit access token.
response ::box::api/request("GET", "https://api.box.com/2.0/users/me", {}, "", {})

// As one tenant's user, without touching context
response2 ::box::api/request("GET", "https://api.box.com/2.0/users/me", {}, "",
  {account: "tenant-42"})

retry-after-seconds

fn (headers: Map?): Int?

The Retry-After header of a response's headers as whole seconds (Int), or null when absent or given as an HTTP date.

Example

::box::api/retry-after-seconds({retry-after: "30"})  // 30
::box::api/retry-after-seconds({})  // null

retry-policy

fn (opts: Map): Map

The immediate-retry policy for a call (pure): {max-retries: 1}, or {max-retries: 0} when opts.retry is false or 0. Clamped to 0..1: box never waits, so it never retries more than once.

Example

::box::api/retry-policy({})  // {max-retries: 1}
::box::api/retry-policy({retry: false})  // {max-retries: 0}

send-with-retry

fn (req: ::hot::http/HttpRequest, policy: Map): ::hot::http/HttpResponse
fn (req: ::hot::http/HttpRequest, policy: Map, attempt: Int): ::hot::http/HttpResponse

Send an HttpRequest; on a connection failure of an idempotent method, send it once more straight away (per policy). Never waits.

Example

req ::box::api/build-http-request("GET", "https://api.box.com/2.0/users/me", {}, "", ::hot::ctx/get("box.access.token"), null)
response ::box::api/send-with-retry(req, {max-retries: 1})
response.status

unwrap

fn (response: Result): Any

The decoded body of a 2xx response (an empty Map for 204), the Err of a failed request, or err(HttpError) for a non-2xx response.

Example

::box::api/unwrap({status: 200, body: {id: "1"}})  // {id: "1"}
::box::api/unwrap({status: 204})  // {}

url-host

fn (url: Str): Str?

The lower-cased host of an http(s) URL (pure), or null unless the authority is plainly a host and optional port. Userinfo, backslashes, extra slashes and control characters all give null: URL parsers disagree on where the host is in those, and a backslash ends the authority in the one that opens the connection, so https://evil.example\@api.box.com/ connects to evil.example.

Example

::box::api/url-host("https://API.box.com/2.0/files")  // "api.box.com"
::box::api/url-host("https://user@api.box.com/")  // null

with-query

fn (url: Str, params: Map): Str

Append query parameters to a URL, dropping null values and empty Vecs. Vecs are comma-joined (Box's style for fields, file_extensions, ancestor_folder_ids, event_type, ...), Bools encode as true/false. Works whether or not the URL already has a query.

Example

::box::api/with-query("https://api.box.com/2.0/search", {limit: 10, sort: null})  // "https://api.box.com/2.0/search?limit=10"
::box::api/with-query("https://api.box.com/2.0/search?query=q4", {limit: 10})  // "https://api.box.com/2.0/search?query=q4&limit=10"

Types

HttpError

HttpError type {
    status: Int,
    headers: Map?,
    body: Any,
    message: Str?,
    code: Str?,
    error-message: Str?,
    request-id: Str?,
    help-url: Str?,
    context-info: Any?,
    retry-after: Int?
}

A non-2xx (or "not ready" 202) response from Box.

Fields

  • status - HTTP status code
  • headers, body - the raw response (body is decoded JSON when JSON)
  • message - readable summary, e.g. "box: HTTP 409 item_name_in_use: Item with the same name already exists (request_id 9f1)"
  • code - Box's code (e.g. "not_found", "item_name_in_use", "rate_limit_exceeded"), or the OAuth error (e.g. "invalid_grant")
  • error-message - Box's message (or OAuth error_description)
  • request-id - Box's request_id, for support tickets
  • help-url - Box's help_url
  • context-info - Box's context_info (e.g. the conflicting item on a 409)
  • retry-after - seconds from a numeric Retry-After header, else null

Page

Page type {
    items: Vec,
    next-marker: Str?,
    next-offset: Int?,
    total-count: Int?,
    response: Map
}

One page of a list call: items (the entries), next-marker (marker paging; null on the last page), next-offset (offset paging; null on the last page), total-count when Box reports it, and the full decoded response.