lxy 0.1.1

A convenient async http and RPC framework in Rust
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
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
use std::{convert::Infallible, sync::Arc};

use axum::{
  Router as AxumRouter,
  extract::Request,
  handler::Handler,
  response::IntoResponse,
  routing::{self, MethodRouter, Route},
};
use tower_layer::Layer;
use tower_service::Service;

/// A boxed layer that can transform MethodRouter -> MethodRouter.
type BoxedLayer = Arc<dyn Fn(MethodRouter) -> MethodRouter + Send + Sync>;

/// Stack frame for tracking current prefix and middlewares.
#[derive(Clone, Default)]
struct StackFrame {
  /// Current path prefix (accumulated).
  prefix: String,
  /// Stacked layers in FIFO order (first added will be applied first).
  layers: Vec<BoxedLayer>,
}

/// Router with prefix and layer management.
///
/// This is a wrapper around [axum::Router] that provides a more flexible way to manage
/// route prefixes, groups and middlewares(layers).
///
/// The key difference from [axum::Router] is that [tower_layer::Layer] (also called middleware)
/// are applied in the order they are added (FIFO). This behavior is opposite to axum's default LIFO order.
///
/// # Overview
///
/// You can chainly add routes with `get`, `post`, etc. methods. [Router::prefix] is provided as a convenient way to add a common prefix to routes.
/// [Router::group] allows you to create a sandboxed group of routes with their own scoped prefixes and middlewares.
///
/// ```
/// use lxy::http::Router;
/// let mut router = Router::new();
///
/// router
///   // GET /
///   .get("/", async || {})
///   // POST /login
///   .post("/login", async || {});
///
/// // Parse URL parameters from path
/// // GET /users/123
/// router.get("/users/{id}", async || { });
///
/// // Add prefix to all following routes
/// // Any routes added after will have '/api' prefix,
/// // even if they are wrapped in a [Router::group].
/// router.prefix("/api");
///
/// // GET /api/info
/// router.get("/info", async || {});
///
/// // following prefixes will be concatenated
/// router.prefix("/v1");
///
/// // GET /api/v1/users
/// router.get("/users", async || {});
/// ```
///
/// # Layers (Middlewares)
///
/// You can add [tower_layer::Layer] (also called middleware) to the routers.
///
/// ```
/// use lxy::http::Router;
/// let mut router = Router::new();
///
/// // GET /, No layer will be applied
/// router.get("/", async || {});
///
/// // Add first layer to following routes
/// router.layer(tower_layer::layer_fn(|svc| {
///   println!("called first");
///   svc
/// }));
///
/// // GET /a, will go through first layer
/// router.get("/a", async || {});
///
/// // You can also use the alias `middleware` to add a layer
/// router.middleware(tower_layer::layer_fn(|svc| {
///   println!("called second");
///   svc
/// }));
///
/// // GET /b, will go through first and second layers
/// router.get("/b", async || {});
/// ```
///
/// # Groups
///
/// Create a group with sandboxed prefixes or [layers(middlewares)][tower_layer::Layer]. After
/// the group ends, the previous prefixes and layers are restored.
/// The following routers won't be affected by anything set in the group.
///
/// This is a common pattern to add a controller based routes.
///
/// ```
/// use lxy::http::Router;
/// let mut router = Router::new();
///
/// router.group(|r| {
///   r.middleware(tower_layer::layer_fn(|svc| {
///     println!("called in group");
///     svc
///   }))
///   .prefix("/api")
///   .group(|r| {
///     r.prefix("/users");
///     // GET /api/users
///     r.get("/", async || {});
///     // POST /api/users
///     r.post("/", async || {});
///     // GET /api/users/1
///     r.get("/{id}", async || {});
///   });
/// });
///
/// // Following routes won't be affected by the ended groups
/// // GET /health
/// router.get("/health", async || {});
/// ```
///
/// # Extractors
///
/// Since this router wraps [axum::Router], all axum extractors work out of the box:
///
/// ```
/// use lxy::http::Router;
/// use axum::extract::{Path, Query};
/// use serde::Deserialize;
///
/// #[derive(Deserialize)]
/// struct Pagination {
///     page: Option<u32>,
///     limit: Option<u32>,
/// }
///
/// let mut router = Router::new();
///
/// // Path parameters are automatically extracted
/// router.get("/users/{id}", |Path(id): Path<u32>| async move {
///     format!("User ID: {}", id)
/// });
///
/// // Query parameters work too
/// router.get("/search", |Query(pagination): Query<Pagination>| async move {
///     format!("Page: {}, Limit: {}",
///         pagination.page.unwrap_or(1),
///         pagination.limit.unwrap_or(10))
/// });
/// ```
#[derive(Default)]
pub struct Router {
  /// The underlying axum router.
  inner: AxumRouter,
  /// Current stack frame (prefix + layers).
  stack: StackFrame,
}

