cachekit-rs 0.13.1

Caching for Rust (beta). Supports cachekit.io SaaS, Redis, Memcached, local File, and Cloudflare Workers.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
//! wasm32 runtime regression tests for the session clock and the Workers
//! backend's request path.
//!
//! `SystemTime::now()` / `Instant::now()` panic on `wasm32-unknown-unknown`,
//! and the compile-only wasm CI check shipped that trap in five releases —
//! these tests *execute* the affected paths on the real wasm32 target. If a
//! target gate is ever reverted to a bare std clock, the affected test traps
//! with `RuntimeError: unreachable` and the run goes red.
//!
//! Runs under `wasm-bindgen-test-runner` (Node) — see the `wasm` job in
//! `.github/workflows/ci.yml`.

#![cfg(all(target_arch = "wasm32", feature = "workers"))]

use cachekit::session::session_headers;
use wasm_bindgen_test::wasm_bindgen_test;

/// The exact panic site: building session headers on wasm32.
/// Reaching the asserts at all proves the clock (and uuid's js entropy) did
/// not trap; the value asserts check non-zero, plausible epoch millis (the
/// bounds mirror the native tests in src/session.rs, keep them in lockstep).
#[wasm_bindgen_test]
fn session_headers_valid_on_wasm32() {
    let headers = session_headers();
    assert_eq!(headers[0].0, "X-CacheKit-Session-ID");
    assert_eq!(headers[1].0, "X-CacheKit-Session-Start");

    let id = uuid::Uuid::parse_str(headers[0].1).expect("session ID should be a valid UUID");
    assert_eq!(id.get_version_num(), 4, "should be UUID v4");

    let start: u64 = headers[1]
        .1
        .parse()
        .expect("session start should be numeric");
    assert!(
        start > 1_704_067_200_000,
        "start {start} should be after 2024"
    );
    assert!(
        start < 4_102_444_800_000,
        "start {start} should be before 2100"
    );
}

/// Exercise the `WorkersCachekitIO` request path up to the fetch boundary:
/// `Backend::get` routes through `fetch()`, which injects `session_headers()`
/// (workers.rs) before any network I/O — the exact path that trapped in
/// production. `.invalid` is reserved (RFC 2606) and never resolves, so under
/// Node this fails fast with a transient network error and no live traffic.
/// A trap in session_headers() would abort the whole test instead.
#[wasm_bindgen_test]
async fn workers_backend_get_reaches_fetch_without_trapping() {
    use cachekit::backend::workers::WorkersCachekitIO;
    use cachekit::backend::Backend;

    let backend = WorkersCachekitIO::builder()
        .api_key("test-key-never-sent")
        .api_url("https://cachekit-wasm-clock.invalid")
        .allow_custom_host(true)
        .build()
        .expect("builder should accept a syntactically valid https URL");

    // Err(transient network failure) is the expected outcome; the regression
    // this guards is a wasm trap *before* the request is even built.
    let result = backend.get("wasm-clock-regression-key").await;
    assert!(
        result.is_err(),
        ".invalid must not resolve — expected a network error, got {result:?}"
    );
}

/// Starts a local HTTP server and points `globalThis.fetch` at it, keeping
/// each request's method, headers, body and redirect mode, so redirects are
/// handled by Node's real `fetch`. `redirect-{3xx}` answers that status with
/// `Location: /v1/cache/redirected`; `redirected` answers 200 to any method
/// and counts its hits in `globalThis.__ckRedirect.targetHits`.
const REDIRECT_SERVER_JS: &str = r"
    const http = process.getBuiltinModule('node:http');
    const state = (globalThis.__ckRedirect = { targetHits: 0 });
    const server = http.createServer((req, res) => {
        req.resume();
        const status = /^\/v1\/cache\/redirect-(3\d\d)$/.exec(req.url)?.[1];
        if (status) return res.writeHead(Number(status), { location: '/v1/cache/redirected' }).end();
        if (req.url === '/v1/cache/redirected') {
            state.targetHits++;
            return res.writeHead(200).end('followed');
        }
        res.writeHead(404).end();
    });
    server.unref();
    return new Promise((resolve) => server.listen(0, '127.0.0.1', () => {
        const origin = `http://127.0.0.1:${server.address().port}`;
        const realFetch = globalThis.fetch;
        globalThis.fetch = async (input, init) => {
            const req = new Request(input, init);
            const body = ['GET', 'HEAD'].includes(req.method) ? undefined : await req.arrayBuffer();
            return realFetch(origin + new URL(req.url).pathname, {
                method: req.method, headers: req.headers, body, redirect: req.redirect,
            });
        };
        state.close = () => {
            globalThis.fetch = realFetch;
            server.closeAllConnections();
            server.close();
        };
        resolve();
    }));
