cachekit-rs 0.5.0

Production-ready caching for Rust. 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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
//! Cloudflare Workers backend using the `worker::Fetch` API.
//!
//! This module is only compiled for `wasm32` targets (`--features workers`).
//! It uses `#[async_trait(?Send)]` because the Workers runtime is
//! single-threaded and `worker::Fetch` futures are `!Send`.

use std::collections::HashMap;
use std::time::Duration;

use async_trait::async_trait;
use zeroize::Zeroizing;

use crate::backend::saas_wire::{
    LockAcquireRequest, LockAcquireResponse, RefreshTtlRequest, TtlResponse,
};
use crate::backend::{Backend, HealthStatus, LockableBackend, TtlInspectable};
use crate::error::BackendError;
use crate::metrics::{metrics_headers, MetricsProvider};
use crate::session::session_headers;
use crate::url_validator::validate_cachekitio_url;

// ── WorkersCachekitIO ────────────────────────────────────────────────────────

/// HTTP backend for cachekit.io that uses `worker::Fetch` instead of `reqwest`.
///
/// Designed for use inside Cloudflare Workers where the standard networking
/// stack is unavailable and `worker::Fetch` is the only HTTP primitive.
pub struct WorkersCachekitIO {
    api_key: Zeroizing<String>,
    api_url: String,
    metrics_provider: Option<MetricsProvider>,
}

/// Redact `api_key` from debug output.
impl std::fmt::Debug for WorkersCachekitIO {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("WorkersCachekitIO")
            .field("api_url", &self.api_url)
            .field("api_key", &"<redacted>")
            .finish()
    }
}

impl WorkersCachekitIO {
    /// Start building a [`WorkersCachekitIO`] instance.
    pub fn builder() -> WorkersCachekitIOBuilder {
        WorkersCachekitIOBuilder::default()
    }

    /// Return the configured API URL.
    pub fn api_url(&self) -> &str {
        &self.api_url
    }

    /// Build the full URL for a cache key path segment.
    fn url(&self, key: &str) -> String {
        let encoded = urlencoding::encode(key);
        format!("{}/v1/cache/{}", self.api_url, encoded)
    }

    /// Build the health-check URL.
    fn health_url(&self) -> String {
        format!("{}/v1/cache/health", self.api_url)
    }

    /// Build the lock URL for a cache key. Callers pass the bare cache key;
    /// the SaaS lock endpoint owns the lock namespace server-side.
    fn lock_url(&self, key: &str) -> String {
        format!("{}/lock", self.url(key))
    }

    /// Build the TTL URL for a cache key.
    fn ttl_url(&self, key: &str) -> String {
        format!("{}/ttl", self.url(key))
    }

    /// Convert a non-success response into a classified, sanitized error.
    async fn error_from_response(&self, mut resp: worker::Response) -> BackendError {
        let status = resp.status_code();
        let body = resp.bytes().await.unwrap_or_default();
        let sanitized = BackendError::sanitize_message(
            std::str::from_utf8(&body).unwrap_or(""),
            self.api_key.as_str(),
        );
        BackendError::from_http_status(status, sanitized.as_bytes())
    }

    /// Execute a fetch request with the given method, URL, optional body, and extra headers.
    async fn fetch(
        &self,
        method: &str,
        url: &str,
        body: Option<Vec<u8>>,
        extra_headers: Vec<(&str, String)>,
    ) -> Result<worker::Response, BackendError> {
        let mut headers = worker::Headers::new();
        headers
            .set(
                "Authorization",
                &format!("Bearer {}", self.api_key.as_str()),
            )
            .map_err(|e| {
                BackendError::permanent(BackendError::sanitize_message(
                    &format!("failed to set auth header: {e}"),
                    self.api_key.as_str(),
                ))
            })?;

        for (name, value) in extra_headers {
            headers.set(name, &value).map_err(|e| {
                BackendError::permanent(BackendError::sanitize_message(
                    &format!("failed to set header {name}: {e}"),
                    self.api_key.as_str(),
                ))
            })?;
        }

        // Inject session headers
        for (name, value) in session_headers() {
            headers.set(name, &value).map_err(|e| {
                BackendError::permanent(format!("failed to set session header {name}: {e}"))
            })?;
        }

        // Inject metrics headers
        for (name, value) in metrics_headers(self.metrics_provider.as_ref()) {
            headers.set(name, &value).map_err(|e| {
                BackendError::permanent(format!("failed to set metrics header {name}: {e}"))
            })?;
        }

        let mut init = worker::RequestInit::new();
        init.with_method(match method {
            "GET" => worker::Method::Get,
            "PUT" => worker::Method::Put,
            "POST" => worker::Method::Post,
            "PATCH" => worker::Method::Patch,
            "DELETE" => worker::Method::Delete,
            "HEAD" => worker::Method::Head,
            _ => {
                return Err(BackendError::permanent(format!(
                    "unsupported HTTP method: {method}"
                )))
            }
        });
        init.with_headers(headers);

        if let Some(bytes) = body {
            let js_array = js_sys::Uint8Array::from(bytes.as_slice());
            init.with_body(Some(js_array.into()));
        }

        let request = worker::Request::new_with_init(url, &init).map_err(|e| {
            BackendError::transient(BackendError::sanitize_message(
                &format!("failed to build request: {e}"),
                self.api_key.as_str(),
            ))
        })?;

        worker::Fetch::Request(request).send().await.map_err(|e| {
            BackendError::transient(BackendError::sanitize_message(
                &format!("fetch failed: {e}"),
                self.api_key.as_str(),
            ))
        })
    }
}

