typeway-server 0.1.0

Server runtime for the typeway type-level web framework
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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
//! Request extraction traits and built-in extractors.
//!
//! Extractors pull typed data from incoming HTTP requests. Each handler
//! argument is an extractor that implements [`FromRequestParts`] (for
//! metadata like path captures, headers, query strings) or [`FromRequest`]
//! (for the request body).

use bytes::Bytes;
use http::request::Parts;
use http::StatusCode;
use serde::de::DeserializeOwned;

use typeway_core::{ExtractPath, PathSpec};

use crate::response::IntoResponse;

/// Extract a value from request metadata (URI, headers, extensions).
///
/// Implementors can be used as handler arguments. Multiple `FromRequestParts`
/// extractors can appear in a single handler since they don't consume the body.
#[diagnostic::on_unimplemented(
    message = "`{Self}` cannot be extracted from request metadata",
    label = "does not implement `FromRequestParts`",
    note = "valid extractors: `Path<P>`, `State<T>`, `Query<T>`, `HeaderMap`"
)]
pub trait FromRequestParts: Sized + Send {
    /// The error type returned when extraction fails.
    type Error: IntoResponse;

    /// Extract this type from the request parts.
    fn from_request_parts(parts: &Parts) -> Result<Self, Self::Error>;
}

/// Extract a value by consuming the request body.
///
/// At most one `FromRequest` extractor can appear per handler (as the last
/// argument), since it consumes the body.
#[diagnostic::on_unimplemented(
    message = "`{Self}` cannot be extracted from the request body",
    label = "does not implement `FromRequest`",
    note = "valid body extractors: `Json<T>`, `Bytes`, `String`, `()`"
)]
pub trait FromRequest: Sized + Send {
    /// The error type returned when extraction fails.
    type Error: IntoResponse;

    /// Extract this type from the request parts and pre-collected body bytes.
    ///
    /// This is async for interface consistency, though body bytes are already
    /// collected by the router before dispatch.
    fn from_request(
        parts: &Parts,
        body: bytes::Bytes,
    ) -> impl std::future::Future<Output = Result<Self, Self::Error>> + Send;
}

// ---------------------------------------------------------------------------
// Path extractor
// ---------------------------------------------------------------------------

/// Extracts typed path captures from the URL.
///
/// The extractor reads `parts.uri.path()` directly and splits it on demand,
/// so there's no per-request `Vec<String>` allocation. When the router has
/// a configured prefix, the byte length of that prefix is stored in
/// extensions as [`PathPrefixOffset`] so this extractor can skip past it.
///
/// # Example
///
/// ```ignore
/// async fn get_user(Path((id,)): Path<path!("users" / u32)>) -> Json<User> {
///     // id: u32, extracted from /users/42
/// }
/// ```
pub struct Path<P: PathSpec>(pub P::Captures);

/// Byte offset into `parts.uri.path()` where the post-prefix path begins.
///
/// Inserted into request extensions by the router only when a prefix is
/// configured. Absent (treated as `0`) for the no-prefix case so we don't
/// touch the extensions map on the hot path.
#[derive(Copy, Clone)]
pub struct PathPrefixOffset(pub usize);

impl<P> FromRequestParts for Path<P>
where
    P: PathSpec + ExtractPath + Send,
    P::Captures: Send,
{
    type Error = (StatusCode, String);

    fn from_request_parts(parts: &Parts) -> Result<Self, Self::Error> {
        let full_path = parts.uri.path();
        let offset = parts
            .extensions
            .get::<PathPrefixOffset>()
            .map_or(0, |o| o.0);
        let path = if offset <= full_path.len() {
            &full_path[offset..]
        } else {
            ""
        };
        let segs: smallvec::SmallVec<[&str; 8]> =
            path.split('/').filter(|s| !s.is_empty()).collect();
        P::extract(&segs).map(Path).ok_or_else(|| {
            (
                StatusCode::BAD_REQUEST,
                format!(
                    "failed to parse path segments for pattern: {}",
                    P::pattern()
                ),
            )
        })
    }
}

// ---------------------------------------------------------------------------
// State extractor
// ---------------------------------------------------------------------------

/// Extracts shared application state.
///
/// State must be added to the server via [`Server::with_state`](crate::server::Server::with_state)
/// and is injected into request extensions.
///
/// # Example
///
/// ```
/// use typeway_server::State;
///
/// #[derive(Clone)]
/// struct DbPool;
///
/// async fn list_users(State(db): State<DbPool>) -> &'static str {
///     let _ = db;
///     "users"
/// }
/// ```
pub struct State<T>(pub T);

impl<T: Clone + Send + Sync + 'static> FromRequestParts for State<T> {
    type Error = (StatusCode, String);

    fn from_request_parts(parts: &Parts) -> Result<Self, Self::Error> {
        parts
            .extensions
            .get::<T>()
            .cloned()
            .map(State)
            .ok_or_else(|| {
                (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    format!(
                        "state of type `{}` not found — did you call .with_state()?",
                        std::any::type_name::<T>()
                    ),
                )
            })
    }
}

