lariv-rs 0.1.0

Compile-time plugin web application framework built on Axum, SeaORM, Maud, and HTMX
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
//! Typed HTTP routing capability for Lariv apps.
//!
//! Mounts compile-time route HLists onto axum, publishes capability values into request
//! extensions, and wires HTMX middleware. Route identity tags live in [`route_tag`].
//!
//! # Routes
//!
//! Register handlers with [`Route::get`], [`Route::post`], and sibling helpers. Prepend
//! tagged routes onto [`crate::http::HttpCapability`] (usually via plugin [`RouteRegistrar`] hooks).
//! At runtime [`into_axum_router`] folds the mounted route list into an axum [`Router`].
//!
//! # Use cases
//!
//! - Bootstrap an app with [`with_http`] before plugins append routes.
//! - Extract mounted plugin state in handlers via [`Cap`] (reads request extensions).
//! - Build the production router with capability injection and HTMX redirect rewriting.
//!
//! # Examples
//!
//! ```rust
//! # use lariv_rs::http::with_http;
//! # use lariv_rs::app::App;
//! let _app = with_http(App::new());
//! ```
//!
//! ```rust ignore
//! // Handler extracting a database pool published from the mounted App HList.
//! async fn list_users(Cap(db): Cap<Arc<DbPool>>) -> impl IntoResponse { /* ... */ }
//! ```

use std::sync::Arc;

use axum::{
    Router,
    body::Body,
    extract::{DefaultBodyLimit, Request},
    handler::Handler,
    http::Extensions,
    middleware::{self, Next},
    routing::{MethodRouter, delete, get, head, options, patch, post, put, trace},
};
use frunk::{HCons, HNil, hlist::HList};

use crate::{
    app::{App, MountedApp},
    capability::{CapStore, Capability},
    components::slots::{SharedChromeFolder, SlotTag},
    tag::Tagged,
    traits::{
        add::{AddCapability, CapTagAbsent},
        get::GetByTag,
    },
};

/// Request body cap for extractors such as [`axum::extract::Multipart`].
///
/// Axum defaults to 2 MiB, which truncates XLSX imports and file uploads mid-parse.
pub const REQUEST_BODY_LIMIT_BYTES: usize = 50 * 1024 * 1024;

pub mod route_tag;

pub use route_tag::{
    AppPaneGet, AppPanePost, BoostPost, FileDownloadGet, FileDownloadPost, FkSelectGet,
    FragmentGet, FragmentPost, GenerationPost, ModalGet, RouteQueryBuilder, RouteTag, RouteUrl,
    nav_url, trailing_slash,
};

/// Capability tag identifying the HTTP router on the app HList.
///
/// Used with [`GetByTag`] to retrieve
/// [`crate::http::HttpCapability`] after mount.
pub struct HttpTag;

/// HTTP method marker stored on a [`Route`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Method {
    Get,
    Post,
    Put,
    Delete,
    Patch,
    Head,
    Options,
    Trace,
}

/// A single axum route entry in the HTTP capability's compile-time HList.
///
/// Created via [`Route::get`], [`Route::post`], etc. Paths are normalized (trailing
/// slash stripped except for root).
#[derive(Clone)]
pub struct Route {
    pub path: String,
    pub method: Method,
    method_router: MethodRouter<()>,
}

impl Route {
    fn new(path: impl Into<String>, method: Method, method_router: MethodRouter<()>) -> Self {
        Self {
            path: normalize_route_path(path),
            method,
            method_router,
        }
    }

    /// Register a GET handler at `path`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use lariv_rs::http::Route;
    /// async fn list_users() {}
    /// let _route = Route::get("/users/", list_users);
    /// ```
    pub fn get<H, T>(path: impl Into<String>, handler: H) -> Self
    where
        H: Handler<T, ()>,
        T: 'static,
    {
        Self::new(path, Method::Get, get(handler))
    }