// HTTP method helpers using macro
macro_rules! impl_http_methods {
    ([$($method:ident),*]) => {
        $(
            #[doc = concat!("Registers a `", stringify!($method), "` route.")]
            pub fn $method<H, T>(&mut self, path: &str, handler: H) -> &mut Self
            where
                H: Handler<T, ()>,
                T: 'static,
            {
                self.add_route(path, routing::$method(handler))
            }
        )*
    };
}

impl Router {
  /// Creates a new empty router.
  pub fn new() -> Self {
    Self::default()
  }

  impl_http_methods!([get, post, put, delete, patch, head, options, trace, connect]);

  /// Adds a prefix to following routes.
  ///
  /// Prefixes are accumulated: multiple `prefix` calls will concatenate paths.
  /// Use [Router::group] to scope the prefix.
  ///
  /// ```
  /// use lxy::http::Router;
  /// let mut router = Router::new();
  ///
  /// router.group(|r| {
  ///   r.prefix("/api")
  ///    .prefix("/v1")
  ///    // GET /api/v1/users
  ///    .get("/users", async || {});
  /// });
  ///
  /// // GET /health (prefix is scoped to group)
  /// router.get("/health", async || {});
  /// ```
  pub fn prefix(&mut self, prefix: &str) -> &mut Self {
    self.stack.prefix = join_paths(&self.stack.prefix, prefix);
    self
  }

  /// Creates a group that inherits current prefix and middlewares.
  ///
  /// Middlewares and prefixes added within the group only apply to routes in that group.
  ///
  /// ```
  /// use lxy::http::Router;
  /// let mut router = Router::new();
  ///
  /// router.group(|r| {
  ///   r.prefix("/api")
  ///    .middleware(tower_layer::layer_fn(|svc| svc))
  ///    // GET /api/protected with middleware
  ///    .get("/protected", async || {});
  /// });
  ///
  /// // GET /public without prefix or middleware
  /// router.get("/public", async || {});
  /// ```
  pub fn group<F>(&mut self, f: F) -> &mut Self
  where
    F: FnOnce(&mut Self),
  {
    let previous_stack = self.stack.clone();
    f(self);
    self.stack = previous_stack;
    self
  }

  /// Adds a [tower_layer::Layer](middleware) to following routes.
  ///
  /// This is an alias to [Router::layer].
  pub fn middleware<L>(&mut self, layer: L) -> &mut Self
  where
    L: Layer<Route> + Clone + Send + Sync + 'static,
    L::Service: Service<Request> + Clone + Send + Sync + 'static,
    <L::Service as Service<Request>>::Response: IntoResponse + 'static,
    <L::Service as Service<Request>>::Error: Into<Infallible> + 'static,
    <L::Service as Service<Request>>::Future: Send + 'static,
  {
    self.layer(layer)
  }

  /// Adds a [tower_layer::Layer](middleware) to following registered routes.
  ///
  /// Layers(Middlewares) are applied in adding order (FIFO),
  /// which means the [axum::extract::Request] will come through first registered middleware first,
  /// and the [axum::response::Response] will go through last registered middleware first.
  ///
  /// ```
  /// use lxy::http::Router;
  /// let mut router = Router::new();
  ///
  /// // The entering order of middleware is first -> second
  /// router
  ///   .layer(tower_layer::layer_fn(|svc| {
  ///     println!("first");
  ///     svc
  ///   }))
  ///   .layer(tower_layer::layer_fn(|svc| {
  ///     println!("second");
  ///     svc
  ///   }))
  ///   .get("/users", async || {});
  /// ```
  pub fn layer<L>(&mut self, layer: L) -> &mut Self
  where
    L: Layer<Route> + Clone + Send + Sync + 'static,
    L::Service: Service<Request> + Clone + Send + Sync + 'static,
    <L::Service as Service<Request>>::Response: IntoResponse + 'static,
    <L::Service as Service<Request>>::Error: Into<Infallible> + 'static,
    <L::Service as Service<Request>>::Future: Send + 'static,
  {
    let layer_fn = move |route: MethodRouter| route.layer(layer.clone());
    self.stack.layers.push(Arc::new(layer_fn));
    self
  }

  /// Builds the router into a service that can handle requests.
  ///
  /// This consumes the router and returns the underlying axum::Router.
  pub(crate) fn build(self) -> AxumRouter {
    self.inner
  }

