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
//! CLI command registry capability — plugins register subcommands; clap builds and dispatches them.
//!
//! The command capability holds a compile-time HList of tagged [`RunCommand`] implementations.
//! At mount, plugin [`CommandRegistrar`] hooks prepend commands. Built-in migrate, seed, and
//! serve commands are included by [`with_commands`].
//!
//! # Lifecycle
//!
//! 1. Attach [`with_commands`] (or an empty capability and register manually).
//! 2. Plugins queue [`CommandRegistrar`] hooks during install.
//! 3. At mount, hooks fold over the command HList → [`CommandCapability`].
//! 4. [`CommandCapability::build_cli`] produces a clap root; [`DispatchCommands::dispatch`] routes argv.
//!
//! # Core types
//!
//! - [`CommandTag`] — capability tag
//! - [`CommandCapability`] — mounted HList of tagged commands
//! - [`CommandCap`] — builder-phase [`CapStore`]
//! - [`RunCommand`] — clap metadata + async runner for one subcommand
//! - [`CommandRegistrar`] — plugin hook trait
//! - [`BuildCli`] / [`DispatchCommands`] — fold traits for clap integration
//!
//! # Built-in commands
//!
//! - [`MigrateCommand`] — runs [`crate::migration::RunMigrations`]
//! - [`SeedCommand`] — runs [`crate::hooks::FoldSeeds`]
//! - [`ServeCommand`] — starts the HTTP server
//!
//! # Examples
//!
//! ```rust ignore
//! // Plugin command registration (implement CommandRegistrar manually or via macro):
//! impl<C> CommandRegistrar<C> for MyRegisterHook {
//!     type Output = impl HList;
//!     fn register_commands(self, cap: CommandCapability<C>) -> CommandCapability<Self::Output> {
//!         cap.prepend::<MyCmdTag, _>(MyCommand)
//!     }
//! }
//!
//! let app = with_commands(app);
//! ```

use clap::{ArgMatches, Args, Command as ClapCommand, FromArgMatches};
use frunk::{HCons, HNil, hlist::HList};

use crate::{
    app::{App, MountedApp},
    capability::{
        ApplyHooks, CapStore, Capability, FoldRegistrarHooks, apply_registrar_hook,
        mount_with_hooks,
    },
    components::SlotTag,
    config::{AppConfig, AppConfigTag, ConfigCapability, ConfigTag},
    db::{DbState, DbTag},
    hooks::{FoldSeeds, SeedRunner, SeedsTag},
    http::{HttpCapability, HttpTag, MountRoutes, ProvideRequestCaps},
    migration::{MigrationCapability, MigrationTag, RunMigrations, mark_migrations},
    tag::Tagged,
    traits::{
        add::{AddCapability, CapTagAbsent},
        get::GetByTag,
    },
};

/// Capability tag for the CLI command registry.
pub struct CommandTag;

/// Tag for the built-in [`MigrateCommand`].
pub struct MigrateCommandTag;

/// Tag for the built-in [`SeedCommand`].
pub struct SeedCommandTag;

/// Tag for the built-in [`MarkMigrationsCommand`].
pub struct MarkMigrationsCommandTag;

/// Tag for the built-in [`ServeCommand`].
pub struct ServeCommandTag;

/// Plugin hook for appending commands onto a [`CommandCapability`].
pub trait CommandRegistrar<C>: Sized {
    type Output;
    fn register_commands(self, cap: CommandCapability<C>) -> CommandCapability<Self::Output>;
}

/// Registered CLI subcommand: clap metadata + async runner.
///
/// Implement on a zero-sized or cloneable type; clap args are a separate [`Args`] struct.
///
/// # Examples
///
/// ```rust ignore
/// #[derive(Args, Clone, Default)]
/// struct MyArgs { #[arg(long)] verbose: bool }
///
/// struct MyCommand;
///
/// #[async_trait]
/// impl<M> RunCommand<M> for MyCommand {
///     type Args = MyArgs;
///     const NAME: &'static str = "my-cmd";
///     const ABOUT: &'static str = "Do something useful";
///     async fn run(args: Self::Args, app: MountedApp<M>) -> anyhow::Result<()> {
///         Ok(())
///     }
/// }
/// ```
#[async_trait::async_trait]
pub trait RunCommand<M, Proof = ()>: Sized {
    type Args: Args + FromArgMatches + Clone + Send;