    /// Register a POST handler at `path`.
    ///
    /// # Use cases
    ///
    /// - Form submissions (create/update/delete) that swap HTMX regions.
    /// - Non-idempotent actions (logout, generation triggers).
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use lariv_rs::http::Route;
    /// async fn create_user() {}
    /// let _route = Route::post("/users/create", create_user);
    /// ```
    pub fn post<H, T>(path: impl Into<String>, handler: H) -> Self
    where
        H: Handler<T, ()>,
        T: 'static,
    {
        Self::new(path, Method::Post, post(handler))
    }

    /// Register a PUT handler at `path`.
    pub fn put<H, T>(path: impl Into<String>, handler: H) -> Self
    where
        H: Handler<T, ()>,
        T: 'static,
    {
        Self::new(path, Method::Put, put(handler))
    }

    /// Register a DELETE handler at `path`.
    pub fn delete<H, T>(path: impl Into<String>, handler: H) -> Self
    where
        H: Handler<T, ()>,
        T: 'static,
    {
        Self::new(path, Method::Delete, delete(handler))
    }

    /// Register a PATCH handler at `path`.
    pub fn patch<H, T>(path: impl Into<String>, handler: H) -> Self
    where
        H: Handler<T, ()>,
        T: 'static,
    {
        Self::new(path, Method::Patch, patch(handler))
    }

    /// Register a HEAD handler at `path`.
    pub fn head<H, T>(path: impl Into<String>, handler: H) -> Self
    where
        H: Handler<T, ()>,
        T: 'static,
    {
        Self::new(path, Method::Head, head(handler))
    }

    /// Register an OPTIONS handler at `path`.
    pub fn options<H, T>(path: impl Into<String>, handler: H) -> Self
    where
        H: Handler<T, ()>,
        T: 'static,
    {
        Self::new(path, Method::Options, options(handler))
    }

    /// Register a TRACE handler at `path`.
    pub fn trace<H, T>(path: impl Into<String>, handler: H) -> Self
    where
        H: Handler<T, ()>,
        T: 'static,
    {
        Self::new(path, Method::Trace, trace(handler))
    }
}

fn normalize_route_path(path: impl Into<String>) -> String {
    let path = path.into();
    if path.len() > 1 && path.ends_with('/') {
        path.trim_end_matches('/').to_owned()
    } else {
        path
    }
}

/// Plugin hook for appending routes onto an [`crate::http::HttpCapability`].
pub trait RouteRegistrar<Http, Proof = ()>: Sized {
    type Output;
    fn register_routes(self, http: Http) -> Self::Output;
}

/// Apply queued route hooks (tail first so install order is preserved).
pub trait FoldMountRoutes<Http, Proof = ()>: Sized {
    type Output;
    fn fold_mount_routes(self, http: Http) -> Self::Output;
}

impl<Http> FoldMountRoutes<Http> for HNil {
    type Output = Http;

    fn fold_mount_routes(self, http: Http) -> Self::Output {
        http
    }
}

impl<Plugin, Hook, Tail, Http, TailProof, Proof> FoldMountRoutes<Http, (TailProof, Proof)>
    for HCons<Tagged<Plugin, Hook>, Tail>
where
    Tail: FoldMountRoutes<Http, TailProof>,
    Hook: RouteRegistrar<Tail::Output, Proof>,
{
    type Output = <Hook as RouteRegistrar<Tail::Output, Proof>>::Output;

    fn fold_mount_routes(self, http: Http) -> Self::Output {
        let http = self.tail.fold_mount_routes(http);
        self.head.value.register_routes(http)
    }
}

/// Fold a routes HList into an axum [`Router`].
pub trait MountRoutes {
    fn mount_routes(self, router: Router<()>) -> Router<()>;
}

/// Collect route entries from a compile-time HList (head-first order).
trait PushRoutes {
    fn push_routes(self, routes: &mut Vec<Route>);
}