// ---------------------------------------------------------------------------
// Query extractor
// ---------------------------------------------------------------------------

/// Extracts typed query string parameters.
///
/// # Example
///
/// ```
/// use typeway_server::Query;
///
/// #[derive(serde::Deserialize)]
/// struct Pagination { page: u32, per_page: u32 }
///
/// async fn list_users(Query(p): Query<Pagination>) -> String {
///     format!("page={}, per_page={}", p.page, p.per_page)
/// }
/// ```
pub struct Query<T>(pub T);

impl<T: DeserializeOwned + Send> FromRequestParts for Query<T> {
    type Error = (StatusCode, String);

    fn from_request_parts(parts: &Parts) -> Result<Self, Self::Error> {
        let query = parts.uri.query().unwrap_or("");
        serde_urlencoded::from_str::<T>(query)
            .map(Query)
            .map_err(|e| {
                (
                    StatusCode::BAD_REQUEST,
                    format!("failed to parse query string: {e}"),
                )
            })
    }
}

// ---------------------------------------------------------------------------
// HeaderMap extractor
// ---------------------------------------------------------------------------

impl FromRequestParts for http::HeaderMap {
    type Error = (StatusCode, String);

    fn from_request_parts(parts: &Parts) -> Result<Self, Self::Error> {
        Ok(parts.headers.clone())
    }
}

// ---------------------------------------------------------------------------
// Extension extractor
// ---------------------------------------------------------------------------

/// Extracts a value from request extensions.
///
/// Use this to access arbitrary types injected by middleware or other
/// infrastructure. Unlike [`State`], extensions are per-request.
///
/// # Example
///
/// ```
/// use typeway_server::Extension;
///
/// #[derive(Clone)]
/// struct RequestId(String);
///
/// async fn handler(Extension(id): Extension<RequestId>) -> String {
///     format!("Request: {}", id.0)
/// }
/// ```
pub struct Extension<T>(pub T);

impl<T: Clone + Send + Sync + 'static> FromRequestParts for Extension<T> {
    type Error = (StatusCode, String);

    fn from_request_parts(parts: &Parts) -> Result<Self, Self::Error> {
        parts
            .extensions
            .get::<T>()
            .cloned()
            .map(Extension)
            .ok_or_else(|| {
                (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    format!(
                        "extension of type `{}` not found in request",
                        std::any::type_name::<T>()
                    ),
                )
            })
    }
}

// ---------------------------------------------------------------------------
// Cookie extractor
// ---------------------------------------------------------------------------

/// Trait for types that extract a specific named cookie.
///
/// # Example
///
/// ```
/// use typeway_server::extract::{Cookie, NamedCookie};
///
/// struct SessionId(String);
///
/// impl NamedCookie for SessionId {
///     const COOKIE_NAME: &'static str = "session_id";
///     fn from_value(value: &str) -> Result<Self, String> {
///         Ok(SessionId(value.to_string()))
///     }
/// }
///
/// async fn handler(Cookie(session): Cookie<SessionId>) -> String {
///     format!("session: {}", session.0)
/// }
/// ```
pub trait NamedCookie: Sized + Send {
    /// The cookie name to extract.
    const COOKIE_NAME: &'static str;
    /// Parse the cookie value string into this type.
    fn from_value(value: &str) -> Result<Self, String>;
}

/// Extracts a single cookie by name.
pub struct Cookie<T>(pub T);

impl<T: NamedCookie + 'static> FromRequestParts for Cookie<T> {
    type Error = (StatusCode, String);

    fn from_request_parts(parts: &Parts) -> Result<Self, Self::Error> {
        let cookies = parts
            .headers
            .get(http::header::COOKIE)
            .and_then(|v| v.to_str().ok())
            .unwrap_or("");

        for pair in cookies.split(';') {
            let pair = pair.trim();
            if let Some(value) = pair
                .strip_prefix(T::COOKIE_NAME)
                .and_then(|s| s.strip_prefix('='))
            {
                return T::from_value(value)
                    .map(Cookie)
                    .map_err(|e| (StatusCode::BAD_REQUEST, e));
            }
        }

        Err((
            StatusCode::BAD_REQUEST,
            format!("missing cookie: {}", T::COOKIE_NAME),
        ))
    }
}

/// Extracts all cookies as a key-value map.
///
/// ```
/// use typeway_server::extract::CookieJar;
///
/// async fn handler(cookies: CookieJar) -> String {
///     let session = cookies.get("session_id").unwrap_or("none");
///     format!("session: {session}")
/// }
/// ```
pub struct CookieJar(pub std::collections::HashMap<String, String>);