    const NAME: &'static str;
    const ABOUT: &'static str;

    async fn run(args: Self::Args, app: MountedApp<M>) -> anyhow::Result<()>;
}

/// Fold command HList into a clap [`ClapCommand`] (tail first = registration order).
pub trait BuildCli<M, Proof = ()> {
    fn augment_cli(cmd: ClapCommand) -> ClapCommand;
}

impl<M> BuildCli<M> for HNil {
    fn augment_cli(cmd: ClapCommand) -> ClapCommand {
        cmd
    }
}

impl<Tag, C, Tail, M, TailProof, Proof> BuildCli<M, (TailProof, Proof)>
    for HCons<Tagged<Tag, C>, Tail>
where
    C: RunCommand<M, Proof>,
    Tail: BuildCli<M, TailProof>,
{
    fn augment_cli(cmd: ClapCommand) -> ClapCommand {
        let cmd = Tail::augment_cli(cmd);
        let sub = C::Args::augment_args(ClapCommand::new(C::NAME).about(C::ABOUT));
        cmd.subcommand(sub)
    }
}

/// Dispatch argv to a registered command's [`RunCommand::run`].
#[async_trait::async_trait]
pub trait DispatchCommands<M, Proof = ()>: Sized {
    async fn dispatch(
        self,
        name: &str,
        matches: &ArgMatches,
        app: MountedApp<M>,
    ) -> anyhow::Result<()>;
}

#[async_trait::async_trait]
impl<M> DispatchCommands<M> for HNil
where
    M: Send + 'static,
{
    async fn dispatch(self, name: &str, _: &ArgMatches, _: MountedApp<M>) -> anyhow::Result<()> {
        anyhow::bail!("unknown command: {name}")
    }
}

#[async_trait::async_trait]
impl<Tag, C, Tail, M, TailProof, Proof> DispatchCommands<M, (TailProof, Proof)>
    for HCons<Tagged<Tag, C>, Tail>
where
    Tag: Send + Sync + 'static,
    C: RunCommand<M, Proof> + Send + Sync,
    Tail: DispatchCommands<M, TailProof> + Send,
    M: Send + 'static,
{
    async fn dispatch(
        self,
        name: &str,
        matches: &ArgMatches,
        app: MountedApp<M>,
    ) -> anyhow::Result<()> {
        if name == C::NAME {
            let args = C::Args::from_arg_matches(matches)?;
            <C as RunCommand<M, Proof>>::run(args, app).await
        } else {
            self.tail.dispatch(name, matches, app).await
        }
    }
}

/// Mounted CLI command capability.
#[derive(Clone)]
pub struct CommandCapability<Cmds> {
    pub commands: Cmds,
}

impl CommandCapability<HNil> {
    /// Empty command list (starting point for [`CommandRegistrar`] hooks).
    pub fn new() -> Self {
        Self { commands: HNil }
    }
}

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

impl<Cmds> CommandCapability<Cmds> {
    /// Prepend a tagged command (head of the HList = most recently registered).
    pub fn prepend<Tag, C>(self, command: C) -> CommandCapability<HCons<Tagged<Tag, C>, Cmds>>
    where
        Cmds: HList,
    {
        CommandCapability {
            commands: HCons {
                head: Tagged::new(command),
                tail: self.commands,
            },
        }
    }

    /// Build the root clap command (`lariv`) with all registered subcommands.
    pub fn build_cli<M, Proof>(&self) -> ClapCommand
    where
        Cmds: BuildCli<M, Proof>,
    {
        let cmd = ClapCommand::new("lariv")
            .subcommand_required(false)
            .arg_required_else_help(false);
        Cmds::augment_cli(cmd)
    }
}

/// Builder-phase command capability.
pub type CommandCap<Hooks, Items> = CapStore<CommandTag, Hooks, Items>;

