camber 0.1.1

Opinionated async Rust for IO-bound services on top of Tokio
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
use super::method::Method;
use super::middleware::MiddlewareFn;
use super::response::IntoResponse;
use super::sse::SseWriter;
use super::stream::StreamResponse;
use super::trie::{RouteHandler, TrieNode};
#[cfg(feature = "ws")]
use super::websocket::WsConn;
use super::{Request, Response};
use crate::RuntimeError;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;

use super::BufferConfig;

// Re-export dispatch types so existing `super::router::*` imports keep working.
#[cfg(feature = "grpc")]
pub use super::dispatch::GrpcRouter;
#[cfg(feature = "ws")]
pub(super) use super::dispatch::WsHandler;
pub(super) use super::dispatch::{
    DispatchResult, FrozenRouter, GateCheck, Handler, ServerDispatch, SseHandler, gate_result,
};

impl std::fmt::Debug for Router {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Router")
            .field("middleware_count", &self.middleware.len())
            .field("buffers", &self.buffers)
            .field(
                "skip_middleware_for_internal",
                &self.skip_middleware_for_internal,
            )
            .finish()
    }
}

/// Maps HTTP method + path pairs to handler functions.
///
/// Routes are inserted into a trie during registration, then frozen
/// via `freeze()` before serving. Static segments take priority over
/// parameterized segments (`:name`) during matching.
pub struct Router {
    root: TrieNode,
    middleware: Vec<MiddlewareFn>,
    buffers: BufferConfig,
    skip_middleware_for_internal: bool,
    #[cfg(feature = "grpc")]
    grpc_router: Option<super::dispatch::GrpcRouter>,
}

impl Default for Router {
    fn default() -> Self {
        Self {
            root: TrieNode::new(),
            middleware: Vec::new(),
            buffers: BufferConfig::default(),
            skip_middleware_for_internal: false,
            #[cfg(feature = "grpc")]
            grpc_router: None,
        }
    }
}

impl Router {
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the maximum request body size in bytes (capped at 256 MB).
    #[must_use]
    pub fn max_request_body(mut self, bytes: usize) -> Self {
        self.buffers = self.buffers.with_max_request_body(bytes);
        self
    }

    /// Set the channel buffer size for SSE connections.
    ///
    /// Controls how many events can be queued before backpressure applies.
    /// Default: 32.
    #[must_use]
    pub fn sse_buffer_size(mut self, size: usize) -> Self {
        self.buffers = self.buffers.with_sse_buffer_size(size);
        self
    }

    /// Set the channel buffer size for WebSocket connections.
    ///
    /// Controls how many messages can be queued in each direction before
    /// backpressure applies. Default: 32.
    #[cfg(feature = "ws")]
    #[must_use]
    pub fn ws_buffer_size(mut self, size: usize) -> Self {
        self.buffers = self.buffers.with_ws_buffer_size(size);
        self
    }

    pub(super) fn buffer_config(&self) -> BufferConfig {
        self.buffers
    }

    /// Skip middleware for internal routes (`/health`, `/metrics`, `/debug/pprof/cpu`).
    ///
    /// Default: `false` (middleware applies to all routes including internal ones).
    /// Set to `true` to restore the pre-v3 behavior where internal routes bypass middleware,
    /// useful when health probes (Kubernetes, load balancers) cannot send auth headers.
    #[must_use]
    pub fn skip_middleware_for_internal(mut self, skip: bool) -> Self {
        self.skip_middleware_for_internal = skip;
        self
    }

    /// Register async middleware that wraps all route handlers.
    ///
    /// Middleware registered first executes outermost (wraps all later
    /// middleware). Each middleware receives the request and a `Next`
    /// handle — call `next.call(req).await` to continue the chain.
    ///
    /// ```ignore
    /// router.use_middleware(|req, next| async move {
    ///     let resp = next.call(req).await;
    ///     resp.with_header("X-Custom", "value")
    /// });
    /// ```
    pub fn use_middleware<F, Fut>(&mut self, mw: F)
    where
        F: Fn(&Request, super::middleware::Next) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Response> + Send + 'static,
    {
        self.middleware
            .push(Box::new(move |req, next| Box::pin(mw(req, next))));
    }

    pub fn get<F, Fut, R>(&mut self, path: &str, handler: F)
    where
        F: Fn(&Request) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = R> + Send + 'static,
        R: IntoResponse + 'static,
    {
        self.add(Method::Get, path, handler);
    }

    pub fn post<F, Fut, R>(&mut self, path: &str, handler: F)
    where
        F: Fn(&Request) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = R> + Send + 'static,
        R: IntoResponse + 'static,
    {
        self.add(Method::Post, path, handler);
    }