impl CookieJar {
    /// Get a cookie value by name.
    pub fn get(&self, name: &str) -> Option<&str> {
        self.0.get(name).map(|s| s.as_str())
    }
}

impl FromRequestParts for CookieJar {
    type Error = (StatusCode, String);

    fn from_request_parts(parts: &Parts) -> Result<Self, Self::Error> {
        let cookies = parts
            .headers
            .get(http::header::COOKIE)
            .and_then(|v| v.to_str().ok())
            .unwrap_or("");

        let map = cookies
            .split(';')
            .filter_map(|pair| {
                let pair = pair.trim();
                let (name, value) = pair.split_once('=')?;
                Some((name.to_string(), value.to_string()))
            })
            .collect();

        Ok(CookieJar(map))
    }
}

// ---------------------------------------------------------------------------
// Method extractor
// ---------------------------------------------------------------------------

/// Extracts the HTTP method from the request.
impl FromRequestParts for http::Method {
    type Error = (StatusCode, String);

    fn from_request_parts(parts: &Parts) -> Result<Self, Self::Error> {
        Ok(parts.method.clone())
    }
}

/// Extracts the request URI.
impl FromRequestParts for http::Uri {
    type Error = (StatusCode, String);

    fn from_request_parts(parts: &Parts) -> Result<Self, Self::Error> {
        Ok(parts.uri.clone())
    }
}

// ---------------------------------------------------------------------------
// Header extractor
// ---------------------------------------------------------------------------

/// Extracts a single header value by name.
///
/// The header name is derived from `T::HEADER_NAME`. Implement [`NamedHeader`]
/// on your type to use this extractor.
///
/// # Example
///
/// ```ignore
/// struct ContentType(String);
///
/// impl NamedHeader for ContentType {
///     const HEADER_NAME: &'static str = "content-type";
///     fn from_value(value: &str) -> Result<Self, String> {
///         Ok(ContentType(value.to_string()))
///     }
/// }
///
/// async fn handler(Header(ct): Header<ContentType>) -> String {
///     format!("Content-Type: {}", ct.0)
/// }
/// ```
pub struct Header<T>(pub T);

/// Trait for types that can be extracted from a named HTTP header.
pub trait NamedHeader: Sized + Send {
    /// The header name (lowercase), e.g. `"content-type"`.
    const HEADER_NAME: &'static str;

    /// Parse the header value string into this type.
    fn from_value(value: &str) -> Result<Self, String>;
}

impl<T: NamedHeader + 'static> FromRequestParts for Header<T> {
    type Error = (StatusCode, String);

    fn from_request_parts(parts: &Parts) -> Result<Self, Self::Error> {
        let value = parts
            .headers
            .get(T::HEADER_NAME)
            .ok_or_else(|| {
                (
                    StatusCode::BAD_REQUEST,
                    format!("missing required header: {}", T::HEADER_NAME),
                )
            })?
            .to_str()
            .map_err(|_| {
                (
                    StatusCode::BAD_REQUEST,
                    format!("invalid header value for: {}", T::HEADER_NAME),
                )
            })?;

        T::from_value(value)
            .map(Header)
            .map_err(|e| (StatusCode::BAD_REQUEST, e))
    }
}

// ---------------------------------------------------------------------------
// Body extractors (FromRequest)
// ---------------------------------------------------------------------------

/// JSON request body extractor.
///
/// Parses the request body as JSON. Requires `Content-Type: application/json`.
///
/// # Example
///
/// ```ignore
/// async fn create_user(Json(body): Json<CreateUser>) -> Json<User> {
///     // body: CreateUser, deserialized from JSON
/// }
/// ```
impl<T: DeserializeOwned + Send> FromRequest for crate::response::Json<T> {
    type Error = (StatusCode, String);

    async fn from_request(_parts: &Parts, body: bytes::Bytes) -> Result<Self, Self::Error> {
        serde_json::from_slice(&body)
            .map(crate::response::Json)
            .map_err(|e| (StatusCode::BAD_REQUEST, format!("invalid JSON: {e}")))
    }
}

impl FromRequest for Bytes {
    type Error = (StatusCode, String);

    async fn from_request(_parts: &Parts, body: bytes::Bytes) -> Result<Self, Self::Error> {
        Ok(body)
    }
}

impl FromRequest for String {
    type Error = (StatusCode, String);

    async fn from_request(_parts: &Parts, body: bytes::Bytes) -> Result<Self, Self::Error> {
        String::from_utf8(body.to_vec()).map_err(|e| {
            (
                StatusCode::BAD_REQUEST,
                format!("request body is not valid UTF-8: {e}"),
            )
        })
    }
}

/// Unit extractor — always succeeds, ignoring the body.
impl FromRequest for () {
    type Error = (StatusCode, String);

    async fn from_request(_parts: &Parts, _body: bytes::Bytes) -> Result<Self, Self::Error> {
        Ok(())
    }
}