Rakuest — README.en

Rakuest

English | 中文

An httpx-flavoured HTTP client for Raku. Request bodies via json / form / files / data / body-stream keywords, plain response objects (4xx/5xx are not exceptions), and cookies / redirects / retries / auth / compression / TLS trust roots handled once in the client facade.

Built on a narrow-waist design: Rakuest::Client owns policy, Rakuest::Transport does exactly one hop. The default backend is pure Raku Cro::HTTP::Client; when you need HTTP/3, SOCKS proxies, mTLS or FTP/SFTP, swap in the libcurl backend — the facade does not change.

Large files stay out of memory in both directions: uploads are pulled chunk by chunk (body-stream and every multipart file part), downloads are pushed straight through (download / stream => True). Pass progress => for per-chunk upload/download reporting, or hooks => to observe every hop and retry.

Install

zef install .

Depends on Cro::HTTP and JSON::Fast. The libcurl backend needs no extra Raku module — it FFIs straight into the system libcurl. gzip/deflate decoding uses the bundled Rakuest::Zlib (a direct binding to the system zlib, see Compression), so no third-party compression module either.

Quick start

use Rakuest;

my $client = Rakuest::Client.new(
    base-url => 'https://360.zef.pm',
    timeout  => 30,
    retry    => 2,                      # only retries transport failures
    headers  => { accept => 'application/json' },
);

my $r = $client.get('/search', params => { q => 'json' });

say $r.status;                  # 200
say $r.header('content-type');
say $r.text;
say $r.json;
say $r.content;                 # Blob (same bytes as .body / .blob)
say $r.elapsed;                 # Duration

$r.raise-for-status;            # opt-in httpx-style raise_for_status

Bodies (pick one — data is the exception: it can ride along with files as text fields):

$client.post('/api',    json  => { name => 'rakuest' });
$client.post('/form',   form  => { a => 1, b => 'x y' });
$client.post('/upload', files => { file => 'README.md' }, data => { note => 'hi' });
$client.put('/raw',     data  => 'bytes or Blob');
$client.put('/huge',    'body-stream' => 'big.iso');       # read and send as you go

Streaming upload (one chunk in memory at a time):

use Rakuest::Body;                                               # body-from-handle / body-from-path

$client.post('/upload', 'body-stream' => 'big.iso');            # path, known length → Content-Length
$client.post('/upload', 'body-stream' => $*IN);                 # IO::Handle
$client.post('/upload', 'body-stream' => $supply-of-blobs);     # unknown length → chunked
$client.post('/upload', 'body-stream' => body-from-handle($fh, :length(1024)));

multipart uploads stream too — files never enter memory as a whole:

$client.post('/upload',
    files => {
        avatar => 'me.png',              # path: read as you send, length known
        log    => $fh,                   # IO::Handle
        raw    => $blob,                 # Blob
        gen    => $supply-of-blobs,      # Supply: length unknown → whole form goes chunked
    },
    data => { note => 'hi' },            # text fields, used together with files
);

The whole form is one Rakuest::Body::Stream: part headers are constant bytes and each file part simply plugs its own stream in, so a single chunk lives in memory at a time — the same machinery as body-stream. To build the parts yourself:

use Rakuest::Form;

my $mp = Rakuest::Form::Multipart.new;
$mp.add(Rakuest::Form::Part.new(name => 'note', value => 'hi'));
$mp.add(Rakuest::Form::Part.new(name => 'f', filename => 'a.bin',
                                content-type => 'application/octet-stream',
                                stream => body-from-path('a.bin'.IO)));

$client.post('/u', 'body-stream' => $mp.to-stream, content-type => $mp.content-type);

Streaming download:

$client.download('/dist/foo.tar.gz', 'foo.tar.gz');

Or consume the bytes yourself:

my $r = $client.get('/big', stream => True);
react whenever $r.body-stream -> $chunk { ... }   # process as it arrives

