Package 'zuhttp'

Title: Minimal HTTP Client Using Native System TLS
Description: A small client for the Hypertext Transfer Protocol (HTTP/1.1 and HTTP/2), over plain connections and over Transport Layer Security (TLS), that uses the operating system's own TLS implementation and certificate trust store instead of a bundled cryptography library or certificate bundle: 'Schannel' on 'Windows', Apple's native TLS on 'macOS', and 'OpenSSL' elsewhere. Provides a total request timeout, cancellation from 'R' with an interrupt, connection reuse, streaming of response bodies to files or callbacks, structured error conditions, and a pluggable transport layer for testing without a network. Intended as a focused alternative to full multi-protocol clients for packages that only need reliable HTTP requests.
Authors: Pedro Baltazar [aut, cre, cph], Kazuho Oku [cph] (picohttpparser, see inst/COPYRIGHTS), Tokuhiro Matsuno [cph] (picohttpparser, see inst/COPYRIGHTS), Daisuke Murase [cph] (picohttpparser, see inst/COPYRIGHTS), Shigeo Mitsunari [cph] (picohttpparser, see inst/COPYRIGHTS), Weijia Song [cph] (uriparser, see inst/COPYRIGHTS), Sebastian Pipping [cph] (uriparser, see inst/COPYRIGHTS), Tatsuhiro Tsujikawa [cph] (nghttp2, see inst/COPYRIGHTS), nghttp2 contributors [cph] (nghttp2, see inst/COPYRIGHTS), sfparse contributors [cph] (sfparse within nghttp2, see inst/COPYRIGHTS), nghttp3 contributors [cph] (sfparse within nghttp2, see inst/COPYRIGHTS)
Maintainer: Pedro Baltazar <[email protected]>
License: MIT + file LICENSE
Version: 0.1.0
Built: 2026-12-01 09:56:26 UTC
Source: https://github.com/pedrobtz/zuhttp

Help Index


Set the request body

Description

zu_body_json() serialises with the JSON backend (see zu_set_json_backend()) and sets Content-Type: application/json. zu_body_form() URL-encodes and sets application/x-www-form-urlencoded. zu_body_raw() sends bytes as given. zu_body_file() sends a file's contents.

Usage

zu_body_json(req, x, auto_unbox = TRUE)

zu_body_form(req, x)

zu_body_raw(req, x, type = NULL)

zu_body_file(req, file, type = "application/octet-stream")

zu_body_stream(req, f, type = "application/octet-stream")

Arguments

req

A zu_request.

x

For zu_body_json(), any object the backend can serialise; for zu_body_form(), a named list; for zu_body_raw(), a raw vector or a string.

auto_unbox

Passed to the JSON backend. TRUE sends list(a = 1) as {"a":1} rather than ⁠{"a":[1]}⁠, which is what R users nearly always mean.

type

Content type to declare.

file

A file path. The file is read into memory; for a body too large for that, see zu_body_stream(). Named file as in zu_post(): path is always where a response goes (D-45).

f

For zu_body_stream(), a function of no arguments that returns the next piece of the body as a raw vector each time it is called, and NULL at the end. It is called for one request: a function that has returned NULL has nothing left, so performing the same request again sends whatever it returns then, usually an empty body. Build the request afresh, with a new function, for each attempt you make. Inside f, the rules of a callback hold (§27.4): it cannot make a request on the client sending it, or read its own response.

Details