";

/// The API never redirects, so a 3xx from it is an error and the backend
/// sends nothing to the `Location` it names. The control shows the harness
/// does follow when a request asks it to, so the zero is not vacuous. Every
/// request runs before any assertion, so a failure never leaves `fetch`
/// patched for the other tests.
#[wasm_bindgen_test]
async fn workers_backend_does_not_follow_redirects() {
    use cachekit::backend::workers::WorkersCachekitIO;
    use cachekit::backend::Backend;
    use cachekit::BackendErrorKind;
    use worker::js_sys::{global, Function, Promise, Reflect};
    use worker::wasm_bindgen::{JsCast, JsValue};
    use worker::wasm_bindgen_futures::JsFuture;

    let backend = WorkersCachekitIO::builder()
        .api_key("test-key-never-sent")
        .build()
        .expect("default URL is valid");

    let start: Promise = Function::new_no_args(REDIRECT_SERVER_JS)
        .call0(&JsValue::NULL)
        .expect("start redirect server")
        .unchecked_into();
    JsFuture::from(start)
        .await
        .expect("redirect server listening");
    let state = Reflect::get(&global(), &"__ckRedirect".into()).expect("server state");
    let target_hits = || {
        Reflect::get(&state, &"targetHits".into())
            .ok()
            .and_then(|v| v.as_f64())
    };

    // Control: a request in follow mode reaches the redirect target.
    let mut init = worker::RequestInit::new();
    init.with_redirect(worker::RequestRedirect::Follow);
    let control = match worker::Request::new_with_init(
        "https://api.cachekit.io/v1/cache/redirect-302",
        &init,
    ) {
        Ok(request) => worker::Fetch::Request(request)
            .send()
            .await
            .map(|resp| resp.status_code()),
        Err(e) => Err(e),
    };
    let control_hits = target_hits();
    let _ = Reflect::set(&state, &"targetHits".into(), &0.into());

    let mut results = Vec::new();
    for status in [301, 302, 303, 307, 308] {
        let key = format!("redirect-{status}");
        results.push(("get", status, backend.get(&key).await.err()));
        results.push(("set", status, backend.set(&key, vec![1], None).await.err()));
        results.push(("delete", status, backend.delete(&key).await.err()));
        results.push(("exists", status, backend.exists(&key).await.err()));
    }
    let hits = target_hits();

    if let Ok(close) = Reflect::get(&state, &"close".into()) {
        let _ = close.unchecked_into::<Function>().call0(&JsValue::NULL);
    }

    assert_eq!(control.ok(), Some(200), "control: the harness follows");
    assert_eq!(
        control_hits,
        Some(1.0),
        "control: the target saw the follow"
    );
    for (op, status, err) in results {
        let err = err.unwrap_or_else(|| panic!("{op} on HTTP {status} must be an error"));
        assert_eq!(
            err.kind,
            BackendErrorKind::Permanent,
            "{op} on HTTP {status}: {err}"
        );
    }
    assert_eq!(hits, Some(0.0), "a redirect was followed");
}

/// The Workers backend sends requests to the URL it validated, as the parser
/// serialized it, never the raw input: workerd's URL parser can differ from
/// the validator's.
#[wasm_bindgen_test]
fn workers_backend_uses_the_validated_url_as_serialized() {
    use cachekit::backend::workers::WorkersCachekitIO;

    let backend = WorkersCachekitIO::builder()
        .api_key("test-key-never-sent")
        .api_url("https://api.cachekit.io\\@evil.example")
        .build()
        .expect("allowlisted host");
    assert_eq!(backend.api_url(), "https://api.cachekit.io/@evil.example");
}