Streaming responses do not negotiate content-encoding (incremental decoding is a separate layer), and elapsed means time to first byte, not total duration.

Auth:

Rakuest::Client.new(:$base-url, auth => { username => 'u', password => 'p' });  # Basic
Rakuest::Client.new(:$base-url, auth => { bearer => 'token' });                  # Bearer
$client.get('/x', auth => 'user:pass');                                          # per request

Error handling

4xx/5xx are responses, not exceptions (call raise-for-status when you want httpx's raise_for_status). What does die is "no HTTP response at all":

use Rakuest;                      # the exception family comes with the entry module

try {
    $client.get('/boom');
    CATCH {
        when X::Rakuest::Timeout        { say 'timed out, retry later' }
        when X::Rakuest::TransportError { say "cannot connect: {.message}" }
        when X::Rakuest                 { say "other failure: {.message}" }   # base class
        default                         { .rethrow }
    }
}

use Rakuest; alone is enough (since 0.4.0). If you only want the exception types without the client, use Rakuest::Error; gives you the same names.

A failing .json also lands in X::Rakuest (the library's own messages are in Chinese), and the message carries the status, content-type and the head of the body — because nine times out of ten it is not broken JSON but a 404/500 XML or HTML error page:

Rakuest: 响应不是 JSON(HTTP 404,content-type: application/xml):<?xml version="1.0"?><Error><Code>NoSuchKey</Code>…。4xx/5xx 不是异常,想直接抛就用 raise-for-status。

Speaking of which: X::Rakuest::TransportError appends a 提示: (hint) line to certificate failures, pointing at ca-file or at "the chain itself is wrong", depending on whether a CA bundle was actually loaded — no more staring at bare unable to get local issuer certificate.

Maintainer note: the classes in lib/Rakuest/Error.rakumod must not carry is export. They are named X::Rakuest…, which is not under the module's own namespace Rakuest::Error, so is export installs them under their last name component — putting a symbol called Rakuest into the importer's scope and shadowing the Rakuest package. use Rakuest; use Rakuest::Error; then fails with Redeclaration of symbol 'Rakuest'. Hence the explicit sub EXPORT at the bottom of the file; t/14-loading.rakutest guards it.

Choosing a backend

Cro is the default: pure Raku, no extra native FFI (HTTPS needs OpenSSL, gzip needs the system zlib — both are already on a normal box). Switch to libcurl when you need any of these:

CapabilityCroCurl
HTTP/1.1✅✅
HTTP/2✅depends on the libcurl build
HTTP/3❌depends on the libcurl build
HTTPS through a proxy (CONNECT)❌ see below✅
SOCKS4/5 proxies❌✅
mTLS client certificates❌✅
FTP / SFTP / SCP / SMTP…❌✅
Windows certificate store❌ (needs ca-file)✅ (Schannel)
Streaming download memorylow (Supply push)low (chunked via Channel)
Streaming upload (chunked)✅✅
Connection reuse✅ (Cro's own pool)✅ (handle pool, bucketed per host)
Read-idle timeout (read-timeout)❌✅ (low-speed detection)
Transfer progress✅ (per-chunk counters)✅ (native xferinfo, whole-body responses too)
Non-HTTP protocols (ftp/file…)❌✅
use Rakuest::Client;
use Rakuest::Transport::Curl;

my $client = Rakuest::Client.new(
    transport => Rakuest::Transport::Curl.new(
        proxy-type      => 'socks5',       # http | socks4 | socks4a | socks5 | socks5h
        proxy           => 'socks5://127.0.0.1:1080',
        client-cert     => 'client.pem',   # mTLS
        client-key      => 'client.key',
        connect-timeout => 5,
        verbose         => True,           # same as curl -v
    ),
    base-url => 'https://api.example.com',
);

say $client.transport.version;             # libcurl/8.21.0 Schannel zlib/1.3.2 …
say $client.transport.available;           # is libcurl present at all?
say $client.transport.capabilities.keys;   # ('http1' 'https' 'ftp' 'socks' 'mtls' …)

Note: an explicitly supplied transport is authoritative — the client's insecure / ca-file / ca-path no longer apply to it (set them on the backend instead). Without transport, the facade configures TLS itself as described below.

If libcurl cannot be loaded (available is false) nothing degrades silently: capabilities returns an empty set and requests throw X::Rakuest::BackendUnavailable, naming the missing library and suggesting the Cro backend.

The binding does not hardcode libcurl.so: native('curl') only resolves on a machine that has the dev package (the symlink), so at startup we probe the standard library directories for the real names — libcurl.so.4, libcurl.dylib, and so on. Same story for libc: on Debian/Ubuntu libc.so is an ld script (GROUP ( … )) and dlopen fails with invalid ELF header, so we ask for libc.so.6 / the musl sonames directly. Both can be overridden through RAKUEST_CURL_LIB / RAKUEST_CRT_LIB (a path or a bare name).

Streaming uploads and connection reuse

Request bodies are pull-based, not push-based. Once a transfer starts, the backend asks Rakuest::Body::Stream for data: the Curl backend through CURLOPT_READFUNCTION, the Cro backend through its chunked encoder. It gets exactly what it asks for, so only one chunk is ever in memory.

Known length (file, Blob) → Content-Length. Unknown (Supply) → Transfer-Encoding: chunked. Both paths are covered by tests: a 300 KB file went out in 64 KB pieces and the server received byte-identical content.

$client.post('/up', 'body-stream' => 'big.iso');        # replayable (reopens the file)
$client.post('/up', 'body-stream' => supply { ... });   # can only be sent once

Connection reuse: the Curl backend checks handles out and back in (curl_easy_reset clears options but keeps the connection cache), so sequential requests from one backend instance handshake once. On by default.

The pool is bucketed per host (key is scheme://host:port, with the host lowercased and the scheme's default port filled in), which makes max-idle-connections a per-host quota, 8 by default. Why bother: in a single flat pool, two sites fight over the same handles — under load, B's check-in pushes A's warm handle out and A has to handshake again, and "8 slots for whom" has no good answer. Bucketed, each host gets its own, and a noisy neighbour cannot touch you.

my $c = Rakuest::Client.new(transport => Rakuest::Transport::Curl.new);
$c.get('/a'); $c.get('/b'); $c.get('/c');   # the server sees a single accept
$c.close;                                    # drains the pool too

my $t = Rakuest::Transport::Curl.new(
    :max-idle-connections(8),   # 8 idle handles per host
    :max-host-pools(64),        # track 64 hosts at most; beyond that, evict an LRU bucket
);
$t.pool-size;                          # total idle handles
$t.pool-size-for('https://a.test/x');  # just this host's bucket
$t.pool-hosts;                         # which host buckets exist right now
$t.pool-key('https://a.test/x');       # → https://a.test:443

Rakuest::Transport::Curl.new(:!reuse-connections);        # one connection per request
Rakuest::Transport::Curl.new(:max-idle-connections(0));   # same

307/308 have to resend the body verbatim. Path / Blob sources can be reopened; a Supply cannot — that raises X::Rakuest::BodyReplay instead of quietly sending an empty body (the server would just see length 0, which is miserable to debug).

Non-HTTP protocols

The libcurl backend speaks FTP/SFTP/SCP/file and more, but the facade only routes http/https to the default backend — other schemes need an explicit mapping:

my $curl = Rakuest::Transport::Curl.new;

my $c = Rakuest::Client.new(
    transport  => $curl,
    transports => { 'ftp' => $curl, 'file' => $curl },
);

$c.get('ftp://127.0.0.1:2121/pub/a.txt').text;
$c.get('file:///C:/Windows/win.ini').text;

Non-HTTP protocols have no status line, so the status is normalised to 200 (a real failure is already a TransportError at the transport layer). Otherwise is-success would always be false — which is exactly why these protocols used to be listed as capabilities yet unusable.

FTP upload is not wired up yet; only the download direction is supported.

Compression

On by default: the facade sends Accept-Encoding: gzip, deflate, decodes the response according to Content-Encoding, and strips content-encoding / content-length (otherwise downstream code would read the decoded bytes as truncated).

$client.get('/x');                     # negotiate + decode
$client.get('/x', compress => False);  # per request
Rakuest::Client.new(:!compress);       # globally
$client.get('/x', headers => { 'accept-encoding' => 'identity' });  # take over

Streaming requests (download) do not negotiate: incremental decoding on a stream is a different layer, and large files are usually compressed at the Content-Type level (.tar.gz), not Content-Encoding.

An encoding we do not know (brotli/zstd) or a corrupt stream throws X::Rakuest::ContentEncoding — compressed bytes are never handed back as if they were the body.

The inflate side is our own code (Rakuest::Zlib: ~150 lines of NativeCall straight onto the system zlib), not Compress::Zlib. This is not fussiness: that module stores raw C pointers in CArray / Str fields, i.e. GC-managed slots. Load it alongside Cro's TLS stack and the first GC that lands inside an inflate loop will treat the pointers zlib wrote as object pointers and mark through them — the process segfaults. That is "HTTP client + gzip response", the most ordinary combination there is. Our binding keeps every pointer slot as uint64, so the GC never looks at them.

The price is one native dependency: zlib1g on Linux (installed by default — curl itself needs it), built into macOS, zlib1.dll on Windows (Git for Windows ships one). When it is missing, decode-body throws X::Rakuest::ContentEncoding with a message saying what to install or how to point RAKUEST_ZLIB_LIB at it, instead of returning mojibake.

Redirects, retries and timeouts

Every hop of a redirect chain is kept in response.history (oldest first, self is the last hop):

my $r = $client.get('/old');
say $r.status;               # 200
say $r.history».status;      # (301 302)  -- how many hops, at a glance
say $r.history[0].url;       # first hop, not the final address

$client.get('/old', follow => False);   # just this hop: history is empty, status is 30x

Entries in history are ordinary Response objects (status/url/headers/body), so chasing a 302 storm needs no packet capture.

Retries cover two kinds of failure, because their semantics differ:

  • Transport failures (cannot connect, TLS, dropped stream): no response to look at, so back off retry-delay * attempt and resend;

  • Statuses in retry-status (default 429 503): the server says "come back later", so honour Retry-After before resending.

Rakuest::Client.new(:$base-url, retry => 3);                        # up to 4 attempts
Rakuest::Client.new(:$base-url, retry => 3, retry-status => set()); # transport failures only
Rakuest::Client.new(:$base-url, retry => 3, max-retry-delay => 5);  # cap Retry-After at 5s

Retry-After accepts both delta-seconds and an HTTP-date; a time in the past means "retry now", and anything above max-retry-delay (60s by default) is truncated -- a server does not get to decide how long your client hangs.

Retries never gamble with a body that cannot be replayed: when a body-stream comes from a Supply (replayable is false) the 429 is returned as-is instead of silently resending an empty body (the server would only see length 0, which is miserable to debug).

Timeouts come in three layers:

OptionWhereWhat it covers
timeoutClient / per requesttotal budget for the request
connect-timeoutClientconnection establishment, 10s by default
read-timeoutCurl backendread-idle limit: abort when throughput stays under 1 byte/s for N seconds
Rakuest::Client.new(
    transport => Rakuest::Transport::Curl.new(read-timeout => 30),
    timeout   => 120,
);

"A server that accepts the connection and then plays dead" is the most common fake hang; a total timeout alone burns the whole budget on it, while read-timeout cuts it in a second or two. The Cro backend has no equivalent (its timeout only knows connect / total).

Concurrency

A single Client can be used from several threads at once:

my @responses = await @urls.map: -> $u { start { $client.get($u) } };
  • The cookie jar locks internally: absorb / header-for / clear / elems are atomic. This is not fussiness -- writing while iterating %!store.values blows up MoarVM with MVM_str_hash_at_end called with a stale hashtable pointer;

  • The default backend is created lazily under a lock, so concurrency cannot produce two connection pools (the extra one would never be closed);

  • The Curl backend's handle pool is lock-protected and bucketed per host: max-idle-connections is a per-host quota, and max-host-pools bounds how many hosts are tracked (LRU bucket eviction beyond that).

close is not concurrency-safe: stop the in-flight requests first.

Progress and hooks

Two things matter when moving large files: how far along it is and what it is actually doing. The first is progress, the second is hooks.

my $c = Rakuest::Client.new(
    :$base-url,
    # total may be Nil (chunked) -- show it as "?"
    progress => -> Rakuest::Progress $p {
        note "{$p.phase} {$p.done}/{$p.total // '?'} {$p.rate.Int} B/s";
    },
);

$c.download('/big.iso', 'big.iso');              # download, chunk by chunk
$c.post('/upload', 'body-stream' => 'big.iso');  # upload, chunk by chunk

Each callback receives an immutable snapshot (Rakuest::Progress):

FieldMeaning
phaseupload / download
done / totalbytes so far / total bytes (total undefined = unknown)
fraction / percent0..1 / 0..100; Nil when total is unknown, never a made-up 0
rate / etaaverage speed of this phase (bytes/s) / seconds remaining
attempt / hopwhich attempt / which hop of the redirect chain
url / method / elapsedaddress and method of this hop, time spent in this phase

Semantics worth pinning down:

  • A retry starts from zero — a fresh tracker per attempt, with attempt incremented, so bytes from the previous round never leak into this one;

  • Unknown stays unknown — a chunked upload/download has no total, so total / fraction / eta are Nil and the caller decides how to render "unknown";

  • The end always reports — the done == total event ignores progress-interval, so a bar never freezes at 99%;

  • Failure reports too — a broken transfer emits one final "that's where it got to" instead of pretending to succeed;

  • A throwing callback fails the request, and the exception reaches the call site unchanged. Callbacks run on the transfer thread (for Curl, inside a native callback), so keep them non-blocking. Swallowing exceptions is how you get "the bar stopped but the request succeeded" — the worst kind of bug to chase.

progress-interval is the minimum gap between callbacks (seconds, default 0 = every transfer tick). curl ticks every 64 KB — that is 16k callbacks for a 1 GB download — so a UI usually wants 0.1 (10 Hz). A single request can opt out or override:

$c.get('/poll');                        # the client-level callback
$c.get('/poll', progress => False);     # not for this request
$c.post('/up', 'body-stream' => $path, progress => &my_bar);

Lifecycle hooks

my $c = Rakuest::Client.new(
    :$base-url,
    hooks => {
        request  => -> $e { $log.info("→ {$e<method>} {$e<url>}") },
        response => -> $e { $log.info("← {$e<response>.status} {$e<url>}") },
        redirect => -> $e { $log.info("  {$e<status>} {$e<from>} → {$e<to>}") },
        retry    => -> $e { $log.info("  retry #{$e<attempt>} in {$e<delay>}s") },
    },
);
EventWhenFields
requestbefore each attemptmethod url hop attempt
responseafter each hop (4xx/5xx included)response hop attempt
redirectafter deciding to followfrom to status response
retryafter deciding to retryurl attempt delay, plus status or error

Events are Rakuest::Event; read fields with $e<field>. One event can carry several callbacks (pass an array). A misspelled event name fails at Client.new rather than silently doing nothing.

redirect and retry fire synchronously in the facade (on the caller's thread), so exceptions surface at the request() call site. Reading the body inside a hook is a trap: a streaming response has not been consumed yet.

TLS trust roots

Priority: insecure > ca-file > ca-path > auto-detection. Auto-detection checks RAKUEST_CA_FILE / SSL_CERT_FILE / CURL_CA_BUNDLE, then common paths (Git for Windows' ca-bundle.crt, /etc/ssl/certs/ca-certificates.crt, Homebrew's cert.pem, …).

Rakuest::Client.new(:$base-url);                        # auto-detect
Rakuest::Client.new(:$base-url, ca-file => 'ca.pem');
Rakuest::Client.new(:$base-url, ca-path => '/etc/ssl/certs');
Rakuest::Client.new(:$base-url, :!auto-ca);             # pass nothing, OpenSSL defaults
Rakuest::Client.new(:$base-url, insecure => True);      # tests only

A verification failure no longer dumps the bare OpenSSL sentence: a 提示: line follows, and it distinguishes no CA bundle on this machine (here is which file to point at) from bundle loaded but the chain still fails (most likely a missing intermediate certificate, or a TLS-intercepting proxy). On Windows libcurl's error text is localized (Schannel goes through FormatMessage), so the Curl backend decides by error code instead of matching strings.

Options

WhereOptionMeaning
Client.newbase-urlbase for relative URLs
timeout / connect-timeoutseconds; total budget / connect
follow / max-redirectsfollow by default, max 10
retry / retry-delaytransport-failure retries and backoff base
retry-status / max-retry-delayalso retry these statuses (default 429 503); cap for Retry-After (60s)
progress / progress-intervalupload/download progress callback; minimum gap between callbacks (seconds, default 0)
hooksrequest / response / redirect / retry callbacks
cookiesin-memory cookie jar, on by default
compressgzip/deflate negotiation, on by default
ca-file / ca-path / auto-ca / insecureTLS trust roots
proxypassed through to the backend
transportexplicit backend (TLS options above then no longer apply)
transportsscheme => backend map
get/post/...params / headersquery string / request headers
json/form/files/datarequest body (files values may be a path / IO::Handle / Blob / Supply; all streamed)
body-streamstreaming body: path / IO::Handle / Supply / Rakuest::Body::Stream
timeout / auth / compressper-request override
progressper-request progress callback (False = not for this request)
follow / max-redirectsper-request redirect policy (max-redirects => 0 means "do not follow")
streamTrue hands the body over as a Supply instead of buffering it
http-version'1.1' / '2' / '3' (backend must support it)

Options may be written as name => value or 'name' => value. Raku treats the latter as a positional argument by default — the facade adopts it as an option so you never hit Too many positionals passed.

Architecture

Rakuest::Client              policy: redirects / cookies / auth / retries / timeout / compression / TLS / capabilities
      │
Rakuest::Transport           narrow-waist role: request(Request) → Promise<Response>, one hop only
      │
Rakuest::Transport::Cro      default: pure Raku, HTTP/1.1 + HTTP/2
Rakuest::Transport::Curl     optional: NativeCall into libcurl — HTTP/2·3 / SOCKS / mTLS / FTP…
Rakuest::Zlib                gzip/deflate decoding: NativeCall into the system zlib (backend-agnostic)

Backend contract (see lib/Rakuest/Transport.rakumod):

  1. Return Rakuest::Response; 4xx/5xx are responses, not exceptions;

  2. Exactly one hop — no redirect following, no cookies, no retries, no auth injection;

  3. On transport failure die X::Rakuest::TransportError (timeouts use its subclass X::Rakuest::Timeout);

  4. For streaming requests put the body in Response.stream instead of buffering;

  5. Declare capabilities via capabilities (http1 http2 http3 ftp socks mtls…).

Because policy lives entirely in the facade, switching backends keeps both your code and the behaviour identical — which is why t/05-client.rakutest can verify all of it against a fake transport.

Writing a backend

use Rakuest::Transport;
use Rakuest::Response;

class My::Transport does Rakuest::Transport {
    method capabilities(--> Set) { set(<http1>) }

    method request(Rakuest::Request $req, Rakuest::Progress::Tracker :$progress --> Promise) {
        start {
            Rakuest::Response.new(status => 200, headers => %(), url => $req.url, blob => Blob.new);
        }
    }
}

:progress may be ignored — it is Nil when nobody asked, and the facade then omits the argument entirely. To support it, mirror what the Cro and Curl backends do: advance('upload', $n) / advance('download', $n) per chunk (or report for absolute counts), set-total when the length is known, finish when a phase ends, and abort-if-failed before finishing so an exception from the user's callback reaches the caller.

Cookies

An in-memory jar following RFC 6265 semantics (backend-independent, so behaviour never changes when you swap backends):

  • name / value / Domain / Path / Secure / Max-Age / Expires;

  • Expires understands all three historical formats — IMF-fixdate (Sun, 06 Nov 1994 08:49:37 GMT), RFC 850 (06-Nov-94) and asctime (Sun Nov 6 08:49:37 1994); an unparsable date makes it a session cookie;

  • Max-Age wins over Expires; Max-Age <= 0 or a past Expires deletes the cookie (this is how sites log you out);

  • Domain must suffix-match the request host, otherwise the whole attribute is ignored — so Set-Cookie: a=1; Domain=com cannot leak a cookie to an entire TLD;

  • on send, longer paths come first.

$client.cookies.header-for('https://a.test/x');   # what would be sent
$client.cookies.clear;
Rakuest::Client.new(:!cookies);                   # disable entirely

Limitations (0.8.2)

  • The Cro backend cannot do HTTPS through a proxy: Cro has no CONNECT tunnel, so it would send GET https://host/ in plaintext to the proxy port (leaking Authorization along with it). That is both a missing feature and a security hole, so it raises X::Rakuest::ProxyUnsupported; use NO_PROXY to bypass, or switch to the Curl backend.

  • Proxy is configured per client, not per request.

  • The pool buckets by scheme://host:port: HTTP and HTTPS to the same machine get separate buckets (they should not share a socket anyway), a different explicit port counts as a different host, and every file:// URL shares one bucket. Through a proxy the bucket is still the target host, not the proxy address — so several sites behind one proxy do not fight over tunnels.

  • For streaming responses elapsed is time-to-first-byte; if the stream breaks midway the error surfaces on the Supply and bytes already written are not rolled back.

  • multipart text fields (data) are strings only, and filenames go out as raw UTF-8 (no RFC 5987 filename*). A form either replays as a whole (all parts from paths / Blobs) or cannot follow a redirect at all — one Supply part makes 307/308 raise BodyReplay.

  • Non-HTTP protocols only cover the download direction; FTP upload is not wired up.

  • Progress counts bytes, not "work completed": a gzip response reports the compressed length (matching Content-Length), and DNS / TCP / TLS setup is not included.

  • Hooks are synchronous (they run on the caller's or the transfer thread); there is no async dispatch and no priority. progress is its own option, not a hook event.

  • Inflating needs the system zlib: when the library is missing, a response with Content-Encoding throws X::Rakuest::ContentEncoding instead of falling back to the raw compressed bytes.

  • Response headers that are not UTF-8 (an old server sending filename="报表.xlsx" in GBK) never fail the request: UTF-8 first, latin-1 as the fallback. The price is that such a header value comes out as mojibake rather than Chinese — HTTP headers carry no encoding declaration, and guessing would only hide the problem.

  • HTTP/2 requires Cro or a libcurl built with nghttp2; HTTP/3 requires a libcurl built with quiche/ngtcp2.

Windows note

IO::Socket::Async::SSL (used by Cro) does not read the Windows certificate store, so HTTPS may fail with Server certificate verification failed. Since 0.2.0 the facade locates Git for Windows' bundled ca-bundle.crt automatically, so this usually needs no configuration; otherwise pass ca-file, or switch to the Curl backend (Schannel reads the system store natively).

Inflating needs a zlib1.dll; Git for Windows keeps one in <install dir>\usr\bin\, usually already on PATH. If it cannot be found, decode-body throws X::Rakuest::ContentEncoding naming what is missing, and RAKUEST_ZLIB_LIB can point at the file directly (path or bare name).

Tests

for t in t/*.rakutest; do raku -Ilib "$t"; done

# live network tests (skipped by default)
RAKUEST_LIVE=1 raku -Ilib xt/live.rakutest
RAKUEST_LIVE=1 RAKUEST_LIVE_BACKEND=curl RAKUEST_LIVE_BASE=https://example.com raku -Ilib xt/live.rakutest

600 offline tests (subtests included; a couple of libcurl capability assertions skip on Linux, where the count is 598), no network: URL parsing, the response object (blob / content / body are the same bytes, the error text for a non-JSON body), redirect semantics and history, cookie jar (including the three Expires date formats and Domain validation), facade policy (fake backend), TLS trust-root precedence plus every certificate-hint branch (no bundle / bundle but bad chain / self-signed / expired / localized Chinese error text), gzip/deflate decoding (real bytes produced by the system gzip, all three wrappers — gzip / zlib / raw — empty input, a 300 KB round trip, and corrupt or truncated streams that must throw X::Rakuest::ContentEncoding), lenient decoding (UTF-8 passthrough, GBK error text, a GBK response header that must not fail the request), native-library soname discovery, libcurl capability negotiation and header-list layout, streaming chunking and mid-stream failure propagation, streaming uploads (300 KB byte-for-byte, chunked framing, 307 replay), multipart (hand-written RFC framing compared byte-for-byte, 300 KB file compared byte-for-byte, backend parity, handle/Blob/Supply sources, chunked fallback, 307 replay), connection reuse (by counting server-side accepts) and per-host pooling (two hosts get two buckets, per-host quota, LRU bucket eviction), file:// plus ftp:// (a minimal FTP server lives in the test), module-loading combinations (each use permutation in a child process, guarding against package-symbol clashes), concurrency (threads sharing one Client and one cookie jar), retry policy (429/503, both Retry-After formats, cap truncation), read-idle timeouts, progress (both backends x upload/download/streaming/whole-body, chunked with no total, throttling, a throwing callback), and lifecycle hooks (request/response/redirect/retry plus a misspelled event name).

Anything that needs a socket is exercised against a bare-socket server from t/lib/RakuestTestServer.rakumod — no internet, and no Cro hiding the details.

Name

Rakuest = Raku + request, and it reads like "request".

Rakuest v0.8.2

httpx 风格的 Raku HTTP 客户端:窄腰 Transport 架构,默认后端 Cro::HTTP::Client,可选 libcurl 后端(HTTP/2、SOCKS、mTLS、FTP/SFTP);流式上传/下载(含 multipart)、按 host 隔离的连接复用、重定向链、Retry-After 重试、并发安全、上传/下载进度与生命周期钩子

Authors

  • skyter10086

License

Apache-2.0

Dependencies

Test Dependencies

Provides

  • Rakuest
  • Rakuest::Body
  • Rakuest::Client
  • Rakuest::CookieJar
  • Rakuest::Encoding
  • Rakuest::Error
  • Rakuest::Event
  • Rakuest::Form
  • Rakuest::Progress
  • Rakuest::Progress::Tracker
  • Rakuest::Request
  • Rakuest::Response
  • Rakuest::Transport
  • Rakuest::Transport::Cro
  • Rakuest::Transport::Curl
  • Rakuest::URI
  • Rakuest::Util
  • Rakuest::Zlib

The Camelia image is copyright 2009 by Larry Wall. "Raku" is a trademark of the Yet Another Society. All rights reserved.

Built with Podlite — the markup and publishing tools behind this site.