  /// Registers a route with a method router.
  fn add_route(&mut self, path: &str, method_router: MethodRouter) -> &mut Self {
    let full_path = join_paths(&self.stack.prefix, path);

    // Apply layers in REVERSE order to achieve FIFO execution
    // User adds: [L1, L2, L3] (FIFO order)
    // We apply: method_router.layer(L3).layer(L2).layer(L1)
    // Axum's LIFO means request flows: L1 -> L2 -> L3
    let method_router_with_layers = self
      .stack
      .layers
      .iter()
      .rev()
      .fold(method_router, |router, layer| layer(router));

    // Merge into axum::Router (clone is cheap due to Arc internally)
    self.inner = self
      .inner
      .clone()
      .route(&full_path, method_router_with_layers);

    self
  }
}

/// Helper function to join two path segments.
fn join_paths(prefix: &str, path: &str) -> String {
  match (prefix.is_empty(), path) {
    (true, _) => path.to_string(),
    (false, "/") => prefix.to_string(),
    (false, _) => {
      let prefix = prefix.trim_end_matches('/');
      let path = path.trim_start_matches('/');
      format!("{}/{}", prefix, path)
    }
  }
}

#[cfg(test)]
impl Router {
  pub(crate) fn compose<F: FnMut(&mut Router)>(mut composer: F) -> Router {
    let mut router = Self::new();
    composer(&mut router);
    router
  }
}

#[cfg(test)]
mod tests {
  use super::*;
  use std::{
    pin::Pin,
    sync::{Arc, Mutex},
  };
  use tower_layer::layer_fn;

  #[test]
  fn test_join_paths() {
    assert_eq!(join_paths("", "/users"), "/users");
    assert_eq!(join_paths("/api", "/users"), "/api/users");
    assert_eq!(join_paths("/api/", "/users"), "/api/users");
    assert_eq!(join_paths("/api", "users"), "/api/users");
    assert_eq!(join_paths("/api/", "users"), "/api/users");
    assert_eq!(join_paths("/api", "/"), "/api");
    assert_eq!(join_paths("/api/v1", "/users"), "/api/v1/users");
  }

  #[derive(Clone)]
  struct LogLayer {
    name: &'static str,
    logs: Arc<Mutex<Vec<String>>>,
  }

  impl<S> Layer<S> for LogLayer {
    type Service = LogService<S>;

    fn layer(&self, inner: S) -> Self::Service {
      LogService {
        inner,
        name: self.name,
        logs: self.logs.clone(),
      }
    }
  }

  #[derive(Clone)]
  struct LogService<S> {
    inner: S,
    name: &'static str,
    logs: Arc<Mutex<Vec<String>>>,
  }