// ── Backend impl (wasm32 only) ───────────────────────────────────────────────

#[async_trait(?Send)]
impl Backend for WorkersCachekitIO {
    async fn get(&self, key: &str) -> Result<Option<Vec<u8>>, BackendError> {
        let mut resp = self.fetch("GET", &self.url(key), None, vec![]).await?;

        match resp.status_code() {
            200 => {
                let bytes = resp.bytes().await.map_err(|e| {
                    BackendError::transient(BackendError::sanitize_message(
                        &format!("failed to read body: {e}"),
                        self.api_key.as_str(),
                    ))
                })?;
                Ok(Some(bytes))
            }
            404 => Ok(None),
            _ => Err(self.error_from_response(resp).await),
        }
    }

    async fn set(
        &self,
        key: &str,
        value: Vec<u8>,
        ttl: Option<Duration>,
    ) -> Result<(), BackendError> {
        let mut headers = vec![("Content-Type", "application/octet-stream".to_owned())];
        if let Some(ttl) = ttl {
            headers.push(("X-TTL", ttl.as_secs().to_string()));
        }

        let mut resp = self
            .fetch("PUT", &self.url(key), Some(value), headers)
            .await?;
        let status = resp.status_code();

        if (200..300).contains(&status) {
            Ok(())
        } else {
            Err(self.error_from_response(resp).await)
        }
    }

    async fn delete(&self, key: &str) -> Result<bool, BackendError> {
        let mut resp = self.fetch("DELETE", &self.url(key), None, vec![]).await?;

        match resp.status_code() {
            200 | 204 => Ok(true),
            404 => Ok(false),
            _ => Err(self.error_from_response(resp).await),
        }
    }

    async fn exists(&self, key: &str) -> Result<bool, BackendError> {
        let resp = self.fetch("HEAD", &self.url(key), None, vec![]).await?;

        match resp.status_code() {
            200 => Ok(true),
            404 => Ok(false),
            status => Err(BackendError::from_http_status(status, &[])),
        }
    }

    async fn health(&self) -> Result<HealthStatus, BackendError> {
        let mut resp = self.fetch("GET", &self.health_url(), None, vec![]).await?;
        let status = resp.status_code();

        if (200..300).contains(&status) {
            let mut details = HashMap::new();
            details.insert("http_status".to_string(), status.to_string());
            Ok(HealthStatus {
                is_healthy: true,
                latency_ms: 0.0,
                backend_type: "workers-cachekitio".to_string(),
                details,
            })
        } else {
            Err(self.error_from_response(resp).await)
        }
    }
}

// ── LockableBackend impl (wasm32 only) ───────────────────────────────────────

/// Lock capability token travels in this request header, never the query
/// string (CWE-532): a `?lock_id=` query leaks the token into access/proxy
/// logs and OpenTelemetry `http.url` spans. Same contract as the native
/// `CachekitIO` impl. See protocol `spec/saas-api.md`.
const LOCK_ID_HEADER: &str = "X-CacheKit-Lock-Id";

#[async_trait(?Send)]
impl LockableBackend for WorkersCachekitIO {
    async fn acquire_lock(
        &self,
        key: &str,
        timeout_ms: u64,
    ) -> Result<Option<String>, BackendError> {
        let body = serde_json::to_vec(&LockAcquireRequest { timeout_ms }).map_err(|e| {
            BackendError::permanent(format!("failed to serialize lock request: {e}"))
        })?;

        let mut resp = self
            .fetch(
                "POST",
                &self.lock_url(key),
                Some(body),
                vec![("Content-Type", "application/json".to_owned())],
            )
            .await?;

        if !(200..300).contains(&resp.status_code()) {
            return Err(self.error_from_response(resp).await);
        }

        // Contested acquire is `200 {"lock_id": null}` — branch on the body,
        // never on a 409 status (protocol#22 / LAB-240).
        let bytes = resp.bytes().await.map_err(|e| {
            BackendError::transient(BackendError::sanitize_message(
                &format!("failed to read lock response: {e}"),
                self.api_key.as_str(),
            ))
        })?;
        let response: LockAcquireResponse = serde_json::from_slice(&bytes)
            .map_err(|e| BackendError::transient(format!("failed to parse lock response: {e}")))?;

        Ok(response.lock_id)
    }