/// Points `globalThis.fetch` at two stalls: a `hang` path whose promise never
/// settles, and a `stall-body` path that answers `200` with a body that never
/// ends. Every request's `AbortSignal` lands in `globalThis.__ckStall.signals`.
const STALL_FETCH_JS: &str = r"
    const state = (globalThis.__ckStall = { signals: [] });
    const realFetch = globalThis.fetch;
    globalThis.fetch = (input, init) => {
        state.signals.push(init?.signal);
        const path = new URL(new Request(input).url).pathname;
        if (path === '/v1/cache/stall-body') {
            return Promise.resolve(new Response(new ReadableStream({}), { status: 200 }));
        }
        return new Promise(() => {});
    };
    state.close = () => { globalThis.fetch = realFetch; };
";

/// Run two futures to completion together; each output carries the
/// `Date.now()` millis at which it finished.
async fn join_timed<A: std::future::Future, B: std::future::Future>(
    a: A,
    b: B,
) -> ((A::Output, f64), (B::Output, f64)) {
    use std::task::Poll;
    use worker::js_sys::Date;

    let (mut a, mut b) = (std::pin::pin!(a), std::pin::pin!(b));
    let (mut done_a, mut done_b) = (None, None);
    std::future::poll_fn(|cx| {
        if done_a.is_none() {
            if let Poll::Ready(out) = a.as_mut().poll(cx) {
                done_a = Some((out, Date::now()));
            }
        }
        if done_b.is_none() {
            if let Poll::Ready(out) = b.as_mut().poll(cx) {
                done_b = Some((out, Date::now()));
            }
        }
        if done_a.is_some() && done_b.is_some() {
            Poll::Ready(())
        } else {
            Poll::Pending
        }
    })
    .await;
    (done_a.expect("a finished"), done_b.expect("b finished"))
}

/// The Workers runtime's `fetch` sets no timeout, so the backend bounds each
/// attempt itself at the native budgets: 5 s for a read and 10 s for a write,
/// body included. Each stalled call fails with `Timeout` within its budget plus
/// 1 s and aborts its request. The three calls run concurrently, so the test
/// takes ~10 s rather than 20 s.
#[wasm_bindgen_test]
async fn workers_backend_times_out_a_stalled_request() {
    use cachekit::backend::workers::WorkersCachekitIO;
    use cachekit::backend::Backend;
    use cachekit::BackendErrorKind;
    use worker::js_sys::{global, Array, Date, Function, Reflect};
    use worker::wasm_bindgen::{JsCast, JsValue};

    let backend = WorkersCachekitIO::builder()
        .api_key("test-key-never-sent")
        .build()
        .expect("default URL is valid");

    Function::new_no_args(STALL_FETCH_JS)
        .call0(&JsValue::NULL)
        .expect("patch fetch");
    let state = Reflect::get(&global(), &"__ckStall".into()).expect("stall state");

    let start = Date::now();
    let ((get_hang, get_hang_at), (((get_body, get_body_at), (set_hang, set_hang_at)), _)) =
        join_timed(
            backend.get("hang"),
            join_timed(
                backend.get("stall-body"),
                backend.set("hang", vec![1], None),
            ),
        )
        .await;

    let signals: Array = Reflect::get(&state, &"signals".into())
        .expect("signals")
        .unchecked_into();
    let aborted: Vec<bool> = signals
        .iter()
        .map(|s| {
            Reflect::get(&s, &"aborted".into())
                .ok()
                .and_then(|v| v.as_bool())
                .unwrap_or(false)
        })
        .collect();
    if let Ok(close) = Reflect::get(&state, &"close".into()) {
        let _ = close.unchecked_into::<Function>().call0(&JsValue::NULL);
    }

    let calls = [
        ("get, no response", get_hang.err(), get_hang_at, 5_000.0),
        ("get, stalled body", get_body.err(), get_body_at, 5_000.0),
        ("set, no response", set_hang.err(), set_hang_at, 10_000.0),
    ];
    for (call, err, at, budget) in calls {
        let err = err.unwrap_or_else(|| panic!("{call}: must fail"));
        assert_eq!(err.kind, BackendErrorKind::Timeout, "{call}: {err}");
        let elapsed = at - start;
        assert!(
            elapsed >= budget - 50.0 && elapsed <= budget + 1_000.0,
            "{call}: gave up after {elapsed} ms, budget {budget} ms"
        );
    }
    assert_eq!(
        aborted,
        [true, true, true],
        "every stalled request is aborted"
    );
}

