ryuk 0.1.0

A Laravel-style full-stack web framework for Rust: axum, SeaORM and Inertia, with auth, queues, mail, storage, cache, scheduling and an MCP server.
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
//! Outbound HTTP client, shaped like Laravel's `Http` facade, over `reqwest`.
//!
//! ```no_run
//! use ryuk::http::Http;
//!
//! # async fn demo() -> Result<(), ryuk::http::HttpError> {
//! let res = Http::post("https://api.example.com/orders")
//!     .bearer_token("secret")
//!     .json(&serde_json::json!({ "sku": "abc", "qty": 2 }))
//!     .timeout(std::time::Duration::from_secs(5))
//!     .retry(3, std::time::Duration::from_millis(200))
//!     .send()
//!     .await?;
//! if res.successful() {
//!     let body: serde_json::Value = res.json()?;
//!     println!("{body}");
//! }
//! # Ok(()) }
//! ```

use std::sync::OnceLock;
use std::time::Duration;

use reqwest::{Method, StatusCode};
use serde::Serialize;
use serde::de::DeserializeOwned;

/// Transport or decoding failure. HTTP error statuses are NOT errors: inspect [`Response`].
#[derive(Debug, thiserror::Error)]
pub enum HttpError {
    /// Connection, timeout, TLS, or invalid request.
    #[error("http request failed: {0}")]
    Request(#[from] reqwest::Error),
    /// A header name or value was invalid, or the body could not be serialized.
    #[error("invalid request: {0}")]
    Invalid(String),
    /// The response body was not valid JSON for the requested type.
    #[error("invalid json response: {0}")]
    Json(#[from] serde_json::Error),
}

/// Entry points: one per verb.
pub struct Http;

impl Http {
    /// Start a GET request.
    pub fn get(url: &str) -> PendingRequest {
        PendingRequest::new(Method::GET, url)
    }
    /// Start a POST request.
    pub fn post(url: &str) -> PendingRequest {
        PendingRequest::new(Method::POST, url)
    }
    /// Start a PUT request.
    pub fn put(url: &str) -> PendingRequest {
        PendingRequest::new(Method::PUT, url)
    }
    /// Start a PATCH request.
    pub fn patch(url: &str) -> PendingRequest {
        PendingRequest::new(Method::PATCH, url)
    }
    /// Start a DELETE request.
    pub fn delete(url: &str) -> PendingRequest {
        PendingRequest::new(Method::DELETE, url)
    }
}

enum Body {
    None,
    Json(serde_json::Value),
    Form(serde_json::Value),
}

/// A request being built; finish with [`PendingRequest::send`].
pub struct PendingRequest {
    method: Method,
    url: String,
    headers: Vec<(String, String)>,
    body: Body,
    bearer: Option<String>,
    timeout: Option<Duration>,
    attempts: u32,
    delay: Duration,
    err: Option<String>,
}

/// Per-attempt timeout when none is set. A request that can wait forever pins a handler or a queue
/// worker for as long as the other side stays silent; override it with [`PendingRequest::timeout`].
pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);

impl PendingRequest {
    fn new(method: Method, url: &str) -> Self {
        Self {
            method,
            url: url.into(),
            headers: Vec::new(),
            body: Body::None,
            bearer: None,
            timeout: Some(DEFAULT_TIMEOUT),
            attempts: 1,
            delay: Duration::ZERO,
            err: None,
        }
    }

    /// `Authorization: Bearer <token>`.
    pub fn bearer_token(mut self, token: &str) -> Self {
        self.bearer = Some(token.into());
        self
    }

    /// Add a header.
    pub fn with_header(mut self, name: &str, value: &str) -> Self {
        self.headers.push((name.into(), value.into()));
        self
    }

    /// JSON body (sets `Content-Type: application/json`).
    pub fn json<T: Serialize>(mut self, body: &T) -> Self {
        match serde_json::to_value(body) {
            Ok(v) => self.body = Body::Json(v),
            Err(e) => self.err = Some(e.to_string()),
        }
        self
    }

    /// URL-encoded form body; `body` must serialize to a flat map of scalars.
    pub fn form<T: Serialize>(mut self, body: &T) -> Self {
        match serde_json::to_value(body) {
            Ok(v) => self.body = Body::Form(v),
            Err(e) => self.err = Some(e.to_string()),
        }
        self
    }

    /// Per-attempt timeout (default [`DEFAULT_TIMEOUT`], 30 seconds).
    pub fn timeout(mut self, d: Duration) -> Self {
        self.timeout = Some(d);
        self
    }