impl PushRoutes for HNil {
    fn push_routes(self, _routes: &mut Vec<Route>) {}
}

impl<Tag, Tail> PushRoutes for HCons<Tagged<Tag, Route>, Tail>
where
    Tail: PushRoutes,
{
    fn push_routes(self, routes: &mut Vec<Route>) {
        routes.push(self.head.value);
        self.tail.push_routes(routes);
    }
}

impl<Routes> MountRoutes for Routes
where
    Routes: PushRoutes,
{
    fn mount_routes(self, mut router: Router<()>) -> Router<()> {
        let mut routes = Vec::new();
        self.push_routes(&mut routes);
        // Later-installed plugins prepend onto the HList, so they appear first
        // here. Keep the first (path, method) and drop earlier duplicates so a
        // later plugin can override (e.g. website owning `/` over dashboard).
        let mut kept = Vec::with_capacity(routes.len());
        for route in routes {
            if kept
                .iter()
                .any(|r: &Route| r.path == route.path && r.method == route.method)
            {
                continue;
            }
            kept.push(route);
        }
        for route in kept {
            router = router.route(&route.path, route.method_router);
        }
        router
    }
}

/// Publish each mounted capability value into request [`Extensions`].
pub trait ProvideRequestCaps {
    fn provide_request_caps(&self, extensions: &mut Extensions);
}

impl ProvideRequestCaps for HNil {
    fn provide_request_caps(&self, _: &mut Extensions) {}
}

impl<Tag, V, Tail> ProvideRequestCaps for HCons<Tagged<Tag, V>, Tail>
where
    V: Clone + Send + Sync + 'static,
    Tail: ProvideRequestCaps,
{
    fn provide_request_caps(&self, extensions: &mut Extensions) {
        extensions.insert(self.head.value.clone());
        self.tail.provide_request_caps(extensions);
    }
}

/// Axum extractor for a capability value published from the mounted App HList.
///
/// Each request receives clones of mounted capability values via middleware in
/// [`into_axum_router`]. Missing values yield `500`.
///
/// # Use cases
///
/// - Inject database pools, config, or plugin state into handlers without global state.
///
/// # Examples
///
/// ```rust ignore
/// async fn handler(Cap(pool): Cap<Arc<DbPool>>) -> impl IntoResponse {
///     // use pool...
/// }
/// ```
pub struct Cap<T>(pub T);