    pub fn put<F, Fut, R>(&mut self, path: &str, handler: F)
    where
        F: Fn(&Request) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = R> + Send + 'static,
        R: IntoResponse + 'static,
    {
        self.add(Method::Put, path, handler);
    }

    pub fn delete<F, Fut, R>(&mut self, path: &str, handler: F)
    where
        F: Fn(&Request) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = R> + Send + 'static,
        R: IntoResponse + 'static,
    {
        self.add(Method::Delete, path, handler);
    }

    pub fn patch<F, Fut, R>(&mut self, path: &str, handler: F)
    where
        F: Fn(&Request) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = R> + Send + 'static,
        R: IntoResponse + 'static,
    {
        self.add(Method::Patch, path, handler);
    }

    pub fn head<F, Fut, R>(&mut self, path: &str, handler: F)
    where
        F: Fn(&Request) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = R> + Send + 'static,
        R: IntoResponse + 'static,
    {
        self.add(Method::Head, path, handler);
    }

    pub fn options<F, Fut, R>(&mut self, path: &str, handler: F)
    where
        F: Fn(&Request) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = R> + Send + 'static,
        R: IntoResponse + 'static,
    {
        self.add(Method::Options, path, handler);
    }

    /// Register an async streaming handler for GET requests.
    ///
    /// The handler returns a `StreamResponse` for incremental body delivery.
    /// Use `StreamResponse::new()` to get both the response and a sender.
    pub fn get_stream(
        &mut self,
        path: &str,
        handler: impl Fn(&Request) -> Pin<Box<dyn Future<Output = StreamResponse> + Send>>
        + Send
        + Sync
        + 'static,
    ) {
        self.add_stream(Method::Get, path, handler);
    }

    /// Register an async streaming handler for POST requests.
    pub fn post_stream(
        &mut self,
        path: &str,
        handler: impl Fn(&Request) -> Pin<Box<dyn Future<Output = StreamResponse> + Send>>
        + Send
        + Sync
        + 'static,
    ) {
        self.add_stream(Method::Post, path, handler);
    }

    /// Register an SSE streaming handler for GET requests.
    ///
    /// The handler receives the request and an `SseWriter` for sending events.
    /// The connection stays open until the handler returns or the client disconnects.
    pub fn get_sse(
        &mut self,
        path: &str,
        handler: impl Fn(&Request, &mut SseWriter) -> Result<(), RuntimeError> + Send + Sync + 'static,
    ) {
        self.root
            .insert_route(Method::Get, path, RouteHandler::Sse(Arc::new(handler)));
    }

    /// Register a WebSocket handler for the given path.
    ///
    /// The handler receives the upgrade request and a bidirectional `WsConn`.
    /// The connection stays open until the handler returns or the client disconnects.
    #[cfg(feature = "ws")]
    pub fn ws(
        &mut self,
        path: &str,
        handler: impl Fn(&Request, WsConn) -> Result<(), RuntimeError> + Send + Sync + 'static,
    ) {
        self.root.insert_route(
            Method::Get,
            path,
            RouteHandler::WebSocket(Arc::new(handler)),
        );
    }

    /// Register a gRPC service (generated by `camber-build`).
    ///
    /// Requests with `content-type: application/grpc` are forwarded to the
    /// tonic service. All other requests go through normal HTTP routing.
    #[cfg(feature = "grpc")]
    pub fn grpc(&mut self, grpc_router: super::dispatch::GrpcRouter) {
        self.grpc_router = Some(grpc_router);
    }

    /// Register a reverse proxy that forwards requests under `prefix` to `backend`.
    ///
    /// The prefix is stripped from the request path before forwarding.
    /// All HTTP methods are handled. The full upstream response is buffered,
    /// so middleware can inspect and modify the response body.
    /// On backend failure, returns 502.
    pub fn proxy(&mut self, prefix: &str, backend: &str) {
        self.insert_proxy_routes(prefix, backend, None, false);
    }

    /// Register a health-checked reverse proxy.
    ///
    /// Behaves like `proxy()` but checks the `healthy` flag before forwarding.
    /// When `healthy` is `false`, returns 503 immediately.
    pub fn proxy_checked(&mut self, prefix: &str, backend: &str, healthy: Arc<AtomicBool>) {
        self.insert_proxy_routes(prefix, backend, Some(healthy), false);
    }

    /// Register a streaming reverse proxy under `prefix`.
    ///
    /// Like `proxy()`, but the upstream response body is forwarded chunk-by-chunk
    /// with backpressure instead of being buffered in memory. Middleware acts as
    /// a request gate only — it can reject before the upstream call, but does not
    /// wrap the streamed response.
    pub fn proxy_stream(&mut self, prefix: &str, backend: &str) {
        self.insert_proxy_routes(prefix, backend, None, true);
    }