    /// Try up to `times` attempts in total, waiting `delay` between them. Only connection errors and 5xx
    /// responses are retried; timeouts and 4xx are not (a retried POST that timed out may have run).
    pub fn retry(mut self, times: u32, delay: Duration) -> Self {
        self.attempts = times.max(1);
        self.delay = delay;
        self
    }

    /// Send the request and buffer the response.
    pub async fn send(self) -> Result<Response, HttpError> {
        if let Some(e) = self.err {
            return Err(HttpError::Invalid(e));
        }
        static CLIENT: OnceLock<reqwest::Client> = OnceLock::new();
        let client = CLIENT.get_or_init(reqwest::Client::new);
        let mut attempt = 1;
        loop {
            let mut rb = client.request(self.method.clone(), &self.url);
            for (k, v) in &self.headers {
                rb = rb.header(k, v);
            }
            if let Some(t) = &self.bearer {
                rb = rb.bearer_auth(t);
            }
            if let Some(t) = self.timeout {
                rb = rb.timeout(t);
            }
            rb = match &self.body {
                Body::None => rb,
                Body::Json(v) => rb.json(v),
                Body::Form(v) => rb
                    .header("content-type", "application/x-www-form-urlencoded")
                    .body(urlencode(v)),
            };
            let last = attempt >= self.attempts;
            match rb.send().await {
                Ok(res) if res.status().is_server_error() && !last => {}
                Ok(res) => {
                    let status = res.status();
                    let headers = res.headers().clone();
                    let body = res.bytes().await?.to_vec();
                    return Ok(Response {
                        status,
                        headers,
                        body,
                    });
                }
                Err(e) if e.is_connect() && !last => {}
                Err(e) => return Err(e.into()),
            }
            attempt += 1;
            tokio::time::sleep(self.delay).await;
        }
    }
}

/// A fully buffered response.
#[derive(Debug, Clone)]
pub struct Response {
    status: StatusCode,
    headers: reqwest::header::HeaderMap,
    body: Vec<u8>,
}

impl Response {
    /// Status code.
    pub fn status(&self) -> StatusCode {
        self.status
    }
    /// Status is exactly 200.
    pub fn ok(&self) -> bool {
        self.status == StatusCode::OK
    }
    /// Status is 2xx.
    pub fn successful(&self) -> bool {
        self.status.is_success()
    }
    /// Status is 4xx or 5xx.
    pub fn failed(&self) -> bool {
        self.status.is_client_error() || self.status.is_server_error()
    }
    /// Header value, if present and valid UTF-8.
    pub fn header(&self, name: &str) -> Option<&str> {
        self.headers.get(name)?.to_str().ok()
    }
    /// Raw body.
    pub fn bytes(&self) -> &[u8] {
        &self.body
    }
    /// Body as (lossy) UTF-8 text.
    pub fn text(&self) -> String {
        String::from_utf8_lossy(&self.body).into_owned()
    }
    /// Body decoded as JSON.
    pub fn json<T: DeserializeOwned>(&self) -> Result<T, HttpError> {
        Ok(serde_json::from_slice(&self.body)?)
    }
}

/// `application/x-www-form-urlencoded` for a flat JSON object (nested values are sent as their JSON text).
fn urlencode(v: &serde_json::Value) -> String {
    fn enc(s: &str) -> String {
        let mut o = String::new();
        for b in s.bytes() {
            match b {
                b' ' => o.push('+'),
                b if b.is_ascii_alphanumeric() || b"-._~".contains(&b) => o.push(b as char),
                b => o.push_str(&format!("%{b:02X}")),
            }
        }
        o
    }
    let Some(map) = v.as_object() else {
        return String::new();
    };
    map.iter()
        .filter(|(_, v)| !v.is_null())
        .map(|(k, v)| {
            let val = v
                .as_str()
                .map(str::to_owned)
                .unwrap_or_else(|| v.to_string());
            format!("{}={}", enc(k), enc(&val))
        })
        .collect::<Vec<_>>()
        .join("&")
}

#[cfg(test)]
mod tests {
    use super::*;
    use axum::{
        Json, Router,
        http::HeaderMap,
        routing::{get, post},
    };
    use std::sync::Arc;
    use std::sync::atomic::{AtomicU32, Ordering};

    async fn serve(app: Router) -> String {
        let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = l.local_addr().unwrap();
        tokio::spawn(async move { axum::serve(l, app).await.unwrap() });
        format!("http://{addr}")
    }

