fusion-stack-laravel-rust 0.3.0

Fusion Stack for Laravel for Rust: versioned, documented JSON APIs with standard errors
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
//! The PHP package's artisan commands, as Laravel for Rust console commands. [`FusionStack`]
//! registers them, so `laravel api:version:list` and the rest work in any application that adds
//! it as a service provider.
//!
//! [`FusionStack`]: crate::FusionStack

use laravel::console::{Console, clap};

use crate::State;

const NO_VERSIONS: &str = "Versioning has no versions yet. Set Config::versions.";

fn state() -> laravel::Result<&'static State> {
    crate::STATE
        .get()
        .map(AsRef::as_ref)
        .ok_or_else(|| laravel::Error::msg("Fusion Stack is not registered as a service provider."))
}

/// Writes text to a file, or prints it.
fn emit(
    console: &mut Console,
    text: &str,
    output: Option<&str>,
    wrote: &str,
) -> laravel::Result<()> {
    match output {
        Some(path) => {
            std::fs::write(path, text)?;
            console.info(format!("Wrote {wrote} to [{path}]."));
        }
        None => console.line(text.strip_suffix('\n').unwrap_or(text)),
    }
    Ok(())
}

fn detail(console: &mut Console, label: &str, value: &str) {
    console.line(format!(
        "  {label} {} {value}",
        ".".repeat(40usize.saturating_sub(label.len()))
    ));
}

/// List the API versions and the breaking changes each one introduced.
#[derive(clap::Parser)]
#[command(name = "api:version:list")]
pub struct ListVersions;

#[laravel::console::command]
impl ListVersions {
    async fn handle(self, console: &mut Console) -> laravel::Result<()> {
        let Some(registry) = state()?.registry.as_ref() else {
            console.info(NO_VERSIONS);
            return Ok(());
        };
        let now = crate::time::now();
        let rows: Vec<[String; 4]> = registry
            .history()
            .into_iter()
            .map(|(version, changes)| {
                [
                    version.to_string(),
                    registry.status(version, now),
                    changes.len().to_string(),
                    changes
                        .iter()
                        .map(|change| format!("• {}", change.description()))
                        .collect::<Vec<_>>()
                        .join("\n"),
                ]
            })
            .collect();
        console.table(["Version", "Status", "Changes", "Description"], rows);
        Ok(())
    }
}

/// Generate a Markdown changelog of the API versions from their version changes.
#[derive(clap::Parser)]
#[command(name = "api:changelog")]
pub struct Changelog {
    /// Write the changelog to this file instead of printing it.
    #[arg(long)]
    output: Option<String>,
    /// Include versions newer than the latest.
    #[arg(long)]
    unreleased: bool,
}

#[laravel::console::command]
impl Changelog {
    async fn handle(self, console: &mut Console) -> laravel::Result<()> {
        if state()?.registry.is_none() {
            console.info(NO_VERSIONS);
            return Ok(());
        }
        let markdown = crate::docs::markdown(self.unreleased);
        emit(console, &markdown, self.output.as_deref(), "the changelog")
    }
}

/// Generate an OpenAPI 3.1 document of the API as one version sees it.
#[derive(clap::Parser)]
#[command(name = "api:openapi")]
pub struct OpenApi {
    /// The API version to describe, such as 2026-06-01. Defaults to the latest.
    #[arg(long = "api-version")]
    api_version: Option<String>,
    /// Write the document to this file instead of printing it.
    #[arg(long)]
    output: Option<String>,
}

#[laravel::console::command]
impl OpenApi {
    async fn handle(self, console: &mut Console) -> laravel::Result<u8> {
        let state = state()?;
        let requested = self
            .api_version
            .as_deref()
            .filter(|_| state.registry.is_some());
        let Ok(document) = crate::openapi::generate(requested) else {
            console.error(format!(
                "Unknown API version [{}]. Run api:version:list to see the versions.",
                requested.unwrap_or_default()
            ));
            return Ok(1);
        };
        let described = document
            .pointer("/info/version")
            .and_then(serde_json::Value::as_str)
            .filter(|_| state.registry.is_some())
            .map_or_else(
                || "the API".to_owned(),
                |version| format!("version {version}"),
            );
        let json = crate::openapi::pretty(&document) + "\n";
        emit(
            console,
            &json,
            self.output.as_deref(),
            &format!("the OpenAPI document for {described}"),
        )?;
        Ok(0)
    }
}

/// List the endpoints, fields, filters, error codes and scopes the API reference has no description for.
#[derive(clap::Parser)]
#[command(name = "api:docs:lint")]
pub struct LintDocs {
    /// Exit with an error when anything has no description, whatever Docs::lint says.
    #[arg(long)]
    fail: bool,
}

