The Dropbox transport: RPC requests (JSON bodies on api.dropboxapi.com), content requests (arguments in the Dropbox-API-Arg header on content.dropboxapi.com, Bytes bodies, results in the Dropbox-API-Result header), team headers, typed errors and cursor pagination.

Header-safe JSON. HTTP headers must be ASCII, so Dropbox-API-Arg (and Dropbox-API-Path-Root) JSON escapes every character from U+007F up as \uXXXX (UTF-16 surrogate pairs above U+FFFF), the way the official SDKs do. Without it, non-ASCII paths such as /Café/日本.txt are corrupted. See ascii-escape.

Team headers. opts.select-user (or the dropbox.select.user context variable) sends Dropbox-API-Select-User: <team_member_id> so a team token acts as that member; opts.select-admin / dropbox.select.admin sends Dropbox-API-Select-Admin (admin access to team-owned content). opts.path-root / dropbox.path.root sends Dropbox-API-Path-Root (see path-root-value): "home", a root namespace id for the team space, or ns:<id> for one namespace.

Retry. Nothing waits between attempts. A connection failure on a read-only route is retried once, immediately (opts.retry: false turns that off). 429s, 5xx and the other transient errors come back as err(HttpError) with retry-after from the Retry-After header (or the 429 body's retry_after): check is-retryable and let a Hot retry policy back off (see https://hot.dev/docs/retries).

401 handling. When a cached token minted from a refresh token is rejected with 401, it is evicted and the call is retried once with a freshly minted token.

Context Vars

Optional
  • dropbox.select.user
  • dropbox.select.admin
  • dropbox.path.root
  • dropbox.api.root

Values

IDEMPOTENT_ROUTES

IDEMPOTENT_ROUTES: Vec [
  "files/list_folder",
  "files/list_folder/continue",
  "files/list_folder/get_latest_cursor",
  "files/list_folder/longpoll",
  "files/get_metadata",
  "files/search_v2",
  "files/search/continue_v2",
  "files/download",
  "files/export",
  "files/get_temporary_link",
  "files/list_revisions",
  "files/delete_batch/check",
  "files/copy_batch/check_v2",
  "files/move_batch/check_v2",
  "files/create_folder_batch/check",
  "sharing/list_shared_links",
  "sharing/get_shared_link_metadata",
  "users/get_current_account",
  "users/get_space_usage",
  "files/upload_session/append_v2"
]

MAX_IMMEDIATE_RETRIES

MAX_IMMEDIATE_RETRIES: Int 1

MAX_PAGES

MAX_PAGES: Int 10000

RETRY_STATUSES

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

RETRY_TAGS

RETRY_TAGS: Vec [
  "too_many_write_operations",
  "too_many_requests",
  "retry_error",
  "internal_error",
  "rate_limit",
  "transient_error"
]

Functions

api-params

fn (opts: Map): Map

Strip the package's own keys (::dropbox::auth/CREDENTIAL_KEYS) from opts, leaving Dropbox arguments.

Example

::dropbox::api/api-params({recursive: true, retry: false})  // {recursive: true}

api-result

fn (response: Map): Any

The decoded Dropbox-API-Result header of a content response (the route's result: file metadata for download, {export_metadata, file_metadata} for export), or null.

Example

::dropbox::api/api-result({headers: {dropbox-api-result: "{\"name\":\"a.txt\"}"}})  // {name: "a.txt"}
::dropbox::api/api-result({headers: {}})  // null

ascii-escape

fn (text: Str): Str

Make a JSON text safe for an HTTP header (pure): every character from U+007F up becomes \uXXXX (lowercase hex; a UTF-16 surrogate pair above U+FFFF), which any JSON parser reads back as the same string. Pure-ASCII text is returned unchanged.

::dropbox::api/ascii-escape("{\"path\":\"/Café\"}")
// "{\"path\":\"/Caf\\u00e9\"}"

body-excerpt

fn (body: Any): Str

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

Example

::dropbox::api/body-excerpt({error_summary: "path/not_found/.."})  // "{\"error_summary\":\"path/not_found/..\"}"
::dropbox::api/body-excerpt(null)  // ""

build-arg

fn (base: Map, opts: Map): Map
fn (base: Map, opts: Map, local-keys: Vec): Map

Build a route argument (pure): base (the function's required fields), overridden by the Dropbox arguments in opts (package keys and the function's own local-keys removed), with nulls dropped.

Example

::dropbox::api/build-arg({path: "/a"}, {limit: 100, retry: false, recursive: null})  // {path: "/a", limit: 100}
::dropbox::api/build-arg({path: "/a"}, {limit: 100, range: 5}, ["range"])  // {path: "/a", limit: 100}

build-request

fn (style: Str, route: Str, arg: Any, body: Any, token: Str?, headers: Map): ::hot::http/HttpRequest

Build the outgoing HttpRequest for a route (pure). style is:

  • "rpc" / "notify" - arg is the JSON body (Content-Type: application/json); a null arg sends no body (Void routes)
  • "upload" - arg goes in Dropbox-API-Arg (header-safe JSON), body (Bytes) is the content, Content-Type: application/octet-stream
  • "download" - arg goes in Dropbox-API-Arg, no body and no Content-Type

token (nullable) becomes the Bearer header; headers (team headers, Range, ...) are added last.

Example

token ::dropbox::auth/access-token()
req ::dropbox::api/build-request("rpc", "files/get_metadata", {path: "/a.txt"}, "", token, {})
req.url

// Content route: the argument travels in Dropbox-API-Arg
up ::dropbox::api/build-request("upload", "files/upload", {path: "/a.txt"}, Bytes("hello"), token, {})
up.headers

collect-cursor

fn (first-page: Result, fetch-next: Fn, items-key: Str): Vec
fn (first-page: Result, fetch-next: Fn, items-key: Str, limit: Int?): Vec

Follow a Dropbox cursor (has_more + cursor) and collect every item, or at most limit (null for no limit). first-page is the already-fetched first page (or an Err), fetch-next is (cursor: Str) -> page (the .../continue call), and items-key names the list ("entries", "matches", "links"). The first failing page's Err is returned.

entries ::dropbox::api/collect-cursor(
  ::dropbox::files/list-folder("/Reports"),
  (c) { ::dropbox::files/list-folder-continue(c) },
  "entries", 1000)

credential-opts

fn (opts: Map): Map

Keep only the package's own keys (credentials, team headers, retry) from opts, to pass them on to a follow-up call.

Example

::dropbox::api/credential-opts({recursive: true, select-user: "dbmid:AAH4f99"})  // {select-user: "dbmid:AAH4f99"}

ctx-team

fn (): Map

The team options read from context (dropbox.select.user, dropbox.select.admin, dropbox.path.root).

Example

team ::dropbox::api/ctx-team()
team.select-user

error-node

fn (e: Any, tag: Str): Map?

The member of a Dropbox error union whose .tag is tag (pure), searching nested unions: for {".tag": "lookup_failed", lookup_failed: {".tag": "incorrect_offset", correct_offset: 8}}, error-node(e, "incorrect_offset") is {".tag": "incorrect_offset", correct_offset: 8}. Null when absent.

Example

e {".tag": "lookup_failed", lookup_failed: {".tag": "incorrect_offset", correct_offset: 8}}
::dropbox::api/error-node(e, "incorrect_offset").correct_offset  // 8
::dropbox::api/error-node(e, "too_large")  // null

error-tags-of

fn (error: Result): Vec

The Dropbox error tag path of a failed call (an HttpError, a Result.Err holding one, or a raw error body), or [].

Example

::dropbox::api/error-tags-of(err({error: {".tag": "path", path: {".tag": "not_found"}}}))  // ["path", "not_found"]
::dropbox::api/error-tags-of("not an error")  // []

has-error-tag

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

True when a failed call's Dropbox error carries tag anywhere in its tag path: has-error-tag(result, "not_found") matches path/not_found, from_lookup/not_found, ...

meta-data ::dropbox::files/get-metadata("/maybe.txt")
if(::dropbox::api/has-error-tag(meta-data, "not_found"), "missing", "present")

header-json

fn (arg: Any): Str

Encode an argument as header-safe JSON (pure): nulls are dropped from Maps, then ascii-escape is applied. This is the Dropbox-API-Arg value.

Example

::dropbox::api/header-json({path: "/Café", rev: null})  // "{\"path\":\"/Caf\\u00e9\"}"

hex4

fn (n: Int): Str

A code unit (0..65535) as four lowercase hex digits: hex4(233) is "00e9".

Example

::dropbox::api/hex4(233)  // "00e9"

http-error

fn (response: Map, route: Str?): HttpError

Build an HttpError (with a readable message) from a non-2xx response and the route that was called, which HttpError(response) cannot know. Pure; exposed for testing and for code that reads responses itself.

Example

body {error_summary: "path/not_found/..", error: {".tag": "path", path: {".tag": "not_found"}}}
e ::dropbox::api/http-error({status: 409, headers: {}, body: body}, "files/get_metadata")
e.message  // "dropbox: HTTP 409 path/not_found (files/get_metadata)"
e.error-tags  // ["path", "not_found"]

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

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

is-not-found

fn (error: Result): Bool

True when a call failed because nothing exists at the path (.../not_found).

Example

::dropbox::api/is-not-found(err({error: {".tag": "path", path: {".tag": "not_found"}}}))  // true

is-reset

fn (error: Result): Bool

True when a cursor was invalidated (reset) and the listing must restart from list_folder.

Example

::dropbox::api/is-reset(err({error: {".tag": "reset"}}))  // true

is-retryable

fn (error: Result): Bool

True when a failed call is worth retrying later: an HttpError (or a Result.Err holding one) with status 408, 429 or 5xx, or a 409 whose tag is transient (too_many_write_operations, retry_error, ...); a TokenError with one of those statuses; or a connection failure. False for successes and permanent errors (400, 401, 403, 409 not_found, ...).

Nothing waits and retries for you: Hot has no in-run sleep. Give the handler, schedule or task a retry policy and fail the run when this returns true; retry-after on the HttpError says how long Dropbox asked you to wait.

sync-dropbox
meta {
  schedule: "every 15 minutes",
  retry: {attempts: 5, delay: 5000, backoff: "exponential", max_delay: 300000, jitter: true}
}
fn (event) {
  page ::dropbox::files/list-folder("/Inbox")
  cond {
    ::dropbox::api/is-retryable(page) => { fail(`dropbox: retrying later: ${err-message(page)}`) }
    is-err(page) => { println(`dropbox: giving up: ${err-message(page)}`) }
    => { length(page.entries) }
  }
}

is-transport-limit

fn (error: Result): Bool

True for the Business-plan data transport limit: a 403 invalid_account_type/feature on an upload once a team has used its monthly data transport calls. Retrying will not help until the next month or a plan change.

Example

e err({status: 403, error: {".tag": "invalid_account_type", invalid_account_type: {".tag": "feature"}}})
::dropbox::api/is-transport-limit(e)  // true

notify

fn (route: Str, arg: Any, opts: Map): Any

Call a notify.dropboxapi.com route (files/list_folder/longpoll). These routes take no authentication, so no Authorization or team header is sent. Returns the decoded JSON result or an Err carrying HttpError.

Example

cursor ::dropbox::sync/get-latest-cursor("/Docs")
poll ::dropbox::api/notify("files/list_folder/longpoll", {cursor: cursor, timeout: 30}, {})
poll.changes

parse-int

fn (value: Any): Int?

Parse an Int from an Int or a decimal-digit Str (surrounding whitespace allowed); null for anything else. Never halts on bad input.

Example

::dropbox::api/parse-int(" 30 ")  // 30
::dropbox::api/parse-int("soon")  // null

path-root-home

fn (): Map

Dropbox-API-Path-Root value for paths relative to the user's home namespace (the default).

Example

::dropbox::api/path-root-home()  // {".tag": "home"}

path-root-namespace

fn (namespace-id: Str): Map

Dropbox-API-Path-Root value for paths relative to one namespace id (a shared or team folder you can access).

Example

::dropbox::api/path-root-namespace("1234")  // {".tag": "namespace_id", namespace_id: "1234"}

path-root-team

fn (root-namespace-id: Str): Map

Dropbox-API-Path-Root value for the team space: paths are relative to the user's root namespace (root_info.root_namespace_id from ::dropbox::users/get-current-account).

Example

::dropbox::api/path-root-team("3235641")  // {".tag": "root", root: "3235641"}

path-root-value

fn (value: Any): Str?

The Dropbox-API-Path-Root header value for a path-root option (pure), or null for none. Accepts a Map (sent as is, e.g. from path-root-team), a JSON Str starting with {, "home", "ns:<id>" (one namespace), or a bare namespace id (the team-space root, the common case for team members).

::dropbox::api/path-root-value("3235641")  // "{\".tag\":\"root\",\"root\":\"3235641\"}"
::dropbox::api/path-root-value("ns:1234")  // "{\".tag\":\"namespace_id\",\"namespace_id\":\"1234\"}"

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

::dropbox::api/plain-payload(err("boom"))  // "boom"
::dropbox::api/plain-payload(err({status: 409}))  // {status: 409}

request

fn (style: Str, route: Str, arg: Any, body: Any, headers: Map, opts: Map): ::hot::http/HttpResponse

Make an authenticated Dropbox request and return the raw HttpResponse (non-2xx included), or an Err for credential and transport failures. style is "rpc", "upload" or "download" (see build-request); headers are extra request headers (e.g. Range); opts carries credentials, team options and retry.

response ::dropbox::api/request("rpc", "users/get_current_account", null, "", {}, {})
response.status

retry-after-seconds

fn (headers: Map?, body: Any): Int?

Seconds to wait from a response's Retry-After header, else the 429 body's error.retry_after, else null.

Example

::dropbox::api/retry-after-seconds({retry-after: "30"}, null)  // 30
::dropbox::api/retry-after-seconds({}, {error: {retry_after: 5}})  // 5

retry-policy

fn (opts: Map): Map

The immediate-retry policy (pure): {max-retries: 1}, or 0 when opts.retry is false or 0. Never more than one: nothing here waits between attempts.

Example

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

route-url

fn (style: Str, route: Str): Str
fn (style: Str, route: Str, root: Str?): Str

The URL of a route on its host: route-url("rpc", "files/list_folder") is https://api.dropboxapi.com/2/files/list_folder; "upload" and "download" use content.dropboxapi.com, "notify" uses notify.dropboxapi.com. When the dropbox.api.root context variable (or the 3-arity root) is set, every route goes to {root}/2/{route} instead, for a proxy or a local mock server.

Example

::dropbox::api/route-url("rpc", "files/list_folder", null)  // "https://api.dropboxapi.com/2/files/list_folder"
::dropbox::api/route-url("download", "files/download", "http://localhost:9000/")  // "http://localhost:9000/2/files/download"

rpc

fn (route: Str, arg: Any): Any
fn (route: Str, arg: Any, opts: Map): Any

Call an RPC route and unwrap: the decoded JSON result on 2xx (null for Void routes), or an Err carrying HttpError (credential failures carry ::dropbox::auth/TokenError). arg is the route argument Map (nulls dropped) or null for Void routes.

account ::dropbox::api/rpc("users/get_current_account", null)
account.email

send-with-retry

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

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

Example

route "users/get_current_account"
req ::dropbox::api/build-request("rpc", route, null, "", ::dropbox::auth/access-token(), {})
response ::dropbox::api/send-with-retry(req, route, {max-retries: 1})
response.status

summary-tags

fn (summary: Str?): Vec

The tag path from an error_summary (pure): "path/not_found/.." gives ["path", "not_found"]; the trailing punctuation Dropbox appends is dropped.

Example

::dropbox::api/summary-tags("path/not_found/..")  // ["path", "not_found"]

team-headers

fn (opts: Map, ctx: Map): Map

The Dropbox-API-Select-User, Dropbox-API-Select-Admin and Dropbox-API-Path-Root headers for a call (pure): from opts (select-user, select-admin, path-root), else from ctx (the same keys). Unset values send no header.

Example

::dropbox::api/team-headers({select-user: "dbmid:AAH4f99"}, {})  // {Dropbox-API-Select-User: "dbmid:AAH4f99"}
::dropbox::api/team-headers({}, {})  // {}

unicode-escape

fn (cp: Int): Str

The JSON \uXXXX escape for a Unicode code point, as a surrogate pair above U+FFFF: unicode-escape(233) is \u00e9, unicode-escape(128512) is \ud83d\ude00.

Example

::dropbox::api/unicode-escape(233)  // "\\u00e9"
::dropbox::api/unicode-escape(128512)  // "\\ud83d\\ude00"

union-tags

fn (e: Any): Vec

The tag path of a Dropbox error union (pure): {".tag": "path", path: {".tag": "not_found"}} gives ["path", "not_found"]. A 429 body's {reason: {".tag": "too_many_requests"}} gives ["too_many_requests"].

Example

::dropbox::api/union-tags({".tag": "path", path: {".tag": "not_found"}})  // ["path", "not_found"]

unwrap

fn (response: Result, route: Str): Any

The decoded body of a 2xx response (null for Void routes), the Err of a failed request, or err(HttpError) for a non-2xx response.

Example

::dropbox::api/unwrap({status: 200, headers: {}, body: {cursor: "AAF"}}, "files/list_folder")  // {cursor: "AAF"}
::dropbox::api/unwrap({status: 200, headers: {}, body: ""}, "auth/token/revoke")  // null
is-err(::dropbox::api/unwrap({status: 409, headers: {}, body: {}}, "files/get_metadata"))  // true

upload-call

fn (route: Str, arg: Any, content: Any, opts: Map): Any

Call an upload-style content route: arg in Dropbox-API-Arg, content (Bytes, or a Str as UTF-8) as the body. Returns the decoded JSON result or an Err carrying HttpError.

Example

result ::dropbox::api/upload-call("files/upload", {path: "/notes.txt", mode: "add"}, "hello\n", {})
result.content_hash

Types

HttpError

HttpError type {
    status: Int,
    headers: Map?,
    body: Any,
    message: Str?,
    route: Str?,
    error-summary: Str?,
    error: Any?,
    error-tag: Str?,
    error-tags: Vec?,
    user-message: Str?,
    retry-after: Int?
}

A non-2xx response from Dropbox.

Fields

  • status - HTTP status code (400 bad input, 401 auth, 403 access, 409 endpoint error, 429 rate limit, 5xx)
  • headers, body - the raw response (body is decoded JSON when JSON)
  • message - readable summary, e.g. "dropbox: HTTP 409 path/not_found (files/get_metadata)"
  • route - the route called, e.g. "files/get_metadata"
  • error-summary - Dropbox's error_summary
  • error - Dropbox's typed error union ({".tag": "path", path: {".tag": "not_found"}})
  • error-tag - the tag path joined with /, e.g. "path/not_found"
  • error-tags - the tag path as a Vec, e.g. ["path", "not_found"]
  • user-message - Dropbox's user_message.text, safe to show users, when sent
  • retry-after - seconds from Retry-After (or the 429 body's retry_after), else null