    #[tokio::test]
    async fn verbs_headers_json_form() {
        let app = Router::new()
            .route(
                "/echo",
                post(
                    |h: HeaderMap, Json(b): Json<serde_json::Value>| async move {
                        Json(serde_json::json!({
                            "auth": h["authorization"].to_str().unwrap(),
                            "x": h["x-test"].to_str().unwrap(),
                            "body": b,
                        }))
                    },
                )
                .get(|| async { "plain" })
                .delete(|| async { axum::http::StatusCode::NOT_FOUND }),
            )
            .route("/form", post(|body: String| async move { body }));
        let base = serve(app).await;

        let r = Http::post(&format!("{base}/echo"))
            .bearer_token("tok")
            .with_header("x-test", "1")
            .json(&serde_json::json!({"a": 1}))
            .send()
            .await
            .unwrap();
        assert!(r.ok() && r.successful() && !r.failed());
        let v: serde_json::Value = r.json().unwrap();
        assert_eq!(v["auth"], "Bearer tok");
        assert_eq!(v["x"], "1");
        assert_eq!(v["body"]["a"], 1);

        let r = Http::get(&format!("{base}/echo")).send().await.unwrap();
        assert_eq!(r.text(), "plain");
        let r = Http::delete(&format!("{base}/echo")).send().await.unwrap();
        assert!(r.failed() && !r.successful() && r.status() == 404);

        let r = Http::post(&format!("{base}/form"))
            .form(&serde_json::json!({"k": "a b"}))
            .send()
            .await
            .unwrap();
        assert_eq!(r.text(), "k=a+b");
    }

    #[tokio::test]
    async fn retries_5xx_but_not_4xx() {
        let n = Arc::new(AtomicU32::new(0));
        let (n1, n2) = (n.clone(), n.clone());
        let app = Router::new()
            .route(
                "/flaky",
                get(move || {
                    let n = n1.clone();
                    async move {
                        if n.fetch_add(1, Ordering::SeqCst) < 2 {
                            axum::http::StatusCode::BAD_GATEWAY
                        } else {
                            axum::http::StatusCode::OK
                        }
                    }
                }),
            )
            .route(
                "/bad",
                get(move || {
                    let n = n2.clone();
                    async move {
                        n.fetch_add(100, Ordering::SeqCst);
                        axum::http::StatusCode::BAD_REQUEST
                    }
                }),
            );
        let base = serve(app).await;
        let r = Http::get(&format!("{base}/flaky"))
            .retry(3, Duration::from_millis(1))
            .send()
            .await
            .unwrap();
        assert!(r.ok());
        assert_eq!(n.load(Ordering::SeqCst), 3);

        n.store(0, Ordering::SeqCst);
        let r = Http::get(&format!("{base}/bad"))
            .retry(3, Duration::from_millis(1))
            .send()
            .await
            .unwrap();
        assert_eq!(r.status(), 400);
        assert_eq!(n.load(Ordering::SeqCst), 100);

        // retries exhausted on 5xx: the last response is returned, not an error
        n.store(0, Ordering::SeqCst);
        let r = Http::get(&format!("{base}/flaky"))
            .retry(2, Duration::ZERO)
            .send()
            .await
            .unwrap();
        assert_eq!(r.status(), 502);
    }

    #[test]
    fn requests_have_a_default_timeout() {
        assert_eq!(DEFAULT_TIMEOUT, Duration::from_secs(30));
        assert_eq!(
            PendingRequest::new(Method::GET, "http://x.test").timeout,
            Some(DEFAULT_TIMEOUT)
        );
        assert_eq!(
            PendingRequest::new(Method::GET, "http://x.test")
                .timeout(Duration::from_secs(2))
                .timeout,
            Some(Duration::from_secs(2))
        );
    }

    #[tokio::test]
    async fn connect_error_is_error_after_retries_and_timeout_applies() {
        let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = l.local_addr().unwrap();
        drop(l);
        let e = Http::get(&format!("http://{addr}/"))
            .retry(2, Duration::from_millis(1))
            .send()
            .await;
        assert!(matches!(e, Err(HttpError::Request(_))));

        let base = serve(Router::new().route(
            "/slow",
            get(|| async {
                tokio::time::sleep(Duration::from_secs(5)).await;
            }),
        ))
        .await;
        let e = Http::get(&format!("{base}/slow"))
            .timeout(Duration::from_millis(50))
            .send()
            .await;
        assert!(matches!(e, Err(HttpError::Request(ref e)) if e.is_timeout()));
    }
}