    async fn release_lock(&self, key: &str, lock_id: &str) -> Result<bool, BackendError> {
        // lock_id is a capability token → X-CacheKit-Lock-Id header, not the
        // query string (CWE-532).
        let resp = self
            .fetch(
                "DELETE",
                &self.lock_url(key),
                None,
                vec![(LOCK_ID_HEADER, lock_id.to_owned())],
            )
            .await?;

        match resp.status_code() {
            200 | 204 => Ok(true),
            404 => Ok(false),
            _ => Err(self.error_from_response(resp).await),
        }
    }
}

// ── TtlInspectable impl (wasm32 only) ────────────────────────────────────────

#[async_trait(?Send)]
impl TtlInspectable for WorkersCachekitIO {
    async fn ttl(&self, key: &str) -> Result<Option<Duration>, BackendError> {
        let mut resp = self.fetch("GET", &self.ttl_url(key), None, vec![]).await?;

        match resp.status_code() {
            200 => {
                let bytes = resp.bytes().await.map_err(|e| {
                    BackendError::transient(BackendError::sanitize_message(
                        &format!("failed to read TTL response: {e}"),
                        self.api_key.as_str(),
                    ))
                })?;
                let body: TtlResponse = serde_json::from_slice(&bytes).map_err(|e| {
                    BackendError::transient(format!("failed to parse TTL response: {e}"))
                })?;
                Ok(body.ttl.map(Duration::from_secs))
            }
            404 => Ok(None),
            _ => Err(self.error_from_response(resp).await),
        }
    }

    async fn refresh_ttl(&self, key: &str, ttl: Duration) -> Result<bool, BackendError> {
        let secs = ttl.as_secs();
        if secs == 0 {
            return Err(BackendError::permanent(
                "refresh_ttl requires at least 1 second".to_string(),
            ));
        }

        let body = serde_json::to_vec(&RefreshTtlRequest { ttl: secs }).map_err(|e| {
            BackendError::permanent(format!("failed to serialize refresh_ttl request: {e}"))
        })?;

        let resp = self
            .fetch(
                "PATCH",
                &self.ttl_url(key),
                Some(body),
                vec![("Content-Type", "application/json".to_owned())],
            )
            .await?;

        match resp.status_code() {
            200 | 204 => Ok(true),
            404 => Ok(false),
            _ => Err(self.error_from_response(resp).await),
        }
    }
}

// ── Builder ──────────────────────────────────────────────────────────────────

/// Builder for [`WorkersCachekitIO`].
#[derive(Default)]
#[must_use]
pub struct WorkersCachekitIOBuilder {
    api_key: Option<Zeroizing<String>>,
    api_url: Option<String>,
    allow_custom_host: bool,
    metrics_provider: Option<MetricsProvider>,
}

impl WorkersCachekitIOBuilder {
    /// Set the API key (required).
    pub fn api_key(mut self, key: impl Into<String>) -> Self {
        self.api_key = Some(Zeroizing::new(key.into()));
        self
    }

    /// Override the API base URL (default: `https://api.cachekit.io`).
    pub fn api_url(mut self, url: impl Into<String>) -> Self {
        self.api_url = Some(url.into());
        self
    }

    /// Allow non-standard hostnames (e.g. custom proxies). Private IPs are still blocked.
    pub fn allow_custom_host(mut self, allow: bool) -> Self {
        self.allow_custom_host = allow;
        self
    }

    /// Provide L1 cache metrics for request telemetry headers.
    pub fn metrics_provider(mut self, provider: MetricsProvider) -> Self {
        self.metrics_provider = Some(provider);
        self
    }

    /// Consume the builder and construct a [`WorkersCachekitIO`].
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - `api_key` was not set or is empty.
    /// - the resolved URL scheme is not `https`.
    /// - the URL hostname is not permitted (see [`validate_cachekitio_url`]).
    pub fn build(self) -> Result<WorkersCachekitIO, crate::error::CachekitError> {
        use crate::error::CachekitError;

        let api_key = self
            .api_key
            .filter(|k| !k.is_empty())
            .ok_or_else(|| CachekitError::Config("api_key is required".to_string()))?;

        let api_url = self
            .api_url
            .unwrap_or_else(|| "https://api.cachekit.io".to_string());

        // Validate URL: HTTPS, allowed host, no private IPs.
        validate_cachekitio_url(&api_url, self.allow_custom_host)?;

        // Trim trailing slash once so url()/health_url() don't repeat it per-request.
        let api_url = api_url.trim_end_matches('/').to_string();

        Ok(WorkersCachekitIO {
            api_key,
            api_url,
            metrics_provider: self.metrics_provider,
        })
    }
}