#[laravel::console::command]
impl LintDocs {
    async fn handle(self, console: &mut Console) -> laravel::Result<u8> {
        let state = state()?;
        let gaps = crate::openapi::undocumented().map_err(laravel::Error::msg)?;
        if gaps.is_empty() {
            console.info("Everything in the API reference has a description.");
            return Ok(0);
        }
        console.table(
            ["Kind", "No description", "Where"],
            gaps.iter()
                .map(|gap| [gap.kind.clone(), gap.item.clone(), gap.location.clone()]),
        );
        let message = if gaps.len() == 1 {
            "1 item has no description.".to_owned()
        } else {
            format!("{} items have no description.", gaps.len())
        };
        if self.fail || state.config.docs.lint_fails {
            console.error(message);
            return Ok(1);
        }
        console.warn(format!(
            "{message} Run with --fail, or set Docs::lint_fails, to fail CI."
        ));
        Ok(0)
    }
}

#[cfg(feature = "database")]
pub use self::database::*;

#[cfg(feature = "database")]
mod database {
    use std::collections::BTreeMap;

    use laravel::console::{Console, clap};
    use laravel::db::{self, col};
    use laravel::prelude::ToSpan;
    use serde_json::Value;

    use super::{detail, state};
    use crate::auth::api_keys;
    use crate::query::Row;
    use crate::versioning::ApiVersion;

    fn text(row: &Row, key: &str) -> String {
        match row.0.get(key) {
            Some(Value::String(text)) => text.clone(),
            Some(Value::Null) | None => String::new(),
            Some(other) => other.to_string(),
        }
    }

    /// Show which clients used which API versions recently.
    #[derive(clap::Parser)]
    #[command(name = "api:version:usage")]
    pub struct VersionUsage {
        /// Only this version, such as 2026-06-01.
        version: Option<String>,
        /// How many days back to look, today included.
        #[arg(long, default_value_t = 30)]
        days: i64,
    }

    #[laravel::console::command]
    impl VersionUsage {
        async fn handle(self, console: &mut Console) -> laravel::Result<u8> {
            let registry = state()?.registry.as_ref();
            let days = self.days.max(1);
            let since = crate::time::date(crate::time::now() - (days - 1) * 86_400);
            let mut query = db::table(crate::usage::TABLE)
                .select(["version", "client_id", "date"])
                .filter(col("date").ge(since));
            if let Some(argument) = &self.version {
                let version = ApiVersion::parse(argument)
                    .and_then(|parsed| registry.and_then(|r| r.by_date(&parsed.date)).cloned());
                let Some(version) = version else {
                    console.error(format!("[{argument}] is not a version of this API."));
                    return Ok(1);
                };
                query = query.filter(col("version").eq(version.to_string()));
            }
            let rows: Vec<Row> = query.get().await?;

            // (version, client) to (last seen, days).
            let mut usage: BTreeMap<(String, String), (String, u64)> = BTreeMap::new();
            for row in &rows {
                let entry = usage
                    .entry((text(row, "version"), text(row, "client_id")))
                    .or_default();
                entry.0 = entry.0.clone().max(text(row, "date"));
                entry.1 += 1;
            }
            if usage.is_empty() {
                let what = self
                    .version
                    .as_ref()
                    .map_or_else(|| "the API".to_owned(), |v| format!("version {v}"));
                console.info(format!("No client used {what} in the last {days} days."));
                return Ok(0);
            }

            // Name API keys, so their owners can be told to upgrade.
            let keys: Vec<Row> = db::table("api_keys").select(["id", "name"]).get().await?;
            let names: BTreeMap<String, String> = keys
                .iter()
                .map(|row| (format!("api_key:{}", text(row, "id")), text(row, "name")))
                .collect();

            let mut ordered: Vec<_> = usage.into_iter().collect();
            ordered.sort_by(|((va, ca), (la, _)), ((vb, cb), (lb, _))| {
                va.cmp(vb).then(lb.cmp(la)).then(ca.cmp(cb))
            });
            let now = crate::time::now();
            let table: Vec<[String; 5]> = ordered
                .into_iter()
                .map(|((version, client), (last, count))| {
                    let status = ApiVersion::parse(&version)
                        .and_then(|parsed| registry.and_then(|r| r.by_date(&parsed.date)))
                        .map_or_else(
                            || "unknown".to_owned(),
                            |known| registry.map(|r| r.status(known, now)).unwrap_or_default(),
                        );
                    let named = names
                        .get(&client)
                        .map_or_else(|| client.clone(), |name| format!("{client} ({name})"));
                    [version, status, named, last, count.to_string()]
                })
                .collect();
            console.table(
                ["Version", "Status", "Client", "Last used", "Days used"],
                table,
            );
            Ok(0)
        }
    }

    /// Create an API key and show it once.
    #[derive(clap::Parser)]
    #[command(name = "api:key:create")]
    pub struct CreateApiKey {
        /// What the key is for, such as "Billing service".
        name: String,
        /// A scope to grant; repeat for several, or * for every scope.
        #[arg(long = "scope")]
        scopes: Vec<String>,
        /// The version to pin the key to. Defaults to the latest version.
        #[arg(long)]
        pin: Option<String>,
        /// Days until the key stops working. Without it, the key never expires.
        #[arg(long, value_name = "DAYS", value_parser = clap::value_parser!(i64).range(1..=36500))]
        expires_in: Option<i64>,
        /// Create an fs_test_ key, which production turns away.
        #[arg(long)]
        test: bool,
    }