zu_body_stream() sends a body produced a piece at a time, for one that is large or not known in advance (§28, §65.7). Over HTTP/2 each piece goes out as the server's flow-control window allows, so with zu_perform()'s stream = TRUE the response can be read while the body is still being sent (full duplex, as gRPC's bidirectional calls need). Over HTTP/1.1 it is sent chunked. Such a body cannot be sent twice: a retry, or a 307 or 308 redirect, raises zu_body_not_replayable instead (§28.2), and an error raised inside f stops the request, closes its connection, and is re-raised unchanged. The implied content type is only a default: a header set on the request or the client always wins (§31.6).

Value

A zu_request.

Examples

req <- zu_request("POST", "https://example.com/upload")
zu_body_raw(req, charToRaw("hello"))

# Three pieces, then the end.
pieces <- list(charToRaw("a"), charToRaw("b"), charToRaw("c"))
i <- 0
zu_body_stream(req, function() {
  i <<- i + 1
  if (i <= length(pieces)) pieces[[i]]
})

Whether a request's body can be replayed

Description

§28.2 makes rewindability a property of the body rather than a convention, so the retry layer (§33) and the redirect layer (§19.1) can refuse rather than truncate.

Usage

zu_body_rewindable(req)

Arguments

req

A zu_request.

Value

A logical. TRUE for an absent body and for any in-memory body; FALSE for a body from zu_body_stream(), which a function produces once and cannot produce again.

See Also

zu_req_replay_safe()

Examples

zu_body_rewindable(zu_request("GET", "https://x.test/"))

Inspect or delete a cassette

Description

Inspect or delete a cassette

Usage

zu_cassette_interactions(
  dir = file.path(tempdir(), "zuhttp-cassettes"),
  name = "default"
)

zu_cassette_clear(
  dir = file.path(tempdir(), "zuhttp-cassettes"),
  name = "default"
)

Arguments

dir, name

The cassette's directory and name, as given to zu_cassette_transport().

Value

zu_cassette_interactions() a list of recorded interactions, each with request, response and recorded_at, all already redacted; zu_cassette_clear() TRUE if a file was removed, invisibly.

Lifecycle

Experimental (D-65). The testing tools are exported so that package tests can run without a network, and may still change before 1.0; the request functions, response accessors and conditions are the stable API.

See Also

zu_cassette_transport()

Examples

zu_cassette_interactions(tempdir(), "no-such-cassette")

Record and replay HTTP interactions

Description

A transport that plays responses back from a cassette on disk, so a downstream package's tests run with no network. In "auto" mode it records whatever it has not seen before and replays everything else, which means a test suite is written once against the real service and then runs offline.

Usage

zu_cassette_transport(
  dir = file.path(tempdir(), "zuhttp-cassettes"),
  name = "default",
  mode = c("auto", "replay", "record"),
  transport = zu_native_transport()
)

Arguments

dir

Directory holding cassettes. Defaults to a subdirectory of tempdir(), so nothing is written outside the session unless asked.

name

Cassette name; one file, ⁠<name>.rds⁠, inside dir.

mode

"auto" records on a miss and replays on a hit; "replay" never touches the network and errors on a miss; "record" always performs the request and overwrites the stored interaction.

transport

The transport used when actually performing a request. A zu_mock_transport() here is how this package tests itself.

Value

A transport object, for zu_client(transport = ).

Lifecycle

Experimental (D-65). The testing tools are exported so that package tests can run without a network, and may still change before 1.0; the request functions, response accessors and conditions are the stable API.

What is written

Credentials are removed before anything reaches the disk: userinfo and secret query parameters in URLs, secret headers in both directions, and form-encoded bodies, all through the §42 policy that the rest of the package uses. A cassette is the one egress that outlives the session, so this is the egress where redaction matters most.

Requests are matched on method, URL and body — not on headers, which vary with client configuration in ways that do not change what a server would reply. The URL and body used for matching are the redacted ones, so a cassette cannot be made to carry a secret by way of its index.

See Also

zu_cassette_interactions(), zu_cassette_clear()

Examples

dir <- file.path(tempdir(), "zuhttp-example")
live <- zu_mock_transport(function(req) zu_response(200L, body = "hello"))

rec <- zu_cassette_transport(dir, "demo", transport = live)
zu_resp_text(zu_get("https://x.test/a", client = zu_client(transport = rec)))

# Now offline: the same request never reaches `live`.
rep <- zu_cassette_transport(dir, "demo", mode = "replay")
zu_resp_text(zu_get("https://x.test/a", client = zu_client(transport = rep)))
zu_cassette_clear(dir, "demo")

Create a reusable client

Description

A client carries what many requests share: a base URL, default headers and query parameters, policy defaults, and the connection pool. It is never the first argument of a request function — see below.

Usage

zu_client(
  base_url = NULL,
  headers = NULL,
  query = NULL,
  timeout = NULL,
  redirects = NULL,
  verify = NULL,
  max_body = NULL,
  user_agent = NULL,
  check = NULL,
  decode = NULL,
  transport = zu_native_transport(),
  pool = zu_pool(),
  retry = NULL,
  middleware = NULL,
  hooks = NULL,
  proxy = NULL,
  tls = NULL,
  http2 = NULL
)

Arguments

base_url

Optional base URL, so that zu_get("/users", client = api) works. Joining is textual, not RFC 3986 resolution: see Details.

headers

Named character vector of default headers.

query

Named list of default query parameters.

timeout

Total seconds for a request, redirects included. DNS resolution is not bounded by it (nor by Ctrl-C); see zuhttp_tls.

redirects

Maximum redirects to follow. 0 returns the 3xx itself. A Location that is not a valid URL reference — a raw space or non-ASCII bytes — raises zu_url_error rather than being repaired (§8.2), and a redirect back to a URL already requested raises zu_redirect_error.

verify

Verify the certificate and hostname. Leave this TRUE.

max_body

Maximum decoded body size in bytes; Inf for no limit.

user_agent

Default User-Agent. Unset, requests send ⁠zuhttp/<version>⁠.

check

Raise a condition for 4xx and 5xx responses (§31.14). FALSE returns the response whatever its status.

decode

Decompress the body transparently (§21.2).

transport

The object that actually performs requests. The default is the network; zu_mock_transport() and zu_cassette_transport() replace it in tests.

pool

Connection reuse settings from zu_pool(), or NULL to open a fresh connection for every request.

retry

A zu_retry() policy. The default retries nothing.

middleware

A function of ⁠(req, next_fn)⁠, or a list of them, wrapping request execution (§31.13). The first is outermost.

hooks

Lifecycle observers from zu_hooks().

proxy

Proxy URL, e.g. "http://proxy:3128". Leave unset to honour the environment (§20.1); pass FALSE to force a direct connection. Not NULL — under the §31.9 merge rules NULL means "reset to the package default", which for a proxy is "consult the environment". FALSE is the only spelling that can mean "definitely do not proxy" without making this one argument an exception to a rule every other policy argument follows.

tls

Certificate trust settings from zu_tls().

http2

HTTP/2 use: "auto" (the default) offers it to every HTTPS server and uses it when the server chooses it, and HTTP/1.1 otherwise; "required" fails with zu_connect_error before sending anything when the connection is not HTTP/2, and on an ⁠http://⁠ URL speaks cleartext HTTP/2 (h2c) directly, without an Upgrade; "off" uses HTTP/1.1 only. zu_resp_connection() reports which version a response came over. A client setting only: there is no per-request form, because it chooses the connection, not the request.

Details

base_url is joined to a request path, not resolved against it: a client with base_url = "https://api.example.com/v1" and a request path of "/users" produces ⁠https://api.example.com/v1/users⁠. RFC 3986 resolution would give ⁠https://api.example.com/users⁠ — the ⁠/v1⁠ silently dropped — which is the single most common surprise in libraries that resolve here. An absolute request URL ignores base_url entirely.

Value

A zu_client object.

The client is never the first argument

zu_get(url, ..., client = api), never zu_get(api, url). Overloading argument one by type breaks autocomplete, makes dispatch murky, and turns a misplaced argument into a confusing error instead of a clear one (§31.3).

See Also

zu_client_update() to derive a client without mutating it.

Examples

api <- zu_client(
  base_url = "https://api.example.com",
  headers = c(Accept = "application/json")
)
api

Derive a client from another

Description

Returns a copy with the named fields changed. Clients are values: this never mutates client, so a derived client cannot surprise code still holding the original (§31.10).

Usage

zu_client_update(client, ...)

Arguments

client

A zu_client.

...

Fields to change, named as in zu_client().

Value

A new zu_client.

Examples

api <- zu_client(base_url = "https://api.example.com")
admin <- zu_client_update(api, headers = c(Authorization = "Bearer xyz"))
identical(api$headers, NULL)   # unchanged

Construct a zuhttp condition

Description

Mostly internal, but exported so that package authors building on zuhttp can raise conditions their users can catch with the same handlers.

Usage

zu_condition(
  code,
  message,
  url = NULL,
  phase = NULL,
  backend = NULL,
  backend_code = NULL,
  request = NULL,
  response = NULL,
  call = sys.call(-1)
)

Arguments

code

Integer code or class name, e.g. "zu_tls_certificate_error".

message

The human-readable message (§34.4: what was attempted, what failed, and the most likely fix).

url

Optional URL. It is redacted before being stored (§42.2), so a condition object can be printed or logged safely.

phase

One of "dns", "connect", "tls", "write", "ttfb", "read", "decode", or NULL.

backend, backend_code

The platform backend and its native code, where useful. Present but never leading (§34.4).

request, response

Objects where they exist.

call

The originating call.

Value

A condition object inheriting from the §34.1 classes, plus error and condition.

Examples

cnd <- zu_condition(
  "zu_timeout_error",
  "the request took too long",
  url = "https://user:[email protected]/v1",
  phase = "read"
)
class(cnd)
cnd$url        # redacted: the userinfo is gone

# Raise it, and catch it by any class in its chain.
tryCatch(stop(cnd), zu_error = function(e) conditionMessage(e))

The package-managed default client

Description

Used by any request that does not name a client. It is re-created in a forked child rather than inherited, so a client made in the parent never hands its connections to parallel::mclapply() workers (§26.4).

Usage

zu_default_client()

Value

A zu_client.

See Also

zu_set_default_client()

Examples

zu_default_client()

Add headers

Description

Add headers

Usage

zu_headers(req, ...)

Arguments

req

A zu_request.

...

Named header values, one value per name. A value of NA removes a header inherited from the client (§31.9); a same-name value replaces it, case-insensitively. A vector of several values, or a name given twice, is an error: join a list-valued field yourself.

Value

A zu_request.

Examples

zu_headers(zu_request("GET", "https://example.com"), Accept = "text/plain")

Register lifecycle hooks

Description

Hooks are observability (§35.3). They are handed a payload and their return value is discarded — a hook that could modify the request would be middleware wearing a disguise, and §31.13 keeps the two apart deliberately.

Usage

zu_hooks(
  before_request = NULL,
  after_response = NULL,
  before_retry = NULL,
  after_retry = NULL
)

Arguments

before_request

Called with list(request, attempt) before each attempt.

after_response

Called with list(request, response, attempt).

before_retry

Called with list(request, attempt, delay, why) before sleeping — §33.4 requires that a retry be visible, because a retry nobody can see is a latency mystery for whoever debugs it later.

after_retry

Called with list(request, attempt) when a retried attempt begins.

Details

Every payload passes through the §42 redaction filter before a handler sees it. A trace handler that logs request headers must not be the mechanism by which a bearer token reaches a log file.

Value

A zu_hooks object, for zu_client(hooks = ).

Examples

seen <- character()
h <- zu_hooks(before_request = function(p) seen <<- c(seen, p$request$url))
cli <- zu_client(
  hooks = h,
  transport = zu_mock_transport(function(r) zu_response(200L))
)
invisible(zu_get("https://x.test/a", client = cli))
seen

What this build of zuhttp can do

Description

Networking diagnostics in one place: which TLS engine is linked, which store decides trust, whether revocation is checked, what the default client is configured to do, and what the environment says about proxies.

Usage

zu_info()

Value

A zu_info list, printed as a report. Fields: version, http (the protocol versions this build speaks, "HTTP/1.1" and "HTTP/2"), tls_backend, trust, tls_available, revocation_default, tls_capabilities (the zu_tls() settings this backend honours, from "pins", "tls13", "ca_file", "ca_extra" and "revocation"; the others raise zu_tls_unsupported_error), compression, ipv6, proxy_env and default_client.

Why the TLS engine and the trust store are listed separately

§13.1 splits them deliberately. A build can speak TLS with one library and decide trust with another — that is exactly what the macOS build does — and "which store trusted this certificate?" is a question users genuinely ask when a certificate works in a browser and not here.

Examples

zu_info()

Perform a request in one call

Description

The short form. zu_get(url) is the whole API for the common case; the arguments below are the same options zu_client() takes, applied to this request only.

Usage

zu_get(
  url,
  query = NULL,
  headers = NULL,
  timeout = NULL,
  redirects = NULL,
  verify = NULL,
  max_body = NULL,
  user_agent = NULL,
  check = NULL,
  decode = NULL,
  retry = NULL,
  path = NULL,
  callback = NULL,
  proxy = NULL,
  tls = NULL,
  trace = FALSE,
  client = zu_default_client()
)

zu_head(
  url,
  query = NULL,
  headers = NULL,
  timeout = NULL,
  redirects = NULL,
  verify = NULL,
  max_body = NULL,
  user_agent = NULL,
  check = NULL,
  decode = NULL,
  retry = NULL,
  path = NULL,
  callback = NULL,
  proxy = NULL,
  tls = NULL,
  trace = FALSE,
  client = zu_default_client()
)

zu_post(
  url,
  query = NULL,
  headers = NULL,
  body = NULL,
  json = NULL,
  form = NULL,
  file = NULL,
  timeout = NULL,
  redirects = NULL,
  verify = NULL,
  max_body = NULL,
  user_agent = NULL,
  check = NULL,
  decode = NULL,
  retry = NULL,
  path = NULL,
  callback = NULL,
  proxy = NULL,
  tls = NULL,
  trace = FALSE,
  client = zu_default_client()
)

zu_put(
  url,
  query = NULL,
  headers = NULL,
  body = NULL,
  json = NULL,
  form = NULL,
  file = NULL,
  timeout = NULL,
  redirects = NULL,
  verify = NULL,
  max_body = NULL,
  user_agent = NULL,
  check = NULL,
  decode = NULL,
  retry = NULL,
  path = NULL,
  callback = NULL,
  proxy = NULL,
  tls = NULL,
  trace = FALSE,
  client = zu_default_client()
)

zu_patch(
  url,
  query = NULL,
  headers = NULL,
  body = NULL,
  json = NULL,
  form = NULL,
  file = NULL,
  timeout = NULL,
  redirects = NULL,
  verify = NULL,
  max_body = NULL,
  user_agent = NULL,
  check = NULL,
  decode = NULL,
  retry = NULL,
  path = NULL,
  callback = NULL,
  proxy = NULL,
  tls = NULL,
  trace = FALSE,
  client = zu_default_client()
)

zu_delete(
  url,
  query = NULL,
  headers = NULL,
  body = NULL,
  json = NULL,
  form = NULL,
  file = NULL,
  timeout = NULL,
  redirects = NULL,
  verify = NULL,
  max_body = NULL,
  user_agent = NULL,
  check = NULL,
  decode = NULL,
  retry = NULL,
  path = NULL,
  callback = NULL,
  proxy = NULL,
  tls = NULL,
  trace = FALSE,
  client = zu_default_client()
)

Arguments

url

An absolute URL, or a path joined to the client's base_url. A URL carrying credentials (⁠user:password@⁠) is refused with zu_url_error; send them as a header instead.

query

Named list of query parameters. Merged with the client's.

headers

Named character vector. Merged with the client's; NA removes an inherited header.

timeout

Total seconds, redirects included. DNS resolution is not bounded by it (nor by Ctrl-C); see zuhttp_tls.

redirects

Maximum redirects to follow.

verify

Verify the certificate and hostname. Leave this TRUE.

max_body

Maximum decoded body size in bytes; Inf for no limit.

user_agent

User-Agent to send.

check

Raise a condition for 4xx and 5xx (§31.14). FALSE returns the response whatever its status.

decode

Decompress transparently. FALSE returns the wire bytes and asks the server not to encode (§21.2).

retry

A zu_retry() policy for this request. Overrides the client's; NULL resets it to the package default, which retries nothing (§31.9). Omit it to inherit the client's.

path

Write the response body to this file instead of holding it in memory (§27). The download is written beside the destination and renamed on success, so a failed or interrupted transfer never leaves a truncated file at path. An existing file at path is replaced, and only once the body has arrived whole. Note what that does and does not cover: a transfer that fails leaves the old file untouched, but a request that completes with a non-2xx status is a successful transfer of an error page, so a 404 body is written and does replace it — check raises afterwards, too late to prevent that. Mutually exclusive with callback: a response body has one destination. Note the asymmetry with file, which is a request body source (§31.6): path is where the response goes, file is where a request body comes from.

callback

A function of one argument called with each decoded chunk as it arrives (§27). Returning FALSE stops the transfer. See zu_req_callback() for what happens when it raises an error.

proxy

Proxy URL for this request, or FALSE for a direct connection. See zu_client() for why disabling is FALSE, not NULL.

tls

Certificate trust settings from zu_tls() for this request.

trace

Collect a §35.3 event trace, readable with zu_resp_trace(). Off by default.

client

A zu_client. Always named.

body

Raw vector or string, sent as-is.

json

An object to serialise as JSON. Sets Content-Type: application/json unless you set that header yourself.

form

A named list, sent as application/x-www-form-urlencoded.

file

A path whose contents become the body.

Details

Passing NULL for a policy argument resets it to the package default rather than to the client's value — that is the documented way to escape a client default (§31.9). Omitting it inherits the client's.

Value

A zu_response.

See Also

zu_request() and zu_perform() to build a request without performing it.

Examples

# A mock transport answers instead of the network, so these run anywhere.
# Swap `client = api` for nothing and the same calls go over the wire.
echo <- zu_mock_transport(function(req) {
  zu_response(
    200L,
    c("Content-Type" = "text/plain"),
    paste(req$method, req$url)
  )
})
api <- zu_client(transport = echo)

r <- zu_get(
  "https://api.example.com/search",
  query = list(q = "HTTP", limit = 20),
  client = api
)
zu_resp_status(r)
zu_resp_text(r)

zu_resp_text(zu_delete("https://api.example.com/users/42", client = api))

zu_resp_text(zu_post(
  "https://api.example.com/users",
  json = list(name = "Alice"),
  client = api
))

if (interactive()) {
  # Download straight to disk: the body never passes through memory, and
  # the file appears at its destination only once it has arrived whole.
  dest <- tempfile(fileext = ".html")
  r <- zu_get("https://example.com", path = dest)
  zu_resp_path(r)
  zu_resp_header(r, "content-type")  # the response is still a response

  # A non-2xx body is still a body: with check = FALSE this returns the
  # 404 AND leaves the error page at `dest`. §27.1's atomicity covers a
  # failed transfer, and a 404 is a successful transfer of an error page.
  r <- zu_get("https://example.com/missing", path = dest, check = FALSE)
  zu_resp_ok(r)
  unlink(dest)
}

Perform a request

Description

The boundary between building a request and touching the network (§31.1 principle 2). Client configuration is merged into the request here, by the rules in zu_client() and §31.9.

Usage

zu_perform(req, client = zu_default_client(), stream = FALSE)

Arguments

req

A zu_request from zu_request().

client

A zu_client. Always named, never positional (§31.3).

stream

Return as soon as the response headers have arrived, with the body unread, and read it with zu_resp_read() (§65.4). Redirects and retries are complete by then. The connection stays with the response until the body is read to its end or zu_resp_abort() is called; a response dropped half-read is aborted when it is garbage-collected. Not with zu_req_path() or zu_req_callback(): a body has one destination. max_body still bounds the whole body, so a long stream needs it raised (Inf for no limit).

Value

A zu_response. By default a 4xx or 5xx status raises a condition instead; see zu_resp_check() and check = FALSE. With stream = TRUE the body is not read and the condition is raised after aborting it.

Examples

fake <- zu_mock_transport(function(req) zu_response(status = 204L))
zu_perform(zu_request("DELETE", "https://example.com/x"),
           client = zu_client(transport = fake))

Connection pool settings

Description

Passed to zu_client() as ⁠pool =⁠. The defaults are §26.2's deliberately conservative ones: a pool that is slightly too eager to discard costs latency, while one that is slightly too eager to reuse corrupts responses.

Usage

zu_pool(
  max_idle = 16L,
  max_per_host = 4L,
  idle_timeout = 30,
  keepalive_time = NULL,
  keepalive_timeout = NULL
)

Arguments

max_idle

Maximum idle connections kept across all hosts.

max_per_host

Maximum idle connections for one scheme/host/port.

idle_timeout

Seconds an unused connection may sit in the pool.

keepalive_time, keepalive_timeout

HTTP/2 keepalive, in seconds (§65.6). An idle HTTP/2 connection silent for keepalive_time is sent a PING before it is reused, and discarded unless the answer arrives within keepalive_timeout (NULL, the default, means 20 seconds) or the request's own timeout, whichever is sooner; the request then opens a new one. This finds a server or middlebox that dropped the connection without saying so. NULL, the default, sends no PING. HTTP/1.1 connections are unaffected.

Value

A zu_pool_config, for zu_client(pool = ). zu_client(pool = NULL) disables reuse entirely, which is what one-shot calls want.

What is never shared

Two requests reuse a connection only if scheme, host, port, proxy identity including credentials, and the whole TLS configuration match (§26.1). That is enforced in C, on every acquisition, by comparing the key field by field — so deriving a client with zu_client_update() can never cause a request with verify = FALSE to travel over a connection established with verification on, even though the derived client shares its parent's pool.

See Also

zu_pool_stats() to see whether reuse is actually happening.

Examples

api <- zu_client(pool = zu_pool(max_idle = 4, idle_timeout = 10))
zu_pool_stats(api)

Close a client's idle connections

Description

Drops every pooled connection without affecting the client's configuration; the next request opens a fresh one. Useful when a server has been restarted underneath a long-lived client.

Usage

zu_pool_reset(client)

Arguments

client

A zu_client.

Value

client, invisibly.

Examples

api <- zu_client()
zu_pool_reset(api)

Connection reuse counters

Description

The §26.2 counters for a client's pool. hits is the number of requests that reused an existing connection; without it, a pooled client and an unpooled one are indistinguishable from R, since both simply return responses.

Usage

zu_pool_stats(client)

Arguments

client

A zu_client.

Value

A named numeric vector, or NULL if the client has pooling disabled or has not made a request yet. discarded_fork and forks_detected count connections dropped by the §26.4 PID guard.

See Also

zu_pool(), zu_pool_reset()

Examples

zu_pool_stats(zu_client())

Add query parameters

Description

Add query parameters

Usage

zu_query(req, ...)

Arguments

req

A zu_request.

...

Named parameters. A value of length > 1 repeats the key (id = c(1, 2) becomes id=1&id=2); NULL or NA removes a parameter inherited from the client (§31.9).

Value

A zu_request.

Examples

zu_query(zu_request("GET", "https://example.com"), q = "HTTP", limit = 20)

Additional header names to redact

Description

The defaults are Authorization, Proxy-Authorization, Cookie, Set-Cookie, X-Api-Key and X-Auth-Token (§42.1). This adds to them; it cannot remove a default. Each call replaces the names registered by an earlier call, so pass the whole set at once.

Usage

zu_redact_headers(...)

Arguments

...

Header names, or a single character vector.

Value

The character vector of extra names now registered, invisibly.

Examples

old <- getOption("zuhttp.redact_headers")
zu_redact_headers("X-Session")
# Printed requests, traces, cassettes and conditions now hide it:
req <- zu_request("GET", "https://api.example.com")
zu_headers(req, `X-Session` = "abc123")
options(zuhttp.redact_headers = old)   # restore

Additional query parameter names to redact

Description

The defaults are access_token, api_key, apikey, signature, sig, client_secret, password, passwd, pwd, secret, token, refresh_token, id_token, private_key, auth_token and session_token, matched exactly and case-insensitively (§42.1). This adds to them; it cannot remove a default. Each call replaces the names registered by an earlier call, so pass the whole set at once.

Usage

zu_redact_params(...)

Arguments

...

Parameter names, or a single character vector.

Value

The character vector of extra names now registered, invisibly.

Examples

old <- getOption("zuhttp.redact_params")
zu_redact_params("ticket")
zu_redact_url("https://api.example.com/v1?ticket=ABC123&page=2")
options(zuhttp.redact_params = old)    # restore

Redact credentials from a URL

Description

Removes userinfo entirely and replaces the value of any secret query parameter with ⁠<redacted>⁠ — never with a truncated prefix, which would be enough to confirm a guess (§42.1).

Usage

zu_redact_url(url)

Arguments

url

A character vector of URLs.

Details

Works on text rather than on a parsed URL, because a URL that failed to parse is exactly the one an error message is about.

Value

A character vector of the same length.

Examples

zu_redact_url("https://user:[email protected]/v1?api_key=SECRET&page=2")

Stream the response body to a callback

Description

f is called with each decoded chunk as a raw vector, as it arrives. Returning FALSE stops the transfer cleanly (§27.2); the connection is then not reused, because its framing position is no longer known (§26.3).

Usage

zu_req_callback(req, callback)

Arguments

req

A zu_request.

callback

A function of one argument (a raw vector). Return FALSE to stop.

Value

A zu_request.

If your callback raises an error

You get your error, not a transport error wrapping it (§27.3). The callback runs inside R_tryCatch(), the native read loop unwinds normally so the socket and decompressor are released, and only then is the original condition re-signalled. That ordering is the whole point: a longjmp straight out of the read loop would leak the connection.

What you may not do inside it

Issue another request on the same client (§27.4). That would deadlock on a pool slot or interleave writes onto the connection currently being read, so it raises an error naming the problem instead. A request through a different client is unrestricted.

See Also

zu_req_path() to stream to a file instead.

Examples

total <- 0
req <- zu_req_callback(
  zu_request("GET", "https://x.test/big"),
  function(chunk) total <<- total + length(chunk)
)

Stream the response body to a file

Description

The composable equivalent of zu_get(url, path = ). The body is written to a temporary file in the same directory as path and renamed once it has arrived whole (§27.1), so a failed, cancelled or interrupted transfer never leaves a truncated file where the caller will find it and trust it.

Usage

zu_req_path(req, path)

Arguments

req

A zu_request.

path

Destination path.

Details

The same directory, rather than tempdir(): rename() is atomic only within a filesystem, and a temporary directory on another mount turns the commit into a copy that can itself fail halfway.

An existing file at path is replaced, and only at that final step — so a download that fails leaves whatever was already there untouched. A non-2xx response is not a failed download, though: the server sent a body and it is written like any other, so a 404 page replaces the file and zu_resp_check() raises after the fact rather than instead of it. Setting both this and zu_req_callback() is an error, raised when the request is performed: a response body has one destination.

Value

A zu_request.

See Also

zu_body_file(), which is the opposite direction — a request body read from a file.

Examples

req <- zu_req_path(zu_request("GET", "https://x.test/big.bin"),
                   file.path(tempdir(), "big.bin"))

Set request policy

Description

Per-request overrides of the client's policy defaults. Passing NULL resets to the package default rather than the client's value (§31.9) — which is the only way to escape a client default at the request level.

Usage

zu_req_timeout(req, total)

zu_req_redirects(req, max)

zu_req_check(req, check = TRUE)

Arguments

req

A zu_request.

total

Total seconds for the request, redirects included, as a single number. DNS resolution is not bounded by it (nor by Ctrl-C); see zuhttp_tls.

max

Maximum redirects to follow. 0 returns the 3xx response itself.

check

Raise a condition for 4xx and 5xx (§31.14).

Value

A zu_request.

Examples

zu_req_timeout(zu_request("GET", "https://example.com"), total = 5)

Whether a request is safe to replay

Description

TRUE when §33.1's second condition holds: the method is idempotent, or the caller declared it replay-safe, or the request carries an Idempotency-Key.

Usage

zu_req_replay_safe(req)

Arguments

req

A zu_request.

Value

A logical.

See Also

zu_body_rewindable(), which is §33.1's third condition.

Examples

zu_req_replay_safe(zu_request("GET", "https://x.test/"))
zu_req_replay_safe(zu_request("POST", "https://x.test/"))

Per-request retry settings

Description

The only way to make a non-idempotent request retryable. zu_retry() on a client says how to retry; this says whether this particular request may be.

Usage

zu_req_retry(
  req,
  attempts = 3L,
  replay_safe = NULL,
  idempotency_key = NULL,
  ...
)

Arguments

req

A zu_request.

attempts

Total attempts for this request; see zu_retry().

replay_safe

Declare that replaying this request is safe even though its method is not idempotent. This is a promise about the server, and only the caller can make it.

idempotency_key

TRUE to generate an Idempotency-Key header, or a string to supply one. A request carrying that header is replay-safe by §33.1, because the header is the mechanism the payment and API ecosystem standardised on for exactly this.

...

Further zu_retry() arguments.

Value

A zu_request.

See Also

zu_retry()

Examples

req <- zu_request("POST", "https://api.example.com/charges")
# A POST is never retried automatically; this is the opt-in.
req <- zu_req_retry(req, attempts = 3, idempotency_key = TRUE)
zu_req_replay_safe(req)

Record a §35.3 event trace for this request

Description

Record a §35.3 event trace for this request

Usage

zu_req_trace(req, trace = TRUE)

Arguments

req

A zu_request.

trace

TRUE (the default) to collect the trace; FALSE to turn off one that an earlier step requested.

Value

A zu_request.

See Also

zu_resp_trace() to read it back.

Examples

zu_req_trace(zu_request("GET", "https://example.com"))

Build a request without performing it

Description

Method and URL are request identity, so both are given here rather than configured later (§31.5). The result is an inert value; zu_perform() is the only thing that touches the network.

Usage

zu_request(method, url)

Arguments

method

HTTP method. Any token is allowed — "PROPFIND" works — and it is upper-cased.

url

An absolute URL, or a path to be joined to a client's base_url at perform time.

Value

A zu_request.

See Also

zu_headers(), zu_query(), zu_body_json(), zu_perform()

Examples

req <- zu_request("POST", "https://api.example.com/users")
req <- zu_body_json(req, list(name = "Alice"))
req

Response accessors

Description

Response accessors

Usage

zu_resp_status(resp)

zu_resp_path(resp)

zu_resp_ok(resp)

zu_resp_headers(resp)

zu_resp_header(resp, name)

zu_resp_url(resp)

zu_resp_method(resp)

zu_resp_timings(resp)

Arguments

resp

A zu_response.

name

A header name. Matching is case-insensitive (§18.3).

Value

zu_resp_status() an integer; zu_resp_ok() a logical, TRUE for a 2xx or 3xx status (a 3xx reaches you with redirects = 0); zu_resp_headers() a named character vector, named as the server spelled each field — over HTTP/2 that is always lowercase (RFC 9113 §8.2.1), so compare names with zu_resp_header() or tolower(); zu_resp_header() a character vector, length 0 when the header is absent and longer than 1 when it repeats; zu_resp_url() the final URL after redirects, with credentials removed (§42.1: userinfo dropped, and a secret query parameter shown as ⁠<redacted>⁠ — see the Credentials section); zu_resp_path() the file the body was written to, or NULL when it was not written to one — a response replayed from a cassette or produced by zu_mock_transport() has no file, so it reports NULL even if the request asked for a path; zu_resp_method() the method actually sent, which a 303 may have rewritten to GET; zu_resp_timings() §35.1's nine measurements — seven phase durations in seconds, then two byte counts. NA for a phase that did not happen, which a pooled connection and a plain http:// request both produce.

Credentials

zu_resp_url() is an egress, so it applies the §42.1 policy in full: a URL that went out as ?access_token=SECRET comes back as ⁠?access_token=<redacted>⁠, and userinfo is dropped entirely. Redaction happens in the engine as the URL is recorded, not here, so resp$url holds the redacted string too — there is no unredacted copy to reach for. That is deliberate: after a redirect chain the final URL is the one most likely to carry a short-lived token, and a value that exists only to be pasted into a log should not be the one that leaks. The original request URL, which the caller already has, is unaffected.

Examples

r <- zu_response(200L, c("Set-Cookie" = "a=1", "Set-Cookie" = "b=2"))
zu_resp_header(r, "set-cookie")

Raise a condition for an error status

Description

A 4xx raises zu_http_client_error, a 5xx raises zu_http_server_error, and both inherit zu_http_status_error and zu_error (§34.1). This is what requests do by default; check = FALSE returns the response instead, and this function then lets you decide later (§31.14).

Usage

zu_resp_check(resp)

Arguments

resp

A zu_response.

Details

A transport failure and an error status are deliberately different things: a 404 is a successful HTTP exchange whose answer is "no".

Value

resp, invisibly, if the status is not an error.

Examples

r <- zu_response(404L, url = "https://example.com/missing")
tryCatch(
  zu_resp_check(r),
  zu_http_client_error = function(e) conditionMessage(e)
)

Connection metadata

Description

§35.2: what actually happened at the transport layer for this response. Reported for the final hop — after a redirect chain the earlier connections are gone, and describing one of those would answer a question nobody asked.

Usage

zu_resp_connection(resp)

Arguments

resp

A zu_response.

Value

A named list: reused_connection, remote_ip, tls_protocol, tls_cipher, trust_backend, http_version, proxy_used, retries_performed and redirect_count.

Why the cipher is named and not numbered

tls_cipher reads "ECDHE-ECDSA-CHACHA20-POLY1305", not "0xcca9". The question someone opens this list to ask is whether the connection has forward secrecy and an AEAD mode, and the name answers it while the number does not. Network.framework and Schannel both report a numeric suite code; it is mapped in C so all three backends say the same kind of thing.

trust_backend is separate from the TLS engine because §13.1 splits them — on macOS the protocol is Network.framework and the trust decision is SecTrust, and "which store trusted this?" is a question users genuinely arrive with.

See Also

zu_resp_timings(), zu_info() for what the build can do.

Examples

r <- zu_response(200L)
zu_resp_connection(r)

The response body as parsed JSON, XML or HTML

Description

zu_resp_json() parses with zujson (see zu_set_json_backend() to use another implementation). zu_resp_xml() and zu_resp_html() use the zuxml and zuhtml packages, which zuhttp suggests rather than requires: install the one you need.

Usage

zu_resp_json(resp, ...)

zu_resp_xml(resp, ...)

zu_resp_html(resp, ...)

Arguments

resp

A zu_response.

...

Passed to the parser: zujson::json_parse() (for example data_frame = TRUE), zuxml::xml_parse() or zuhtml::html_parse().

Details

The body's bytes go to the parser as they arrived. A charset in Content-Type is passed on as the encoding, which for XML overrides the document's own declaration, as HTTP intends; without one the parser reads the byte-order mark or the declaration. JSON is always UTF-8 (RFC 8259). zu_resp_html() also passes the response's final URL as the base for resolving relative links.

An empty body, or one the parser rejects, raises zu_body_decode_error naming the format; the parser's own message comes last (§34.4).

Value

zu_resp_json(): vectors and lists, by zujson's type mapping (an array of objects stays a list unless data_frame = TRUE). zu_resp_xml(): a zuxml document. zu_resp_html(): a zuhtml document.

Examples

r <- zu_response(
  200L,
  c("Content-Type" = "application/json"),
  '{"name": "Alice", "tags": ["a", "b"]}'
)
str(zu_resp_json(r))

if (requireNamespace("zuxml", quietly = TRUE)) {
  x <- zu_resp_xml(zu_response(
    200L,
    c("Content-Type" = "application/xml"),
    "<feed><title>News</title></feed>"
  ))
  zuxml::xml_text(zuxml::xml_find_first(x, "title"))
}

if (requireNamespace("zuhtml", quietly = TRUE)) {
  h <- zu_resp_html(zu_response(
    200L,
    c("Content-Type" = "text/html"),
    "<title>Hello</title><p>World</p>"
  ))
  zuhtml::html_title(h)
}

The response body, decoded

Description

zu_resp_raw() returns the decoded bytes. Because Accept-Encoding: gzip is sent by default and decompression is transparent (§21.2), these are not the bytes that crossed the wire; if you are checksumming against a server-side hash, perform the request with decode = FALSE and the body will be exactly what the server sent.

Usage

zu_resp_raw(resp)

Arguments

resp

A zu_response.

Value

A raw vector.

Examples

r <- zu_response(200L, body = "hello")
zu_resp_raw(r)
rawToChar(zu_resp_raw(r))

Read a streamed response body, its trailers, or stop reading

Description

A response from zu_perform() with stream = TRUE arrives with its body unread (§65.4). zu_resp_read() returns the next piece of it: up to n decoded bytes, waiting for at least one, and a raw vector of length 0 at the end. Over HTTP/2 the server is allowed to send only as far ahead as the caller reads, so a body nobody reads holds the server at one flow-control window. max_body is enforced across the whole body, and every wait is bounded by the request's timeout afresh and interruptible with Ctrl-C. timeout bounds one call instead: a caller with a deadline for the whole stream passes what is left of it, and a read that runs out raises zu_timeout_error and ends the body, as any failed read does.

Usage

zu_resp_read(resp, n = 65536, timeout = NULL)

zu_resp_abort(resp)

zu_resp_trailers(resp, name = NULL)

Arguments

resp

A zu_response.

n

Maximum bytes to return.

timeout

Seconds this call may wait, or NULL (the default) for the request's timeout. A response that was not streamed by its transport never waits, and ignores it.

name

A field name, or NULL for all of them.

Details

zu_resp_abort() stops reading (§65.5). Over HTTP/2 it resets the stream (RST_STREAM(CANCEL)) and keeps the connection for the next request; over HTTP/1.1 it closes the connection. A second call, or a call on a body read to its end, does nothing. A later zu_resp_read() raises zu_cancelled_error.

zu_resp_trailers() returns the header fields sent after the body: HTTP/2 trailers, or a chunked HTTP/1.1 body's trailer section (§65.3, D-91). gRPC carries its status there. Matching is case-insensitive as in zu_resp_header(). For a streamed response they are known once zu_resp_read() has returned the end of the body; before that, and after zu_resp_abort() or a failed read, zu_resp_trailers() returns NULL: the trailers are unknown, which is not the same as none (D-98).

A response that was not streamed by its transport (a mock, a cassette) reads from its stored body, in pieces of n, and follows the same rules, trailers included: build one with zu_response(trailers = ). So code written against zu_resp_read() runs against zu_mock_transport() and cassettes unchanged. A streamed response has no body to hand to zu_resp_raw(), zu_resp_text() or zu_resp_json(), which refuse it.

Value

zu_resp_read() a raw vector; zu_resp_abort() resp, invisibly; zu_resp_trailers() a named character vector (name = NULL) or a character vector, length 0 when the field is absent, or NULL while a streamed body is unread.

Examples

fake <- zu_mock_transport(function(req) zu_response(200L, body = "hello"))
r <- zu_perform(
  zu_request("GET", "https://example.com/"),
  client = zu_client(transport = fake),
  stream = TRUE
)
zu_resp_read(r, 3)
zu_resp_read(r, 3)
zu_resp_read(r, 3)

The response body as text

Description

Character encoding is decided by this chain (§31.7):

Usage

zu_resp_text(resp, encoding = NULL, on_invalid = c("error", "substitute"))

Arguments

resp

A zu_response.

encoding

Encoding to assume, overriding the chain above.

on_invalid

"error" raises zu_body_decode_error on bytes that are not valid in the chosen encoding; "substitute" opts into lossy conversion. Silent corruption is not on the menu.

Details

  1. encoding if you pass one;

  2. the charset parameter of Content-Type, if iconv() knows it;

  3. a UTF-8, UTF-16LE or UTF-16BE byte-order mark, which is then stripped;

  4. otherwise UTF-8 — not the ISO-8859-1 that RFC 7231 nominally implies. That default is a historical artefact; UTF-8 is right far more often, and being wrong the other way produces mojibake users blame on the server.

For application/json, RFC 8259 mandates UTF-8, so steps 2–4 are skipped.

The result is always marked UTF-8.

Value

A single UTF-8 string.

Examples

zu_resp_text(zu_response(200L, c("Content-Type" = "text/plain"), "hi"))

The event trace for a request

Description

§35.3's lifecycle events, in order, when the request was made with trace = TRUE. This is the DNS-to-body view: the phases a timing summary can only total up.

Usage

zu_resp_trace(resp)

Arguments

resp

A zu_response.

Value

A data frame of event, at_ms, n and detail, or NULL if the request was not traced. at_ms is milliseconds from the start of the operation, so the gaps between rows are the phases.

Why a trace is collected rather than streamed

These events happen inside the connect and handshake paths, where an R error raised from a callback would longjmp past a half-built socket and a live TLS context — the §27.3 hazard, at six more call sites. A trace does not need to be live to be useful, so the engine appends to a fixed log and R renders it afterwards. Tracing off costs one NULL check per event.

Credentials

The detail of a URL-bearing event is redacted by the engine as it is recorded (§42.2): userinfo is dropped and a secret query parameter reads ⁠<redacted>⁠. It has to happen there rather than here — the trace is stored on the response, so anything this function could filter would already have been written down.

See Also

zu_resp_timings() for the summary, zu_verbose() for a printed narration.

Examples

# A trace is recorded by the network engine, so a mock has nothing to
# show; the example makes a real request and runs only interactively.
if (interactive()) {
  r <- zu_get("https://example.com", trace = TRUE)
  zu_resp_trace(r)
}

Construct a response

Description

Mostly for mock transports (§31.12) and for tests. Real responses come back from zu_perform().

Usage

zu_response(
  status = 200L,
  headers = NULL,
  body = raw(),
  url = NULL,
  tls_version = NULL,
  redirects = 0L,
  trailers = NULL
)

Arguments

status

HTTP status, a whole number from 100 to 599.

headers

Named character vector. Repeated names are allowed and are preserved (§18.3).

body

A raw vector, or a string (encoded as UTF-8).

url

The final URL.

tls_version

TLS version string, or NULL for plain HTTP.

redirects

Number of redirects followed.

trailers

Named character vector of trailer fields (§65.3), as zu_resp_trailers() returns them: where gRPC carries its status. NULL, the default, means none were sent.

Value

A zu_response.

Lifecycle

Experimental (D-65). The testing tools are exported so that package tests can run without a network, and may still change before 1.0; the request functions, response accessors and conditions are the stable API.

Examples

zu_response(200L, c("Content-Type" = "text/plain"), "hello")
zu_response(200L, body = raw(), trailers = c("grpc-status" = "0"))

Retry policy

Description

Retrying is off by default: the package default is attempts = 1.

Usage

zu_retry(
  attempts = 3L,
  backoff = c("exponential", "constant"),
  base = 1,
  max_delay = 60,
  jitter = TRUE,
  retry_after = TRUE,
  max_retry_after = 60,
  attempt_timeout = NULL,
  on = NULL
)

Arguments

attempts

Total attempts including the first, so attempts = 1 means no retrying and attempts = 3 means at most two retries.

backoff

"exponential" or "constant".

base

Seconds for the first backoff interval.

max_delay

Ceiling for a single computed backoff, in seconds.

jitter

Randomise each delay over ⁠[0, delay]⁠ ("full jitter"). On by default: synchronised retries from many R sessions are a real thundering-herd source (§33.3).

retry_after

Honour a Retry-After response header.

max_retry_after

Clamp for Retry-After, in seconds. A hostile or misconfigured server must not be able to pin an R session for hours.

attempt_timeout

Optional per-attempt bound in seconds. The total timeout still bounds the whole call (§24.3); this bounds one try.

on

Extra HTTP statuses to treat as retryable, beyond §33.2's 408, 429, 500, 502, 503 and 504: whole numbers from 100 to 599.

Details

A request with a streaming callback is not retried once the callback has been handed any bytes: what it received, and did with them, cannot be taken back, so a retry would give it a second body after the first. A retryable failure that delivered nothing, such as a 503 with an empty body, is still retried.

Value

A zu_retry_policy, for zu_client(retry = ) or zu_req_retry().

See Also

zu_req_retry() for per-request opt-in, including the replay-safety override that a POST needs.

Examples

zu_retry(attempts = 3)
zu_client(retry = zu_retry(attempts = 5, max_delay = 10))

Replace the default client

Description

Replace the default client

Usage

zu_set_default_client(client)

Arguments

client

A zu_client, or NULL to restore the package default.

Value

The previous default, invisibly.

Examples

old <- zu_set_default_client(zu_client(timeout = 5))
zu_set_default_client(old)

Choose the JSON implementation

Description

zu_body_json() and zu_resp_json() use zujson by default (zujson::json_write() and zujson::json_parse()); this replaces it with anything else, jsonlite included.

Usage

zu_set_json_backend(encode = NULL, decode = NULL)

Arguments

encode

A function ⁠(x, ...)⁠ returning a single JSON string. Must accept ..., since request-level options are forwarded to it. NULL restores zujson's.

decode

A function ⁠(txt, ...)⁠ returning an R object. NULL restores zujson's.

Value

The previous backend, invisibly.

Examples

# Any pair of functions will do; a real one would wrap a JSON package,
# e.g. encode = function(x, ...) RcppSimdJson::serialize(x).
old <- zu_set_json_backend(
  encode = function(x, ...) sprintf('{"n":%d}', length(x)),
  decode = function(txt, ...) list(text = txt)
)
req <- zu_request("POST", "https://api.example.com")
req <- zu_body_json(req, list(1, 2))
rawToChar(req$body)

zu_set_json_backend(old$encode, old$decode)   # restore

Match a request and return a canned response

Description

A stub pairs a matcher with a response. Every supplied criterion must match (they are ANDed); an omitted criterion matches anything.

Usage

zu_stub(
  response,
  method = NULL,
  url = NULL,
  regex = NULL,
  headers = NULL,
  body = NULL,
  times = Inf
)

Arguments

response

A zu_response(), or a function of one request returning one. The function form is for stubs whose reply depends on the request.

method

HTTP method to match, case-insensitive. NULL matches any.

url

URL to match. A plain string must match exactly after client merging — that is, the absolute URL with the query attached. Use regex for anything looser.

regex

A regular expression matched against the URL, as an alternative to url.

headers

Named character vector of headers that must be present with these values. Names are matched case-insensitively (§18.3); headers not named here are ignored.

body

Raw or character body that must match exactly.

times

Maximum number of times this stub may match; Inf by default. A stub with times = 1 is how you assert a request is not retried.

Value

A zu_stub, for zu_mock_transport().

Lifecycle

Experimental (D-65). The testing tools are exported so that package tests can run without a network, and may still change before 1.0; the request functions, response accessors and conditions are the stable API.

See Also

zu_mock_transport()

Examples

stub <- zu_stub(zu_response(201L), method = "POST", regex = "/users$")
api  <- zu_client(transport = zu_mock_transport(stub))
zu_resp_status(zu_perform(zu_request("POST", "https://x.test/users"),
                          client = api))

TLS and certificate trust settings

Description

TLS and certificate trust settings

Usage

zu_tls(
  ca_file = NULL,
  ca_extra = NULL,
  pins = NULL,
  revocation = FALSE,
  min_version = NULL
)

Arguments

ca_file

Path to a PEM bundle that replaces the system trust store: only these roots are trusted. Matches curl and OpenSSL, and surprises people who expect it to add — for that, use ca_extra.

ca_extra

Path to a PEM bundle that adds to the system trust store: the platform's roots are still trusted, plus these. This is the enterprise case — a corporate root alongside the public ones.

pins

Public-key pins as "sha256//<base64>" strings. Checked in addition to chain and hostname verification, never instead of it (§14.4). A connection must satisfy both, so pins with verify = FALSE raises zu_tls_unsupported_error before any connection is made.

revocation

Check certificate revocation. Off by default, and the default is deliberate — see below.

min_version

Minimum TLS version: 12 or 13.

Value

A zu_tls_config object, for zu_client(tls = ) or zu_get(url, tls = ).

Why revocation is off by default

Two measured reasons (§14.5, S0 finding F-4). It costs 7-15x on macOS — trust evaluation went from ~4-9 ms to ~62 ms, because a positive response requires an OCSP or CRL fetch. And that fetch happens inside the platform's trust evaluator, which zuhttp neither owns nor can deadline or cancel: it is invisible to the timeout model and punches a hole in the cancellation guarantee. Turning it on is a reasonable choice; making it the default would mean every request carries an uninterruptible network call nobody asked for.

Verification is not configured here

Use verify = FALSE on the client or the request. It is a merged policy argument like timeout, and having a second place to set it would make "is this connection verified?" a question with two answers.

See Also

zu_info(), which reports the effective revocation policy.

Examples

zu_tls(ca_extra = "corporate-root.pem")
zu_tls(pins = "sha256//YLh1dUR9y6Kja30RrAn7JKnbQG/uEtLMkBgFF2Fuihg=")

The TLS backend this build was linked against

Description

The TLS backend this build was linked against

Usage

zu_tls_backend()

Value

A short backend identifier, e.g. "openssl", "schannel", "network-framework".

Examples

zu_tls_backend()

Transports

Description

A transport is the object that actually performs a request. The default is the network. zu_mock_transport() takes a function of one argument — the resolved request — and returns whatever that function returns, so package tests can exercise their own code without a network, a server, or an internet-dependent CRAN check.

Usage

zu_mock_transport(handler = NULL, ...)

Arguments

handler

A function of one argument (a zu_request with client configuration already merged in) returning a zu_response(); or one or more zu_stub()s, which match on method, URL, headers and body (§37).

...

Further zu_stub()s.

Value

A transport object, for zu_client(transport = ).

Lifecycle

Experimental (D-65). The testing tools are exported so that package tests can run without a network, and may still change before 1.0; the request functions, response accessors and conditions are the stable API.

Examples

fake <- zu_mock_transport(function(req) {
  zu_response(
    status = 200L,
    body = charToRaw('{"ok":true}'),
    headers = c("Content-Type" = "application/json")
  )
})
r <- zu_get("https://example.com", client = zu_client(transport = fake))
zu_resp_status(r)
zu_resp_json(r)

Print a trace of each request

Description

Returns hooks that log the request lifecycle, for zu_client(hooks = zu_verbose()).

Usage

zu_verbose(to = stderr(), body = TRUE)

Arguments

to

A connection to write to. Defaults to stderr(), so a trace never contaminates data a script is writing to stdout.

body

Show response body sizes.

Value

A zu_hooks() object.

Credentials

A trace cannot leak one, and in two different ways. The request and response lines come from §35.3 hooks, whose payloads are redacted before any handler runs, so this function never sees a real Authorization header — there is nothing here to get right or wrong, which is why verbose logging is implemented as hooks rather than as its own path through the request. The phase lines from trace = TRUE are different: they are read off the response, so the engine redacts each URL as it records it (§42.2, D-51). A traced URL therefore shows ⁠?access_token=<redacted>⁠ rather than the token, and userinfo is dropped entirely.

Seeing the whole chain

Pair it with trace = TRUE on the request and the §35.3 phases appear — DNS, connect, TLS handshake, request, headers, body — each with the time it happened and the gap since the previous one. Without trace, the output is the HTTP layer only.

See Also

zu_resp_trace(), zu_hooks() for your own handlers.

Examples

cli <- zu_client(
  hooks = zu_verbose(),
  transport = zu_mock_transport(function(r) zu_response(200L))
)
invisible(zu_get("https://example.test/x", client = cli))

HTTPS in a forked process

Description

Why zuhttp raises zu_fork_error inside mclapply() on macOS, and what to use instead.

Details

parallel::mclapply(), parallel::mcparallel() and future's multicore plan all work by forking the R process. Two separate things go wrong when a forked child makes an HTTPS request.

The TLS engine does not survive fork() (macOS). Network.framework runs on Grand Central Dispatch, which refuses to run in a forked child of a process that already used it, and the system's trust evaluator keeps a connection to trustd that is not inherited either. A child that tries is killed outright — measured during the design spikes: a parent that had made one HTTPS request, then forked, produced children killed by SIGILL (SIGSEGV under the earlier engine); a parent that had made none produced children that survived. It is fork-after-use, not fork-at-all, which is why the failure looks intermittent and why it usually appears only once a script grows a warm-up request.

zuhttp therefore records the process ID that first opened an HTTPS connection and refuses to open one in a different process, raising zu_fork_error. That does not make forked HTTPS work. It makes it diagnosable: an error naming the cause instead of a worker vanishing.

Inherited connections. A forked child also inherits the parent's open sockets, pooled TLS sessions included. If both processes write into one TLS session the session is corrupted, and the resulting failure is nondeterministic and appears far from its cause. The same PID guard drops every inherited connection on first use in the child, without a graceful TLS shutdown — a polite close would write to a socket the parent still owns. zu_pool_stats() reports these as discarded_fork and forks_detected.

What to use instead

PSOCK clusters and future::plan("multisession") start fresh R processes with exec() rather than forking, so neither hazard exists:

cl <- parallel::makeCluster(4)
parallel::clusterEvalQ(cl, library(zuhttp))
parallel::parLapply(cl, urls, function(u) zu_get(u, path = basename(u)))
parallel::stopCluster(cl)

Plain HTTP in a forked child does not touch the trust evaluator, so it is not subject to the first hazard — but it is still subject to the second, and relying on that distinction is not worth the surprise when a URL later becomes ⁠https://⁠.

zuhttp performs one request at a time; there is no built-in concurrency, so parallelism is always the caller's to arrange.

See Also

zu_pool_stats() for the counters, zu_client() for the pool.


TLS backends and their limits

Description

Which TLS implementation zuhttp used, and what each one can and cannot do.

Details

zuhttp bundles no cryptography and no CA bundle. It uses the TLS stack and the trust store the platform already ships, chosen by ./configure at install time and reported by zu_tls_backend():

Platform Engine Trust store
Windows Schannel the system certificate stores
macOS Network.framework Keychain, via SecTrustEvaluateWithError
elsewhere system OpenSSL the system CA directory

The consequence worth knowing is that behaviour is not uniform, because the platforms are not. What follows is what actually differs.

Refused, never downgraded

Every zu_tls() setting is a request for a stronger connection. When the linked backend cannot honour one, the request raises zu_tls_unsupported_error (a zu_tls_error) before any network I/O, rather than connecting without it. zu_info()$tls_capabilities lists what this build honours:

Setting OpenSSL macOS Windows
pins yes refused refused
min_version = 13 yes yes refused
ca_file yes yes refused
ca_extra yes yes refused
revocation = TRUE refused yes, with caveats yes

A refusal is zu_tls_unsupported_error; a pin that does not match is zu_tls_pin_error. The two are different classes so that "this backend cannot pin" is never mistaken for "the pin was checked and failed".

Maximum TLS version

TLS 1.3 is negotiated wherever the server offers it, except on Windows, where zu_tls(min_version = 13) is refused rather than silently downgraded: the Schannel build available through Rtools lacks SCH_CREDENTIALS. Asking for 1.3 there raises rather than quietly giving you 1.2 — silently weakening a security setting is worse than failing. Connections still negotiate the highest version both ends support; it is the floor that cannot be raised.

Certificate pinning

zu_tls()'s pins works on OpenSSL only. On macOS and Windows the platform will not hand over the SubjectPublicKeyInfo without hand-parsing DER, and that parser is not written yet. Both refuse, because a pin that silently compares the wrong bytes is worse than no pin. A pinned request either enforces the pin or raises; it never quietly succeeds unpinned.

Custom certificate authorities

ca_file replaces the system trust store; ca_extra adds to it. The distinction is deliberate and is the usual source of confusion — with ca_file set, a public certificate that verified a moment ago will not. Neither is implemented on Windows yet: Schannel refuses both, rather than verifying against the Windows store and ignoring the file.

Revocation

Off by default: zuhttp asks for no revocation check unless told to. What the platform then does differs. OpenSSL and Schannel check nothing. macOS may check anyway: the system's trust evaluation consults Apple's own revocation data when it has it, with no policy asking for it, so a certificate Apple knows to be revoked can be rejected even with revocation = FALSE — on one run and not the next. zuhttp cannot switch that off and does not try.

zu_tls(revocation = TRUE) opts in, and what that buys you is backend-dependent in a way worth knowing before you rely on it:

  • OpenSSL: refused. OpenSSL neither downloads CRLs nor performs OCSP on its own, so a CRL check with no CRL source fails every chain, valid ones included. Rather than offer a flag that means "no connection will ever succeed", this backend raises zu_tls_unsupported_error.

  • macOS: it works, in that revoked certificates are rejected — but so are valid certificates from CAs that no longer answer revocation queries. Let's Encrypt retired OCSP, so a large share of the web fails under it.

  • Windows: Schannel checks the chain, excluding the root, through the platform's own revocation machinery.

Both caveats are recorded rather than papered over, and both are why revocation is not merely off by default but is a setting to reach for deliberately.

HTTPS through a proxy on macOS

On macOS the TLS engine is Network.framework, which opens the connection and runs the proxy's CONNECT itself. Its API for that starts with macOS 14: on macOS 11 to 13, HTTPS through a proxy raises zu_proxy_error saying so, rather than going direct. Plain ⁠http://⁠ through a proxy, and direct HTTPS, work on every macOS R supports.

Three smaller differences. A proxy that refuses the tunnel is reported as refused but without its HTTP status, which Network.framework does not pass on; a 407 is still zu_proxy_auth_error. Credentials go to the proxy when it asks for them, after its 407, rather than with the first request. And with proxy = FALSE, zuhttp asks for a direct connection, which on a Mac with a system-wide proxy configured is a preference the system may override.

Name resolution is not bounded

DNS resolution uses the system resolver (getaddrinfo()), which is synchronous. Neither timeout nor Ctrl-C interrupts it, so a host whose resolver stalls can hold R for as long as the resolver takes — on a misconfigured network, minutes. Every later phase (connect, handshake, response) is bounded by both. The exception is HTTPS on macOS, where Network.framework resolves the name itself and both apply.

See Also

zu_tls() for the settings, zu_tls_backend() for what this build linked, zu_info() for the whole configuration at once.