/// Await a JS `setTimeout` of `ms`, letting pending promise callbacks run.
async fn sleep_ms(ms: u32) {
    use worker::js_sys::{Function, Promise};
    use worker::wasm_bindgen::{JsCast, JsValue};
    use worker::wasm_bindgen_futures::JsFuture;

    let wait: Promise =
        Function::new_with_args("ms", "return new Promise(r => setTimeout(r, ms));")
            .call1(&JsValue::NULL, &ms.into())
            .expect("sleep")
            .unchecked_into();
    JsFuture::from(wait).await.expect("sleep resolves");
}

/// A request that answers before its budget leaves nothing behind: its
/// deadline timer and that timer's wasm callbacks are freed, so a long-lived
/// isolate does not grow with traffic.
#[wasm_bindgen_test]
async fn workers_backend_frees_the_deadline_of_a_completed_request() {
    use cachekit::backend::workers::WorkersCachekitIO;
    use cachekit::backend::Backend;
    use worker::js_sys::Function;
    use worker::wasm_bindgen::{externref_heap_live_count, JsCast, JsValue};

    let restore: Function = Function::new_no_args(
        "const old = globalThis.fetch;
         globalThis.fetch = () => Promise.resolve(new Response('ok'));
         return () => { globalThis.fetch = old; };",
    )
    .call0(&JsValue::NULL)
    .expect("patch fetch")
    .unchecked_into();
    let backend = WorkersCachekitIO::builder()
        .api_key("test-key-never-sent")
        .build()
        .expect("default URL is valid");

    let warmup = backend.get("warmup").await;
    sleep_ms(0).await;
    let before = externref_heap_live_count();
    let mut results = Vec::new();
    for _ in 0..200 {
        results.push(backend.get("ok").await);
    }
    sleep_ms(0).await;
    let retained = externref_heap_live_count() - before;
    let _ = restore.call0(&JsValue::NULL);

    assert_eq!(warmup.ok(), Some(Some(b"ok".to_vec())));
    assert!(results
        .iter()
        .all(|r| r.as_ref().ok() == Some(&Some(b"ok".to_vec()))));
    assert!(
        retained < 10,
        "200 completed requests retained {retained} live JS references"
    );
}

/// A caller that drops a call mid-flight (say, racing it against a fallback)
/// aborts its request rather than leaving it outstanding with no deadline.
#[wasm_bindgen_test]
async fn workers_backend_aborts_a_dropped_request() {
    use cachekit::backend::workers::WorkersCachekitIO;
    use cachekit::backend::Backend;
    use std::task::Poll;
    use worker::js_sys::{global, Function, Reflect};
    use worker::wasm_bindgen::{JsCast, JsValue};

    let restore: Function = Function::new_no_args(
        "const old = globalThis.fetch;
         globalThis.fetch = (_input, init) => {
             globalThis.__ckDropped = init.signal;
             return new Promise((_resolve, reject) =>
                 init.signal.addEventListener('abort', () => reject(new Error('aborted'))));
         };
         return () => { globalThis.fetch = old; };",
    )
    .call0(&JsValue::NULL)
    .expect("patch fetch")
    .unchecked_into();
    let backend = WorkersCachekitIO::builder()
        .api_key("test-key-never-sent")
        .build()
        .expect("default URL is valid");

    let mut call = backend.get("dropped");
    let pending = std::future::poll_fn(|cx| Poll::Ready(call.as_mut().poll(cx).is_pending())).await;
    drop(call);
    sleep_ms(0).await;
    let aborted = Reflect::get(&global(), &"__ckDropped".into())
        .and_then(|signal| Reflect::get(&signal, &"aborted".into()))
        .ok()
        .and_then(|v| v.as_bool());
    let _ = restore.call0(&JsValue::NULL);

    assert!(pending, "the call was in flight when dropped");
    assert_eq!(aborted, Some(true), "dropping the call aborts its request");
}