  impl<S, Request> Service<Request> for LogService<S>
  where
    S: Service<Request> + Clone + Send + 'static,
    S::Future: Send,
    Request: Send + 'static,
  {
    type Response = S::Response;
    type Error = S::Error;
    type Future =
      Pin<Box<dyn std::future::Future<Output = Result<Self::Response, Self::Error>> + Send>>;

    fn poll_ready(
      &mut self,
      cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Result<(), Self::Error>> {
      self.inner.poll_ready(cx)
    }

    fn call(&mut self, req: Request) -> Self::Future {
      let log = self.logs.clone();
      let name = self.name;
      let inner = self.inner.clone();
      let mut inner = std::mem::replace(&mut self.inner, inner);

      log.lock().unwrap().push(format!("{}_before", name));

      Box::pin(async move {
        let result = inner.call(req).await;
        log.lock().unwrap().push(format!("{}_after", name));
        result
      })
    }
  }

  #[tokio::test]
  async fn test_middleware_execution_order() {
    use http::Request as HttpRequest;

    let log = Arc::new(Mutex::new(Vec::new()));

    let mut router = Router::new();

    // Add middlewares: A, B, C
    // Expected execution order: A_before -> B_before -> C_before -> handler ->  C_after -> B_after -> A_after
    router
      .middleware(LogLayer {
        name: "A",
        logs: log.clone(),
      })
      .middleware(LogLayer {
        name: "B",
        logs: log.clone(),
      })
      .middleware(LogLayer {
        name: "C",
        logs: log.clone(),
      })
      .get("/test", || async { "OK" });

    let mut service = router.build();

    // Make a request
    let req = HttpRequest::builder()
      .uri("/test")
      .body(axum::body::Body::empty())
      .unwrap();

    let _response = service.call(req).await.unwrap();

    let recorded = log.lock().unwrap().clone();

    // Verify the order: A(B(C(handler))) means:
    // - A starts first (outermost)
    // - B starts second
    // - C starts third (innermost)
    // - handler executes
    // - C completes first
    // - B completes second
    // - A completes last
    assert_eq!(
      recorded,
      vec![
        "A_before", "B_before", "C_before", "C_after", "B_after", "A_after",
      ]
    );
  }

  #[tokio::test]
  async fn test_group_middleware_isolation() {
    use http::Request as HttpRequest;

    let log = Arc::new(Mutex::new(Vec::new()));

    let mut router = Router::new();

    // Global middleware
    router.middleware(LogLayer {
      name: "Global",
      logs: log.clone(),
    });

    // Group with additional middleware
    router.group(|r| {
      r.middleware(LogLayer {
        name: "GroupOnly",
        logs: log.clone(),
      })
      .get("/grouped", || async { "grouped" });
    });

    // Route outside group should NOT have GroupOnly middleware
    router.get("/outside", || async { "outside" });

    let mut service = router.build();

    // Test grouped route
    log.lock().unwrap().clear();
    let req = HttpRequest::builder()
      .uri("/grouped")
      .body(axum::body::Body::empty())
      .unwrap();
    let _response = service.call(req).await.unwrap();

    let recorded = log.lock().unwrap().clone();
    assert_eq!(
      recorded,
      vec![
        "Global_before",
        "GroupOnly_before",
        "GroupOnly_after",
        "Global_after",
      ]
    );

    // Test outside route - should only have Global middleware
    log.lock().unwrap().clear();
    let req = HttpRequest::builder()
      .uri("/outside")
      .body(axum::body::Body::empty())
      .unwrap();
    let _response = service.call(req).await.unwrap();

    let recorded = log.lock().unwrap().clone();
    assert_eq!(recorded, vec!["Global_before", "Global_after",]);
  }

  #[tokio::test]
  async fn test_prefix_accumulation() {
    use http::StatusCode;

    let mut router = Router::new();
    router.middleware(layer_fn(|svc| {
      println!("Request received");
      svc
    }));

    router.group(|r| {
      r.prefix("/api")
        .prefix("/v1")
        .get("/users", || async { "users" });
    });

    // Verify the route was registered at /api/v1/users
    let mut service = router.build();

    let req = http::Request::builder()
      .uri("/api/v1/users")
      .body(axum::body::Body::empty())
      .unwrap();

    let response = service.call(req).await.unwrap();
    assert_eq!(response.status(), StatusCode::OK);

    // /api/users should 404
    let req = http::Request::builder()
      .uri("/api/users")
      .body(axum::body::Body::empty())
      .unwrap();

    let response = service.call(req).await.unwrap();
    assert_eq!(response.status(), StatusCode::NOT_FOUND);
  }

  #[tokio::test]
  async fn test_path_parameters() {
    use axum::extract::Path;
    use http::{Request as HttpRequest, StatusCode};

    let mut router = Router::new();

    router.get("/users/{id}", |Path(id): Path<u32>| async move {
      format!("User ID: {}", id)
    });

    let mut service = router.build();

    let req = HttpRequest::builder()
      .uri("/users/123")
      .body(axum::body::Body::empty())
      .unwrap();

    let response = service.call(req).await.unwrap();
    assert_eq!(response.status(), StatusCode::OK);

    let body = axum::body::to_bytes(response.into_body(), usize::MAX)
      .await
      .unwrap();
    assert_eq!(body, "User ID: 123");
  }

  #[tokio::test]
  async fn test_query_parameters() {
    use axum::extract::Query;
    use http::{Request as HttpRequest, StatusCode};
    use serde::Deserialize;

    #[derive(Deserialize)]
    struct Pagination {
      page: Option<u32>,
      limit: Option<u32>,
    }

    let mut router = Router::new();

    router.get(
      "/search",
      |Query(pagination): Query<Pagination>| async move {
        format!(
          "Page: {}, Limit: {}",
          pagination.page.unwrap_or(1),
          pagination.limit.unwrap_or(10)
        )
      },
    );

    let mut service = router.build();

    let req = HttpRequest::builder()
      .uri("/search?page=2&limit=20")
      .body(axum::body::Body::empty())
      .unwrap();

    let response = service.call(req).await.unwrap();
    assert_eq!(response.status(), StatusCode::OK);

    let body = axum::body::to_bytes(response.into_body(), usize::MAX)
      .await
      .unwrap();
    assert_eq!(body, "Page: 2, Limit: 20");
  }
}