Skip to main content

fusion_stack/
console.rs

1//! The PHP package's artisan commands, as Laravel for Rust console commands. [`FusionStack`]
2//! registers them, so `laravel api:version:list` and the rest work in any application that adds
3//! it as a service provider.
4//!
5//! [`FusionStack`]: crate::FusionStack
6
7use laravel::console::{Console, clap};
8
9use crate::State;
10
11const NO_VERSIONS: &str = "Versioning has no versions yet. Set Config::versions.";
12
13fn state() -> laravel::Result<&'static State> {
14    crate::STATE
15        .get()
16        .map(AsRef::as_ref)
17        .ok_or_else(|| laravel::Error::msg("Fusion Stack is not registered as a service provider."))
18}
19
20/// Writes text to a file, or prints it.
21fn emit(
22    console: &mut Console,
23    text: &str,
24    output: Option<&str>,
25    wrote: &str,
26) -> laravel::Result<()> {
27    match output {
28        Some(path) => {
29            std::fs::write(path, text)?;
30            console.info(format!("Wrote {wrote} to [{path}]."));
31        }
32        None => console.line(text.strip_suffix('\n').unwrap_or(text)),
33    }
34    Ok(())
35}
36
37fn detail(console: &mut Console, label: &str, value: &str) {
38    console.line(format!(
39        "  {label} {} {value}",
40        ".".repeat(40usize.saturating_sub(label.len()))
41    ));
42}
43
44/// List the API versions and the breaking changes each one introduced.
45#[derive(clap::Parser)]
46#[command(name = "api:version:list")]
47pub struct ListVersions;
48
49#[laravel::console::command]
50impl ListVersions {
51    async fn handle(self, console: &mut Console) -> laravel::Result<()> {
52        let Some(registry) = state()?.registry.as_ref() else {
53            console.info(NO_VERSIONS);
54            return Ok(());
55        };
56        let now = crate::time::now();
57        let rows: Vec<[String; 4]> = registry
58            .history()
59            .into_iter()
60            .map(|(version, changes)| {
61                [
62                    version.to_string(),
63                    registry.status(version, now),
64                    changes.len().to_string(),
65                    changes
66                        .iter()
67                        .map(|change| format!("• {}", change.description()))
68                        .collect::<Vec<_>>()
69                        .join("\n"),
70                ]
71            })
72            .collect();
73        console.table(["Version", "Status", "Changes", "Description"], rows);
74        Ok(())
75    }
76}
77
78/// Generate a Markdown changelog of the API versions from their version changes.
79#[derive(clap::Parser)]
80#[command(name = "api:changelog")]
81pub struct Changelog {
82    /// Write the changelog to this file instead of printing it.
83    #[arg(long)]
84    output: Option<String>,
85    /// Include versions newer than the latest.
86    #[arg(long)]
87    unreleased: bool,
88}
89
90#[laravel::console::command]
91impl Changelog {
92    async fn handle(self, console: &mut Console) -> laravel::Result<()> {
93        if state()?.registry.is_none() {
94            console.info(NO_VERSIONS);
95            return Ok(());
96        }
97        let markdown = crate::docs::markdown(self.unreleased);
98        emit(console, &markdown, self.output.as_deref(), "the changelog")
99    }
100}
101
102/// Generate an OpenAPI 3.1 document of the API as one version sees it.
103#[derive(clap::Parser)]
104#[command(name = "api:openapi")]
105pub struct OpenApi {
106    /// The API version to describe, such as 2026-06-01. Defaults to the latest.
107    #[arg(long = "api-version")]
108    api_version: Option<String>,
109    /// Write the document to this file instead of printing it.
110    #[arg(long)]
111    output: Option<String>,
112}
113
114#[laravel::console::command]
115impl OpenApi {
116    async fn handle(self, console: &mut Console) -> laravel::Result<u8> {
117        let state = state()?;
118        let requested = self
119            .api_version
120            .as_deref()
121            .filter(|_| state.registry.is_some());
122        let Ok(document) = crate::openapi::generate(requested) else {
123            console.error(format!(
124                "Unknown API version [{}]. Run api:version:list to see the versions.",
125                requested.unwrap_or_default()
126            ));
127            return Ok(1);
128        };
129        let described = document
130            .pointer("/info/version")
131            .and_then(serde_json::Value::as_str)
132            .filter(|_| state.registry.is_some())
133            .map_or_else(
134                || "the API".to_owned(),
135                |version| format!("version {version}"),
136            );
137        let json = crate::openapi::pretty(&document) + "\n";
138        emit(
139            console,
140            &json,
141            self.output.as_deref(),
142            &format!("the OpenAPI document for {described}"),
143        )?;
144        Ok(0)
145    }
146}
147
148/// List the endpoints, fields, filters, error codes and scopes the API reference has no description for.
149#[derive(clap::Parser)]
150#[command(name = "api:docs:lint")]
151pub struct LintDocs {
152    /// Exit with an error when anything has no description, whatever Docs::lint says.
153    #[arg(long)]
154    fail: bool,
155}
156
157#[laravel::console::command]
158impl LintDocs {
159    async fn handle(self, console: &mut Console) -> laravel::Result<u8> {
160        let state = state()?;
161        let gaps = crate::openapi::undocumented().map_err(laravel::Error::msg)?;
162        if gaps.is_empty() {
163            console.info("Everything in the API reference has a description.");
164            return Ok(0);
165        }
166        console.table(
167            ["Kind", "No description", "Where"],
168            gaps.iter()
169                .map(|gap| [gap.kind.clone(), gap.item.clone(), gap.location.clone()]),
170        );
171        let message = if gaps.len() == 1 {
172            "1 item has no description.".to_owned()
173        } else {
174            format!("{} items have no description.", gaps.len())
175        };
176        if self.fail || state.config.docs.lint_fails {
177            console.error(message);
178            return Ok(1);
179        }
180        console.warn(format!(
181            "{message} Run with --fail, or set Docs::lint_fails, to fail CI."
182        ));
183        Ok(0)
184    }
185}
186
187#[cfg(feature = "database")]
188pub use self::database::*;
189
190#[cfg(feature = "database")]
191mod database {
192    use std::collections::BTreeMap;
193
194    use laravel::console::{Console, clap};
195    use laravel::db::{self, col};
196    use laravel::prelude::ToSpan;
197    use serde_json::Value;
198
199    use super::{detail, state};
200    use crate::auth::api_keys;
201    use crate::query::Row;
202    use crate::versioning::ApiVersion;
203
204    fn text(row: &Row, key: &str) -> String {
205        match row.0.get(key) {
206            Some(Value::String(text)) => text.clone(),
207            Some(Value::Null) | None => String::new(),
208            Some(other) => other.to_string(),
209        }
210    }
211
212    /// Show which clients used which API versions recently.
213    #[derive(clap::Parser)]
214    #[command(name = "api:version:usage")]
215    pub struct VersionUsage {
216        /// Only this version, such as 2026-06-01.
217        version: Option<String>,
218        /// How many days back to look, today included.
219        #[arg(long, default_value_t = 30)]
220        days: i64,
221    }
222
223    #[laravel::console::command]
224    impl VersionUsage {
225        async fn handle(self, console: &mut Console) -> laravel::Result<u8> {
226            let registry = state()?.registry.as_ref();
227            let days = self.days.max(1);
228            let since = crate::time::date(crate::time::now() - (days - 1) * 86_400);
229            let mut query = db::table(crate::usage::TABLE)
230                .select(["version", "client_id", "date"])
231                .filter(col("date").ge(since));
232            if let Some(argument) = &self.version {
233                let version = ApiVersion::parse(argument)
234                    .and_then(|parsed| registry.and_then(|r| r.by_date(&parsed.date)).cloned());
235                let Some(version) = version else {
236                    console.error(format!("[{argument}] is not a version of this API."));
237                    return Ok(1);
238                };
239                query = query.filter(col("version").eq(version.to_string()));
240            }
241            let rows: Vec<Row> = query.get().await?;
242
243            // (version, client) to (last seen, days).
244            let mut usage: BTreeMap<(String, String), (String, u64)> = BTreeMap::new();
245            for row in &rows {
246                let entry = usage
247                    .entry((text(row, "version"), text(row, "client_id")))
248                    .or_default();
249                entry.0 = entry.0.clone().max(text(row, "date"));
250                entry.1 += 1;
251            }
252            if usage.is_empty() {
253                let what = self
254                    .version
255                    .as_ref()
256                    .map_or_else(|| "the API".to_owned(), |v| format!("version {v}"));
257                console.info(format!("No client used {what} in the last {days} days."));
258                return Ok(0);
259            }
260
261            // Name API keys, so their owners can be told to upgrade.
262            let keys: Vec<Row> = db::table("api_keys").select(["id", "name"]).get().await?;
263            let names: BTreeMap<String, String> = keys
264                .iter()
265                .map(|row| (format!("api_key:{}", text(row, "id")), text(row, "name")))
266                .collect();
267
268            let mut ordered: Vec<_> = usage.into_iter().collect();
269            ordered.sort_by(|((va, ca), (la, _)), ((vb, cb), (lb, _))| {
270                va.cmp(vb).then(lb.cmp(la)).then(ca.cmp(cb))
271            });
272            let now = crate::time::now();
273            let table: Vec<[String; 5]> = ordered
274                .into_iter()
275                .map(|((version, client), (last, count))| {
276                    let status = ApiVersion::parse(&version)
277                        .and_then(|parsed| registry.and_then(|r| r.by_date(&parsed.date)))
278                        .map_or_else(
279                            || "unknown".to_owned(),
280                            |known| registry.map(|r| r.status(known, now)).unwrap_or_default(),
281                        );
282                    let named = names
283                        .get(&client)
284                        .map_or_else(|| client.clone(), |name| format!("{client} ({name})"));
285                    [version, status, named, last, count.to_string()]
286                })
287                .collect();
288            console.table(
289                ["Version", "Status", "Client", "Last used", "Days used"],
290                table,
291            );
292            Ok(0)
293        }
294    }
295
296    /// Create an API key and show it once.
297    #[derive(clap::Parser)]
298    #[command(name = "api:key:create")]
299    pub struct CreateApiKey {
300        /// What the key is for, such as "Billing service".
301        name: String,
302        /// A scope to grant; repeat for several, or * for every scope.
303        #[arg(long = "scope")]
304        scopes: Vec<String>,
305        /// The version to pin the key to. Defaults to the latest version.
306        #[arg(long)]
307        pin: Option<String>,
308        /// Days until the key stops working. Without it, the key never expires.
309        #[arg(long, value_name = "DAYS", value_parser = clap::value_parser!(i64).range(1..=36500))]
310        expires_in: Option<i64>,
311        /// Create an fs_test_ key, which production turns away.
312        #[arg(long)]
313        test: bool,
314    }
315
316    #[laravel::console::command]
317    impl CreateApiKey {
318        async fn handle(self, console: &mut Console) -> laravel::Result<()> {
319            let version = self.pin.clone().or_else(|| {
320                state()
321                    .ok()
322                    .and_then(|state| state.registry.as_ref())
323                    .map(|registry| registry.latest.to_string())
324            });
325            let expires_at = match self.expires_in {
326                Some(days) => Some(laravel::now().checked_add(days.days())?.timestamp()),
327                None => None,
328            };
329            let (id, plain) = api_keys::issue(api_keys::Issue {
330                name: self.name,
331                scopes: self.scopes.clone(),
332                version: version.clone(),
333                rate_limit_tier: None,
334                expires_at,
335                test: self.test,
336            })
337            .await?;
338            console.info(format!(
339                "Created API key {id}. Copy it now: it is not stored and cannot be shown again."
340            ));
341            console.line(format!("  {plain}"));
342            console.new_line();
343            let scopes = if self.scopes.is_empty() {
344                "none".to_owned()
345            } else {
346                self.scopes.join(", ")
347            };
348            detail(console, "Scopes", &scopes);
349            detail(
350                console,
351                "Pinned version",
352                version.as_deref().unwrap_or("the default version"),
353            );
354            if let Some(expires_at) = expires_at {
355                let expires = format!("{} UTC", expires_at.strftime("%Y-%m-%d %H:%M"));
356                detail(console, "Expires", &expires);
357            }
358            Ok(())
359        }
360    }
361
362    /// Change the API version a key is pinned to, such as when its owner upgrades.
363    #[derive(clap::Parser)]
364    #[command(name = "api:key:pin")]
365    pub struct PinApiKey {
366        /// The API key ID.
367        key: i64,
368        /// The version to pin it to. Defaults to the latest version.
369        version: Option<String>,
370    }
371
372    #[laravel::console::command]
373    impl PinApiKey {
374        async fn handle(self, console: &mut Console) -> laravel::Result<u8> {
375            let row: Option<Row> = db::table("api_keys")
376                .select(["id", "name", "version"])
377                .filter(col("id").eq(self.key))
378                .first()
379                .await?;
380            let Some(row) = row else {
381                console.error(format!("There is no API key [{}].", self.key));
382                return Ok(1);
383            };
384            let registry = state()?.registry.as_ref();
385            let version = match (registry, &self.version) {
386                (Some(registry), None) => Some(registry.latest.clone()),
387                (Some(registry), Some(name)) => registry.named(name),
388                (None, _) => None,
389            }
390            .filter(|version| registry.is_some_and(|r| !r.is_retired(version, crate::time::now())));
391            let Some(version) = version else {
392                console.error(format!(
393                    "[{}] is not a released, unretired version. Run api:version:list to see them.",
394                    self.version.unwrap_or_default()
395                ));
396                return Ok(1);
397            };
398            let previous = Some(text(&row, "version"))
399                .filter(|v| !v.is_empty())
400                .unwrap_or_else(|| "the default version".to_owned());
401            api_keys::pin_to(self.key, Some(&version.to_string())).await?;
402            console.info(format!(
403                "API key {} ({}) moved from {previous} to {version}.",
404                self.key,
405                text(&row, "name")
406            ));
407            Ok(0)
408        }
409    }
410
411    /// Register a webhook endpoint and show its signing secret.
412    #[derive(clap::Parser)]
413    #[command(name = "api:webhook:create")]
414    pub struct CreateWebhookEndpoint {
415        /// Where to send the webhooks.
416        url: String,
417        /// An event type to subscribe to, such as order.created or order.*; repeat for several.
418        /// Defaults to every event.
419        #[arg(long = "event")]
420        events: Vec<String>,
421        /// The version to pin the endpoint to. Defaults to the latest version.
422        #[arg(long)]
423        pin: Option<String>,
424        /// What the endpoint is for.
425        #[arg(long)]
426        description: Option<String>,
427    }
428
429    #[laravel::console::command]
430    impl CreateWebhookEndpoint {
431        async fn handle(self, console: &mut Console) -> laravel::Result<()> {
432            let events: Vec<&str> = if self.events.is_empty() {
433                vec!["*"]
434            } else {
435                self.events.iter().map(String::as_str).collect()
436            };
437            let id = crate::webhooks::register(
438                &self.url,
439                &events,
440                self.pin.as_deref(),
441                self.description.as_deref(),
442            )
443            .await?;
444            let row: Option<Row> = db::table("webhook_endpoints")
445                .select(["version"])
446                .filter(col("id").eq(id))
447                .first()
448                .await?;
449            let version = row
450                .map(|row| text(&row, "version"))
451                .filter(|v| !v.is_empty())
452                .unwrap_or_else(|| "the default version".to_owned());
453            console.info(format!(
454                "Registered webhook endpoint {id}. Use this secret to verify its signatures:"
455            ));
456            console.line(crate::webhooks::secret(id).await?);
457            detail(console, "Events", &events.join(", "));
458            detail(console, "Pinned to", &version);
459            Ok(())
460        }
461    }
462}
463
464/// Registers the commands.
465pub(crate) fn register(commands: &mut laravel::console::Commands) {
466    commands
467        .add::<ListVersions>()
468        .add::<Changelog>()
469        .add::<OpenApi>()
470        .add::<LintDocs>();
471    #[cfg(feature = "database")]
472    commands
473        .add::<VersionUsage>()
474        .add::<CreateApiKey>()
475        .add::<PinApiKey>()
476        .add::<CreateWebhookEndpoint>();
477}