impl<Hooks, Items> CommandCap<Hooks, Items> {
    /// Eagerly fold registrar hooks into items (testing / pre-mount inspection).
    pub fn resolve_hooks(
        self,
    ) -> CommandCap<HNil, <Hooks as FoldRegistrarHooks<CommandTag, Items>>::Output>
    where
        Hooks: FoldRegistrarHooks<CommandTag, Items>,
    {
        CapStore::with_items(self.hooks.fold_registrar_hooks(self.items))
    }
}

apply_registrar_hook! {
    capability: CommandCapability;
    trait: CommandRegistrar;
    method: register_commands;
    field: commands;
    proof: crate::capability::CommandHookProof;
    tag: CommandTag;
}

impl<Hooks, Items> Capability for CommandCap<Hooks, Items>
where
    Hooks: ApplyHooks<Items>,
{
    type Value = CommandCapability<Hooks::Output>;
    type Output = Tagged<CommandTag, CommandCapability<Hooks::Output>>;
    type Hooks = Hooks;
    type Items = Items;

    fn mount(self) -> Self::Output {
        mount_with_hooks(self, |items| CommandCapability { commands: items })
    }
}

/// Default command HList from [`with_commands`] (migrate, mark-migrations, seed, serve).
pub type DefaultCommands = HCons<
    Tagged<ServeCommandTag, ServeCommand>,
    HCons<
        Tagged<SeedCommandTag, SeedCommand>,
        HCons<
            Tagged<MarkMigrationsCommandTag, MarkMigrationsCommand>,
            HCons<Tagged<MigrateCommandTag, MigrateCommand>, HNil>,
        >,
    >,
>;

/// Run database migrations (`lariv migrate`).
#[derive(Clone, Copy, Debug, Default)]
pub struct MigrateCommand;

/// CLI args for [`MigrateCommand`] (no flags).
#[derive(Args, Debug, Clone, Default)]
pub struct MigrateArgs {}

#[async_trait::async_trait]
impl<M, MigIdx, DbIdx, Migrators> RunCommand<M, (MigIdx, DbIdx, Migrators)> for MigrateCommand
where
    M: GetByTag<MigrationTag, MigIdx, Value = MigrationCapability<Migrators>>
        + GetByTag<DbTag, DbIdx, Value = DbState>
        + Sync
        + Send
        + 'static,
    Migrators: RunMigrations + Clone + Send + Sync,
    MigIdx: Send + Sync + 'static,
    DbIdx: Send + Sync + 'static,
{
    type Args = MigrateArgs;
    const NAME: &'static str = "migrate";
    const ABOUT: &'static str = "Run database migrations";

    async fn run(_args: Self::Args, app: MountedApp<M>) -> anyhow::Result<()> {
        app.run_migrations().await?;
        Ok(())
    }
}

/// Mark every registered migration as applied without running DDL (`lariv mark-migrations`).
#[derive(Clone, Copy, Debug, Default)]
pub struct MarkMigrationsCommand;

/// CLI args for [`MarkMigrationsCommand`] (no flags).
#[derive(Args, Debug, Clone, Default)]
pub struct MarkMigrationsArgs {}

#[async_trait::async_trait]
impl<M, MigIdx, DbIdx, Migrators> RunCommand<M, (MigIdx, DbIdx, Migrators)>
    for MarkMigrationsCommand
where
    M: GetByTag<MigrationTag, MigIdx, Value = MigrationCapability<Migrators>>
        + GetByTag<DbTag, DbIdx, Value = crate::db::DbState>
        + Sync
        + Send
        + 'static,
    Migrators: crate::migration::CollectMigrations + Clone + Send + Sync,
    MigIdx: Send + Sync + 'static,
    DbIdx: Send + Sync + 'static,
{
    type Args = MarkMigrationsArgs;
    const NAME: &'static str = "mark-migrations";
    const ABOUT: &'static str = "Mark all registered migrations as applied without running them";

    async fn run(_args: Self::Args, app: MountedApp<M>) -> anyhow::Result<()> {
        let inserted = mark_migrations(&app).await?;
        tracing::info!(inserted, "migration versions recorded in seaql_migrations");
        Ok(())
    }
}