impl<S, T> axum::extract::FromRequestParts<S> for Cap<T>
where
    T: Clone + Send + Sync + 'static,
    S: Send + Sync,
{
    type Rejection = (axum::http::StatusCode, &'static str);

    async fn from_request_parts(
        parts: &mut axum::http::request::Parts,
        _state: &S,
    ) -> Result<Self, Self::Rejection> {
        parts.extensions.get::<T>().cloned().map(Cap).ok_or((
            axum::http::StatusCode::INTERNAL_SERVER_ERROR,
            "missing capability in request extensions",
        ))
    }
}

/// Mounted HTTP capability holding a compile-time HList of tagged [`Route`] entries.
///
/// Builder plugins prepend routes; at mount time the list is wrapped in [`Arc`] so
/// per-request clones stay cheap.
#[derive(Clone)]
pub struct HttpCapability<Routes> {
    pub routes: Routes,
}

impl HttpCapability<HNil> {
    pub fn new() -> Self {
        Self { routes: HNil }
    }
}

impl Default for HttpCapability<HNil> {
    fn default() -> Self {
        Self::new()
    }
}

impl<Routes> HttpCapability<Routes> {
    pub fn prepend<Tag>(self, route: Route) -> HttpCapability<HCons<Tagged<Tag, Route>, Routes>>
    where
        Routes: HList,
    {
        HttpCapability {
            routes: HCons {
                head: Tagged::new(route),
                tail: self.routes,
            },
        }
    }

    pub fn get_route<Tag, Index>(&self) -> &Route
    where
        Routes: GetByTag<Tag, Index, Value = Route>,
    {
        self.routes.get_by_tag()
    }

    pub fn into_router(self) -> Router<()>
    where
        Routes: MountRoutes,
    {
        self.routes.mount_routes(Router::new())
    }
}

/// Builder-phase HTTP capability (`items` holds [`crate::http::HttpCapability`], `hooks` queues
/// deferred [`RouteRegistrar`] plugins).
pub type HttpCap<Hooks, Http> = CapStore<HttpTag, Hooks, Http>;

impl<Hooks, Routes> HttpCap<Hooks, HttpCapability<Routes>> {
    /// Apply route hooks, then clear the hook list.
    pub fn resolve_route_hooks<Proof>(
        self,
    ) -> HttpCap<HNil, <Hooks as FoldMountRoutes<HttpCapability<Routes>, Proof>>::Output>
    where
        Hooks: FoldMountRoutes<HttpCapability<Routes>, Proof>,
    {
        let http = self.hooks.fold_mount_routes(self.items);
        CapStore::with_items(http)
    }
}

impl<Http> Capability for HttpCap<HNil, Http> {
    /// Shared so request-extension / middleware clones do not deep-copy the route HList
    /// (recursive [`Clone`] of dozens of [`Route`]s overflows the default tokio stack).
    type Value = Arc<Http>;
    type Output = Tagged<HttpTag, Arc<Http>>;
    type Hooks = HNil;
    type Items = Http;

    fn mount(self) -> Self::Output {
        Tagged::new(Arc::new(self.items))
    }
}

/// Add an empty HTTP capability to `app` (call before plugins register routes).
///
/// # Examples
///
/// ```rust
/// # use lariv_rs::{app::App, http::with_http};
/// let app = with_http(App::new());
/// ```
pub fn with_http<L, Proof>(app: App<L>) -> App<HCons<HttpCap<HNil, HttpCapability<HNil>>, L>>
where
    L: HList + CapTagAbsent<HttpTag, Proof>,
{
    app.add_capability(CapStore::with_items(HttpCapability::new()))
}

/// Build the axum [`Router`] from a mounted app: fold routes, inject capability extensions,
/// apply HTMX middleware (redirect rewrite + `Vary`), and raise the request body limit
/// to [`REQUEST_BODY_LIMIT_BYTES`] so multipart uploads are not truncated at Axum's 2 MiB default.
///
/// # Use cases
///
/// - Final step in `main` after [`App::mount`](crate::app::App::mount).
/// - Serve the Lariv app with per-request access to all mounted capabilities.
pub fn into_axum_router<M, HttpIdx, Routes, SlotIdx>(app: &MountedApp<M>) -> Router
where
    M: GetByTag<HttpTag, HttpIdx, Value = Arc<HttpCapability<Routes>>>,
    M: GetByTag<SlotTag, SlotIdx, Value = SharedChromeFolder>,
    M: ProvideRequestCaps + Clone + Send + Sync + 'static,
    Routes: MountRoutes + Clone,
{
    // One deep clone of routes to hand ownership to axum; mounted value stays behind Arc.
    let router = app
        .get_capability_output::<HttpTag, HttpIdx>()
        .as_ref()
        .clone()
        .into_router();
    // Arc so each request only bumps a refcount instead of recursively cloning the cap HList.
    let caps = Arc::new(app.capabilities.clone());
    router
        .layer(middleware::from_fn(crate::web::htmx_middleware))
        .layer(middleware::from_fn(
            move |mut req: Request<Body>, next: Next| {
                let caps = Arc::clone(&caps);
                async move {
                    caps.provide_request_caps(req.extensions_mut());
                    next.run(req).await
                }
            },
        ))
        .layer(DefaultBodyLimit::max(REQUEST_BODY_LIMIT_BYTES))
}