    /// Register a health-checked streaming reverse proxy.
    ///
    /// Behaves like `proxy_stream()` but checks the `healthy` flag before forwarding.
    /// When `healthy` is `false`, returns 503 immediately.
    pub fn proxy_checked_stream(&mut self, prefix: &str, backend: &str, healthy: Arc<AtomicBool>) {
        self.insert_proxy_routes(prefix, backend, Some(healthy), true);
    }

    fn insert_proxy_routes(
        &mut self,
        prefix: &str,
        backend: &str,
        healthy: Option<Arc<AtomicBool>>,
        streaming: bool,
    ) {
        let backend: Arc<str> = backend.into();
        let prefix_owned: Arc<str> = prefix.into();
        let wildcard_pattern = format!("{prefix}/*proxy_path");
        let exact_pattern = match prefix.is_empty() {
            true => "/".to_owned(),
            false => prefix.to_owned(),
        };

        let methods = [
            Method::Get,
            Method::Post,
            Method::Put,
            Method::Delete,
            Method::Patch,
            Method::Head,
            Method::Options,
        ];
        for method in methods {
            for pattern in [wildcard_pattern.as_str(), exact_pattern.as_str()] {
                let handler = proxy_route_handler(
                    streaming,
                    Arc::clone(&backend),
                    Arc::clone(&prefix_owned),
                    healthy.as_ref().map(Arc::clone),
                );
                self.root.insert_route(method, pattern, handler);
            }
        }
    }

    /// Serve static files from `dir` under the given URL `prefix`.
    pub fn static_files(&mut self, prefix: &str, dir: &str) {
        let exact_base_dir: Box<std::path::Path> = std::path::PathBuf::from(dir).into_boxed_path();
        let wildcard_base_dir: Box<std::path::Path> =
            std::path::PathBuf::from(dir).into_boxed_path();
        let wildcard_pattern = format!("{prefix}/*filepath");
        let exact_pattern = match prefix.is_empty() {
            true => "/".to_owned(),
            false => prefix.to_owned(),
        };
        self.root.insert_route(
            Method::Get,
            &exact_pattern,
            RouteHandler::Async(Box::new(move |_req: &Request| {
                let resp = super::static_files::serve_file(&exact_base_dir, "index.html");
                Box::pin(async move { resp }) as Pin<Box<dyn Future<Output = Response> + Send>>
            })),
        );
        self.root.insert_route(
            Method::Get,
            &wildcard_pattern,
            RouteHandler::Async(Box::new(move |req: &Request| {
                let file_path = req.param("filepath").unwrap_or("");
                let resp = super::static_files::serve_file(&wildcard_base_dir, file_path);
                Box::pin(async move { resp }) as Pin<Box<dyn Future<Output = Response> + Send>>
            })),
        );
    }

    fn add<F, Fut, R>(&mut self, method: Method, path: &str, handler: F)
    where
        F: Fn(&Request) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = R> + Send + 'static,
        R: IntoResponse + 'static,
    {
        self.root.insert_route(
            method,
            path,
            RouteHandler::Async(Box::new(move |req: &Request| {
                let fut = handler(req);
                Box::pin(async move { fut.await.into_response() })
                    as Pin<Box<dyn Future<Output = Response> + Send>>
            })),
        );
    }

    fn add_stream(
        &mut self,
        method: Method,
        path: &str,
        handler: impl Fn(&Request) -> Pin<Box<dyn Future<Output = StreamResponse> + Send>>
        + Send
        + Sync
        + 'static,
    ) {
        self.root
            .insert_route(method, path, RouteHandler::Stream(Box::new(handler)));
    }

    /// Freeze routes into an immutable trie for serving.
    pub(super) fn freeze(self) -> FrozenRouter {
        FrozenRouter {
            root: self.root.freeze(),
            middleware: self.middleware.into_boxed_slice(),
            skip_middleware_for_internal: self.skip_middleware_for_internal,
            #[cfg(feature = "grpc")]
            grpc_router: self.grpc_router,
        }
    }
}

fn proxy_route_handler(
    streaming: bool,
    backend: Arc<str>,
    prefix: Arc<str>,
    healthy: Option<Arc<std::sync::atomic::AtomicBool>>,
) -> RouteHandler {
    match streaming {
        true => RouteHandler::ProxyStream {
            backend,
            prefix,
            healthy,
        },
        false => RouteHandler::Proxy {
            backend,
            prefix,
            healthy,
        },
    }
}