| 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 |
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.
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")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")
req |
A |
x |
For |
auto_unbox |
Passed to the JSON backend. |
type |
Content type to declare. |
file |
A file path. The file is read into memory; for a body too
large for that, see |
f |
For |
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).
A zu_request.
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]] })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]] })
§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.
zu_body_rewindable(req)zu_body_rewindable(req)
req |
A |
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.
zu_body_rewindable(zu_request("GET", "https://x.test/"))zu_body_rewindable(zu_request("GET", "https://x.test/"))
Inspect or delete a cassette
zu_cassette_interactions( dir = file.path(tempdir(), "zuhttp-cassettes"), name = "default" ) zu_cassette_clear( dir = file.path(tempdir(), "zuhttp-cassettes"), name = "default" )zu_cassette_interactions( dir = file.path(tempdir(), "zuhttp-cassettes"), name = "default" ) zu_cassette_clear( dir = file.path(tempdir(), "zuhttp-cassettes"), name = "default" )
dir, name
|
The cassette's directory and name, as given to
|
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.
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.
zu_cassette_interactions(tempdir(), "no-such-cassette")zu_cassette_interactions(tempdir(), "no-such-cassette")
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.
zu_cassette_transport( dir = file.path(tempdir(), "zuhttp-cassettes"), name = "default", mode = c("auto", "replay", "record"), transport = zu_native_transport() )zu_cassette_transport( dir = file.path(tempdir(), "zuhttp-cassettes"), name = "default", mode = c("auto", "replay", "record"), transport = zu_native_transport() )
dir |
Directory holding cassettes. Defaults to a subdirectory of
|
name |
Cassette name; one file, |
mode |
|
transport |
The transport used when actually performing a request.
A |
A transport object, for zu_client(transport = ).
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.
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.
zu_cassette_interactions(), zu_cassette_clear()
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")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")
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.
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 )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 )
base_url |
Optional base URL, so that |
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. |
verify |
Verify the certificate and hostname. Leave this |
max_body |
Maximum decoded body size in bytes; |
user_agent |
Default |
check |
Raise a condition for 4xx and 5xx responses (§31.14). |
decode |
Decompress the body transparently (§21.2). |
transport |
The object that actually performs requests. The default
is the network; |
pool |
Connection reuse settings from |
retry |
A |
middleware |
A function of |
hooks |
Lifecycle observers from |
proxy |
Proxy URL, e.g. |
tls |
Certificate trust settings from |
http2 |
HTTP/2 use: |
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.
A zu_client object.
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).
zu_client_update() to derive a client without mutating it.
api <- zu_client( base_url = "https://api.example.com", headers = c(Accept = "application/json") ) apiapi <- zu_client( base_url = "https://api.example.com", headers = c(Accept = "application/json") ) api
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).
zu_client_update(client, ...)zu_client_update(client, ...)
client |
A |
... |
Fields to change, named as in |
A new zu_client.
api <- zu_client(base_url = "https://api.example.com") admin <- zu_client_update(api, headers = c(Authorization = "Bearer xyz")) identical(api$headers, NULL) # unchangedapi <- zu_client(base_url = "https://api.example.com") admin <- zu_client_update(api, headers = c(Authorization = "Bearer xyz")) identical(api$headers, NULL) # unchanged
Mostly internal, but exported so that package authors building on zuhttp can raise conditions their users can catch with the same handlers.
zu_condition( code, message, url = NULL, phase = NULL, backend = NULL, backend_code = NULL, request = NULL, response = NULL, call = sys.call(-1) )zu_condition( code, message, url = NULL, phase = NULL, backend = NULL, backend_code = NULL, request = NULL, response = NULL, call = sys.call(-1) )
code |
Integer code or class name, e.g. |
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 |
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. |
A condition object inheriting from the §34.1 classes, plus error
and condition.
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))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))
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).
zu_default_client()zu_default_client()
A zu_client.
zu_default_client()zu_default_client()
Add headers
zu_headers(req, ...)zu_headers(req, ...)
req |
A |
... |
Named header values, one value per name. A value of |
A zu_request.
zu_headers(zu_request("GET", "https://example.com"), Accept = "text/plain")zu_headers(zu_request("GET", "https://example.com"), Accept = "text/plain")
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.
zu_hooks( before_request = NULL, after_response = NULL, before_retry = NULL, after_retry = NULL )zu_hooks( before_request = NULL, after_response = NULL, before_retry = NULL, after_retry = NULL )
before_request |
Called with |
after_response |
Called with |
before_retry |
Called with |
after_retry |
Called with |
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.
A zu_hooks object, for zu_client(hooks = ).
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)) seenseen <- 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
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.
zu_info()zu_info()
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.
§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.
zu_info()zu_info()
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.
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() )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() )
url |
An absolute URL, or a path joined to the client's |
query |
Named list of query parameters. Merged with the client's. |
headers |
Named character vector. Merged with the client's; |
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 |
max_body |
Maximum decoded body size in bytes; |
user_agent |
|
check |
Raise a condition for 4xx and 5xx (§31.14). |
decode |
Decompress transparently. |
retry |
A |
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 |
callback |
A function of one argument called with each decoded chunk
as it arrives (§27). Returning |
proxy |
Proxy URL for this request, or |
tls |
Certificate trust settings from |
trace |
Collect a §35.3 event trace, readable with
|
client |
A |
body |
Raw vector or string, sent as-is. |
json |
An object to serialise as JSON. Sets |
form |
A named list, sent as |
file |
A path whose contents become the body. |
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.
A zu_response.
zu_request() and zu_perform() to build a request without
performing it.
# 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) }# 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) }
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.
zu_perform(req, client = zu_default_client(), stream = FALSE)zu_perform(req, client = zu_default_client(), stream = FALSE)
req |
A |
client |
A |
stream |
Return as soon as the response headers have arrived, with
the body unread, and read it with |
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.
fake <- zu_mock_transport(function(req) zu_response(status = 204L)) zu_perform(zu_request("DELETE", "https://example.com/x"), client = zu_client(transport = fake))fake <- zu_mock_transport(function(req) zu_response(status = 204L)) zu_perform(zu_request("DELETE", "https://example.com/x"), client = zu_client(transport = fake))
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.
zu_pool( max_idle = 16L, max_per_host = 4L, idle_timeout = 30, keepalive_time = NULL, keepalive_timeout = NULL )zu_pool( max_idle = 16L, max_per_host = 4L, idle_timeout = 30, keepalive_time = NULL, keepalive_timeout = NULL )
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 |
A zu_pool_config, for zu_client(pool = ). zu_client(pool = NULL) disables reuse entirely, which is what one-shot calls want.
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.
zu_pool_stats() to see whether reuse is actually happening.
api <- zu_client(pool = zu_pool(max_idle = 4, idle_timeout = 10)) zu_pool_stats(api)api <- zu_client(pool = zu_pool(max_idle = 4, idle_timeout = 10)) zu_pool_stats(api)
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.
zu_pool_reset(client)zu_pool_reset(client)
client |
A |
client, invisibly.
api <- zu_client() zu_pool_reset(api)api <- zu_client() zu_pool_reset(api)
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.
zu_pool_stats(client)zu_pool_stats(client)
client |
A |
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.
zu_pool_stats(zu_client())zu_pool_stats(zu_client())
Add query parameters
zu_query(req, ...)zu_query(req, ...)
req |
A |
... |
Named parameters. A value of length > 1 repeats the key
( |
A zu_request.
zu_query(zu_request("GET", "https://example.com"), q = "HTTP", limit = 20)zu_query(zu_request("GET", "https://example.com"), q = "HTTP", limit = 20)
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.
zu_redact_headers(...)zu_redact_headers(...)
... |
Header names, or a single character vector. |
The character vector of extra names now registered, invisibly.
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) # restoreold <- 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
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.
zu_redact_params(...)zu_redact_params(...)
... |
Parameter names, or a single character vector. |
The character vector of extra names now registered, invisibly.
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) # restoreold <- 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
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).
zu_redact_url(url)zu_redact_url(url)
url |
A character vector of URLs. |
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.
A character vector of the same length.
zu_redact_url("https://user:[email protected]/v1?api_key=SECRET&page=2")zu_redact_url("https://user:[email protected]/v1?api_key=SECRET&page=2")
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).
zu_req_callback(req, callback)zu_req_callback(req, callback)
req |
A |
callback |
A function of one argument (a raw vector). Return |
A zu_request.
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.
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.
zu_req_path() to stream to a file instead.
total <- 0 req <- zu_req_callback( zu_request("GET", "https://x.test/big"), function(chunk) total <<- total + length(chunk) )total <- 0 req <- zu_req_callback( zu_request("GET", "https://x.test/big"), function(chunk) total <<- total + length(chunk) )
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.
zu_req_path(req, path)zu_req_path(req, path)
req |
A |
path |
Destination path. |
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.
A zu_request.
zu_body_file(), which is the opposite direction — a request body
read from a file.
req <- zu_req_path(zu_request("GET", "https://x.test/big.bin"), file.path(tempdir(), "big.bin"))req <- zu_req_path(zu_request("GET", "https://x.test/big.bin"), file.path(tempdir(), "big.bin"))
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.
zu_req_timeout(req, total) zu_req_redirects(req, max) zu_req_check(req, check = TRUE)zu_req_timeout(req, total) zu_req_redirects(req, max) zu_req_check(req, check = TRUE)
req |
A |
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. |
check |
Raise a condition for 4xx and 5xx (§31.14). |
A zu_request.
zu_req_timeout(zu_request("GET", "https://example.com"), total = 5)zu_req_timeout(zu_request("GET", "https://example.com"), total = 5)
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.
zu_req_replay_safe(req)zu_req_replay_safe(req)
req |
A |
A logical.
zu_body_rewindable(), which is §33.1's third condition.
zu_req_replay_safe(zu_request("GET", "https://x.test/")) zu_req_replay_safe(zu_request("POST", "https://x.test/"))zu_req_replay_safe(zu_request("GET", "https://x.test/")) zu_req_replay_safe(zu_request("POST", "https://x.test/"))
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.
zu_req_retry( req, attempts = 3L, replay_safe = NULL, idempotency_key = NULL, ... )zu_req_retry( req, attempts = 3L, replay_safe = NULL, idempotency_key = NULL, ... )
req |
A |
attempts |
Total attempts for this request; see |
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 |
|
... |
Further |
A zu_request.
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)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
zu_req_trace(req, trace = TRUE)zu_req_trace(req, trace = TRUE)
req |
A |
trace |
|
A zu_request.
zu_resp_trace() to read it back.
zu_req_trace(zu_request("GET", "https://example.com"))zu_req_trace(zu_request("GET", "https://example.com"))
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.
zu_request(method, url)zu_request(method, url)
method |
HTTP method. Any token is allowed — |
url |
An absolute URL, or a path to be joined to a client's |
A zu_request.
zu_headers(), zu_query(), zu_body_json(), zu_perform()
req <- zu_request("POST", "https://api.example.com/users") req <- zu_body_json(req, list(name = "Alice")) reqreq <- zu_request("POST", "https://api.example.com/users") req <- zu_body_json(req, list(name = "Alice")) req
Response accessors
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)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)
resp |
A |
name |
A header name. Matching is case-insensitive (§18.3). |
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.
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.
r <- zu_response(200L, c("Set-Cookie" = "a=1", "Set-Cookie" = "b=2")) zu_resp_header(r, "set-cookie")r <- zu_response(200L, c("Set-Cookie" = "a=1", "Set-Cookie" = "b=2")) zu_resp_header(r, "set-cookie")
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).
zu_resp_check(resp)zu_resp_check(resp)
resp |
A |
A transport failure and an error status are deliberately different things: a 404 is a successful HTTP exchange whose answer is "no".
resp, invisibly, if the status is not an error.
r <- zu_response(404L, url = "https://example.com/missing") tryCatch( zu_resp_check(r), zu_http_client_error = function(e) conditionMessage(e) )r <- zu_response(404L, url = "https://example.com/missing") tryCatch( zu_resp_check(r), zu_http_client_error = function(e) conditionMessage(e) )
§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.
zu_resp_connection(resp)zu_resp_connection(resp)
resp |
A |
A named list: reused_connection, remote_ip, tls_protocol,
tls_cipher, trust_backend, http_version, proxy_used,
retries_performed and redirect_count.
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.
zu_resp_timings(), zu_info() for what the build can do.
r <- zu_response(200L) zu_resp_connection(r)r <- zu_response(200L) zu_resp_connection(r)
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.
zu_resp_json(resp, ...) zu_resp_xml(resp, ...) zu_resp_html(resp, ...)zu_resp_json(resp, ...) zu_resp_xml(resp, ...) zu_resp_html(resp, ...)
resp |
A |
... |
Passed to the parser: |
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).
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.
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) }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) }
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.
zu_resp_raw(resp)zu_resp_raw(resp)
resp |
A |
A raw vector.
r <- zu_response(200L, body = "hello") zu_resp_raw(r) rawToChar(zu_resp_raw(r))r <- zu_response(200L, body = "hello") zu_resp_raw(r) rawToChar(zu_resp_raw(r))
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.
zu_resp_read(resp, n = 65536, timeout = NULL) zu_resp_abort(resp) zu_resp_trailers(resp, name = NULL)zu_resp_read(resp, n = 65536, timeout = NULL) zu_resp_abort(resp) zu_resp_trailers(resp, name = NULL)
resp |
A |
n |
Maximum bytes to return. |
timeout |
Seconds this call may wait, or |
name |
A field name, or |
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.
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.
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)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)
Character encoding is decided by this chain (§31.7):
zu_resp_text(resp, encoding = NULL, on_invalid = c("error", "substitute"))zu_resp_text(resp, encoding = NULL, on_invalid = c("error", "substitute"))
resp |
A |
encoding |
Encoding to assume, overriding the chain above. |
on_invalid |
|
encoding if you pass one;
the charset parameter of Content-Type, if iconv() knows it;
a UTF-8, UTF-16LE or UTF-16BE byte-order mark, which is then stripped;
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.
A single UTF-8 string.
zu_resp_text(zu_response(200L, c("Content-Type" = "text/plain"), "hi"))zu_resp_text(zu_response(200L, c("Content-Type" = "text/plain"), "hi"))
§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.
zu_resp_trace(resp)zu_resp_trace(resp)
resp |
A |
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.
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.
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.
zu_resp_timings() for the summary, zu_verbose() for a printed
narration.
# 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) }# 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) }
Mostly for mock transports (§31.12) and for tests. Real responses come back
from zu_perform().
zu_response( status = 200L, headers = NULL, body = raw(), url = NULL, tls_version = NULL, redirects = 0L, trailers = NULL )zu_response( status = 200L, headers = NULL, body = raw(), url = NULL, tls_version = NULL, redirects = 0L, trailers = NULL )
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 |
redirects |
Number of redirects followed. |
trailers |
Named character vector of trailer fields (§65.3), as
|
A zu_response.
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.
zu_response(200L, c("Content-Type" = "text/plain"), "hello") zu_response(200L, body = raw(), trailers = c("grpc-status" = "0"))zu_response(200L, c("Content-Type" = "text/plain"), "hello") zu_response(200L, body = raw(), trailers = c("grpc-status" = "0"))
Retrying is off by default: the package default is attempts = 1.
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 )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 )
attempts |
Total attempts including the first, so |
backoff |
|
base |
Seconds for the first backoff interval. |
max_delay |
Ceiling for a single computed backoff, in seconds. |
jitter |
Randomise each delay over |
retry_after |
Honour a |
max_retry_after |
Clamp for |
attempt_timeout |
Optional per-attempt bound in seconds. The |
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. |
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.
A zu_retry_policy, for zu_client(retry = ) or
zu_req_retry().
zu_req_retry() for per-request opt-in, including the
replay-safety override that a POST needs.
zu_retry(attempts = 3) zu_client(retry = zu_retry(attempts = 5, max_delay = 10))zu_retry(attempts = 3) zu_client(retry = zu_retry(attempts = 5, max_delay = 10))
Replace the default client
zu_set_default_client(client)zu_set_default_client(client)
client |
A |
The previous default, invisibly.
old <- zu_set_default_client(zu_client(timeout = 5)) zu_set_default_client(old)old <- zu_set_default_client(zu_client(timeout = 5)) zu_set_default_client(old)
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.
zu_set_json_backend(encode = NULL, decode = NULL)zu_set_json_backend(encode = NULL, decode = NULL)
encode |
A function |
decode |
A function |
The previous backend, invisibly.
# 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# 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
A stub pairs a matcher with a response. Every supplied criterion must match (they are ANDed); an omitted criterion matches anything.
zu_stub( response, method = NULL, url = NULL, regex = NULL, headers = NULL, body = NULL, times = Inf )zu_stub( response, method = NULL, url = NULL, regex = NULL, headers = NULL, body = NULL, times = Inf )
response |
A |
method |
HTTP method to match, case-insensitive. |
url |
URL to match. A plain string must match exactly after client
merging — that is, the absolute URL with the query attached. Use |
regex |
A regular expression matched against the URL, as an
alternative to |
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; |
A zu_stub, for zu_mock_transport().
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.
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))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
zu_tls( ca_file = NULL, ca_extra = NULL, pins = NULL, revocation = FALSE, min_version = NULL )zu_tls( ca_file = NULL, ca_extra = NULL, pins = NULL, revocation = FALSE, min_version = NULL )
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 |
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 |
revocation |
Check certificate revocation. Off by default, and the default is deliberate — see below. |
min_version |
Minimum TLS version: |
A zu_tls_config object, for zu_client(tls = ) or
zu_get(url, tls = ).
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.
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.
zu_info(), which reports the effective revocation policy.
zu_tls(ca_extra = "corporate-root.pem") zu_tls(pins = "sha256//YLh1dUR9y6Kja30RrAn7JKnbQG/uEtLMkBgFF2Fuihg=")zu_tls(ca_extra = "corporate-root.pem") zu_tls(pins = "sha256//YLh1dUR9y6Kja30RrAn7JKnbQG/uEtLMkBgFF2Fuihg=")
The TLS backend this build was linked against
zu_tls_backend()zu_tls_backend()
A short backend identifier, e.g. "openssl", "schannel",
"network-framework".
zu_tls_backend()zu_tls_backend()
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.
zu_mock_transport(handler = NULL, ...)zu_mock_transport(handler = NULL, ...)
handler |
A function of one argument (a |
... |
Further |
A transport object, for zu_client(transport = ).
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.
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)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)
Returns hooks that log the request lifecycle, for
zu_client(hooks = zu_verbose()).
zu_verbose(to = stderr(), body = TRUE)zu_verbose(to = stderr(), body = TRUE)
to |
A connection to write to. Defaults to |
body |
Show response body sizes. |
A zu_hooks() object.
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.
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.
zu_resp_trace(), zu_hooks() for your own handlers.
cli <- zu_client( hooks = zu_verbose(), transport = zu_mock_transport(function(r) zu_response(200L)) ) invisible(zu_get("https://example.test/x", client = cli))cli <- zu_client( hooks = zu_verbose(), transport = zu_mock_transport(function(r) zu_response(200L)) ) invisible(zu_get("https://example.test/x", client = cli))
Why zuhttp raises zu_fork_error inside mclapply() on macOS, and what
to use instead.
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.
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.
zu_pool_stats() for the counters, zu_client() for the pool.
Which TLS implementation zuhttp used, and what each one can and cannot do.
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.
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".
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.
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.
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.
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.
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.
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.
zu_tls() for the settings, zu_tls_backend() for what this
build linked, zu_info() for the whole configuration at once.