/// Run registered seed hooks (`lariv seed`).
#[derive(Clone, Copy, Debug, Default)]
pub struct SeedCommand;

/// CLI args for [`SeedCommand`] (no flags).
#[derive(Args, Debug, Clone, Default)]
pub struct SeedArgs {}

#[async_trait::async_trait]
impl<M, SeedsIdx, Seeds, SeedProof> RunCommand<M, (SeedsIdx, Seeds, SeedProof)> for SeedCommand
where
    M: GetByTag<SeedsTag, SeedsIdx, Value = SeedRunner<Seeds>> + Sync + Send + 'static,
    Seeds: FoldSeeds<M, SeedProof> + Clone + Send + Sync,
    SeedsIdx: Send + Sync + 'static,
    SeedProof: Send + Sync + 'static,
{
    type Args = SeedArgs;
    const NAME: &'static str = "seed";
    const ABOUT: &'static str = "Run database seed hooks";

    async fn run(_args: Self::Args, app: MountedApp<M>) -> anyhow::Result<()> {
        app.run_seeds().await
    }
}

/// Start the HTTP server (`lariv serve`).
#[derive(Clone, Copy, Debug, Default)]
pub struct ServeCommand;

/// CLI args for [`ServeCommand`] (no flags).
#[derive(Args, Debug, Clone, Default)]
pub struct ServeArgs {}

#[async_trait::async_trait]
impl<M, CfgIdx, Configs, AppCfgIdx, HttpIdx, Routes, SlotIdx, ServeIdx, ServeHooks, ServeProof>
    RunCommand<
        M,
        (
            CfgIdx,
            Configs,
            AppCfgIdx,
            HttpIdx,
            Routes,
            SlotIdx,
            ServeIdx,
            ServeHooks,
            ServeProof,
        ),
    > for ServeCommand
where
    M: GetByTag<ConfigTag, CfgIdx, Value = ConfigCapability<Configs>>
        + GetByTag<HttpTag, HttpIdx, Value = std::sync::Arc<HttpCapability<Routes>>>
        + GetByTag<SlotTag, SlotIdx, Value = crate::components::SharedChromeFolder>
        + GetByTag<
            crate::hooks::ServeStartupsTag,
            ServeIdx,
            Value = crate::hooks::ServeStartupRunner<ServeHooks>,
        > + ProvideRequestCaps
        + Clone
        + Send
        + Sync
        + 'static,
    Configs: GetByTag<AppConfigTag, AppCfgIdx, Value = AppConfig> + Send + Sync,
    Routes: MountRoutes + Clone + Send + Sync,
    ServeHooks: crate::hooks::FoldServeStartups<M, ServeProof> + Clone + Send + Sync,
    CfgIdx: Send + Sync + 'static,
    AppCfgIdx: Send + Sync + 'static,
    HttpIdx: Send + Sync + 'static,
    SlotIdx: Send + Sync + 'static,
    ServeIdx: Send + Sync + 'static,
    ServeProof: Send + Sync + 'static,
{
    type Args = ServeArgs;
    const NAME: &'static str = "serve";
    const ABOUT: &'static str = "Start the HTTP server";

    async fn run(_args: Self::Args, app: MountedApp<M>) -> anyhow::Result<()> {
        app.serve().await
    }
}

/// Attach the command capability with built-in migrate, seed, and serve subcommands.
///
/// # Examples
///
/// ```rust ignore
/// let app = with_commands(app);
/// // After mount:
/// let cli = app.get_capability_output::<CommandTag, _>().build_cli::<_, _>();
/// ```
pub fn with_commands<L, Proof>(app: App<L>) -> App<HCons<CommandCap<HNil, DefaultCommands>, L>>
where
    L: HList + CapTagAbsent<CommandTag, Proof>,
{
    app.add_capability(CapStore::with_items(
        CommandCapability::new()
            .prepend::<MigrateCommandTag, _>(MigrateCommand)
            .prepend::<MarkMigrationsCommandTag, _>(MarkMigrationsCommand)
            .prepend::<SeedCommandTag, _>(SeedCommand)
            .prepend::<ServeCommandTag, _>(ServeCommand)
            .commands,
    ))
}