    #[laravel::console::command]
    impl CreateApiKey {
        async fn handle(self, console: &mut Console) -> laravel::Result<()> {
            let version = self.pin.clone().or_else(|| {
                state()
                    .ok()
                    .and_then(|state| state.registry.as_ref())
                    .map(|registry| registry.latest.to_string())
            });
            let expires_at = match self.expires_in {
                Some(days) => Some(laravel::now().checked_add(days.days())?.timestamp()),
                None => None,
            };
            let (id, plain) = api_keys::issue(api_keys::Issue {
                name: self.name,
                scopes: self.scopes.clone(),
                version: version.clone(),
                rate_limit_tier: None,
                expires_at,
                test: self.test,
            })
            .await?;
            console.info(format!(
                "Created API key {id}. Copy it now: it is not stored and cannot be shown again."
            ));
            console.line(format!("  {plain}"));
            console.new_line();
            let scopes = if self.scopes.is_empty() {
                "none".to_owned()
            } else {
                self.scopes.join(", ")
            };
            detail(console, "Scopes", &scopes);
            detail(
                console,
                "Pinned version",
                version.as_deref().unwrap_or("the default version"),
            );
            if let Some(expires_at) = expires_at {
                let expires = format!("{} UTC", expires_at.strftime("%Y-%m-%d %H:%M"));
                detail(console, "Expires", &expires);
            }
            Ok(())
        }
    }

    /// Change the API version a key is pinned to, such as when its owner upgrades.
    #[derive(clap::Parser)]
    #[command(name = "api:key:pin")]
    pub struct PinApiKey {
        /// The API key ID.
        key: i64,
        /// The version to pin it to. Defaults to the latest version.
        version: Option<String>,
    }

    #[laravel::console::command]
    impl PinApiKey {
        async fn handle(self, console: &mut Console) -> laravel::Result<u8> {
            let row: Option<Row> = db::table("api_keys")
                .select(["id", "name", "version"])
                .filter(col("id").eq(self.key))
                .first()
                .await?;
            let Some(row) = row else {
                console.error(format!("There is no API key [{}].", self.key));
                return Ok(1);
            };
            let registry = state()?.registry.as_ref();
            let version = match (registry, &self.version) {
                (Some(registry), None) => Some(registry.latest.clone()),
                (Some(registry), Some(name)) => registry.named(name),
                (None, _) => None,
            }
            .filter(|version| registry.is_some_and(|r| !r.is_retired(version, crate::time::now())));
            let Some(version) = version else {
                console.error(format!(
                    "[{}] is not a released, unretired version. Run api:version:list to see them.",
                    self.version.unwrap_or_default()
                ));
                return Ok(1);
            };
            let previous = Some(text(&row, "version"))
                .filter(|v| !v.is_empty())
                .unwrap_or_else(|| "the default version".to_owned());
            api_keys::pin_to(self.key, Some(&version.to_string())).await?;
            console.info(format!(
                "API key {} ({}) moved from {previous} to {version}.",
                self.key,
                text(&row, "name")
            ));
            Ok(0)
        }
    }

    /// Register a webhook endpoint and show its signing secret.
    #[derive(clap::Parser)]
    #[command(name = "api:webhook:create")]
    pub struct CreateWebhookEndpoint {
        /// Where to send the webhooks.
        url: String,
        /// An event type to subscribe to, such as order.created or order.*; repeat for several.
        /// Defaults to every event.
        #[arg(long = "event")]
        events: Vec<String>,
        /// The version to pin the endpoint to. Defaults to the latest version.
        #[arg(long)]
        pin: Option<String>,
        /// What the endpoint is for.
        #[arg(long)]
        description: Option<String>,
    }

    #[laravel::console::command]
    impl CreateWebhookEndpoint {
        async fn handle(self, console: &mut Console) -> laravel::Result<()> {
            let events: Vec<&str> = if self.events.is_empty() {
                vec!["*"]
            } else {
                self.events.iter().map(String::as_str).collect()
            };
            let id = crate::webhooks::register(
                &self.url,
                &events,
                self.pin.as_deref(),
                self.description.as_deref(),
            )
            .await?;
            let row: Option<Row> = db::table("webhook_endpoints")
                .select(["version"])
                .filter(col("id").eq(id))
                .first()
                .await?;
            let version = row
                .map(|row| text(&row, "version"))
                .filter(|v| !v.is_empty())
                .unwrap_or_else(|| "the default version".to_owned());
            console.info(format!(
                "Registered webhook endpoint {id}. Use this secret to verify its signatures:"
            ));
            console.line(crate::webhooks::secret(id).await?);
            detail(console, "Events", &events.join(", "));
            detail(console, "Pinned to", &version);
            Ok(())
        }
    }
}

/// Registers the commands.
pub(crate) fn register(commands: &mut laravel::console::Commands) {
    commands
        .add::<ListVersions>()
        .add::<Changelog>()
        .add::<OpenApi>()
        .add::<LintDocs>();
    #[cfg(feature = "database")]
    commands
        .add::<VersionUsage>()
        .add::<CreateApiKey>()
        .add::<PinApiKey>()
        .add::<CreateWebhookEndpoint>();
}