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 serde_json::Value;
197
198    use super::{detail, state};
199    use crate::auth::api_keys;
200    use crate::query::Row;
201    use crate::versioning::ApiVersion;
202
203    fn text(row: &Row, key: &str) -> String {
204        match row.0.get(key) {
205            Some(Value::String(text)) => text.clone(),
206            Some(Value::Null) | None => String::new(),
207            Some(other) => other.to_string(),
208        }
209    }
210
211    /// Show which clients used which API versions recently.
212    #[derive(clap::Parser)]
213    #[command(name = "api:version:usage")]
214    pub struct VersionUsage {
215        /// Only this version, such as 2026-06-01.
216        version: Option<String>,
217        /// How many days back to look, today included.
218        #[arg(long, default_value_t = 30)]
219        days: i64,
220    }
221
222    #[laravel::console::command]
223    impl VersionUsage {
224        async fn handle(self, console: &mut Console) -> laravel::Result<u8> {
225            let registry = state()?.registry.as_ref();
226            let days = self.days.max(1);
227            let since = crate::time::date(crate::time::now() - (days - 1) * 86_400);
228            let mut query = db::table(crate::usage::TABLE)
229                .select(["version", "client_id", "date"])
230                .filter(col("date").ge(since));
231            if let Some(argument) = &self.version {
232                let version = ApiVersion::parse(argument)
233                    .and_then(|parsed| registry.and_then(|r| r.by_date(&parsed.date)).cloned());
234                let Some(version) = version else {
235                    console.error(format!("[{argument}] is not a version of this API."));
236                    return Ok(1);
237                };
238                query = query.filter(col("version").eq(version.to_string()));
239            }
240            let rows: Vec<Row> = query.get().await?;
241
242            // (version, client) to (last seen, days).
243            let mut usage: BTreeMap<(String, String), (String, u64)> = BTreeMap::new();
244            for row in &rows {
245                let entry = usage
246                    .entry((text(row, "version"), text(row, "client_id")))
247                    .or_default();
248                entry.0 = entry.0.clone().max(text(row, "date"));
249                entry.1 += 1;
250            }
251            if usage.is_empty() {
252                let what = self
253                    .version
254                    .as_ref()
255                    .map_or_else(|| "the API".to_owned(), |v| format!("version {v}"));
256                console.info(format!("No client used {what} in the last {days} days."));
257                return Ok(0);
258            }
259
260            // Name API keys, so their owners can be told to upgrade.
261            let keys: Vec<Row> = db::table("api_keys").select(["id", "name"]).get().await?;
262            let names: BTreeMap<String, String> = keys
263                .iter()
264                .map(|row| (format!("api_key:{}", text(row, "id")), text(row, "name")))
265                .collect();
266
267            let mut ordered: Vec<_> = usage.into_iter().collect();
268            ordered.sort_by(|((va, ca), (la, _)), ((vb, cb), (lb, _))| {
269                va.cmp(vb).then(lb.cmp(la)).then(ca.cmp(cb))
270            });
271            let now = crate::time::now();
272            let table: Vec<[String; 5]> = ordered
273                .into_iter()
274                .map(|((version, client), (last, count))| {
275                    let status = ApiVersion::parse(&version)
276                        .and_then(|parsed| registry.and_then(|r| r.by_date(&parsed.date)))
277                        .map_or_else(
278                            || "unknown".to_owned(),
279                            |known| registry.map(|r| r.status(known, now)).unwrap_or_default(),
280                        );
281                    let named = names
282                        .get(&client)
283                        .map_or_else(|| client.clone(), |name| format!("{client} ({name})"));
284                    [version, status, named, last, count.to_string()]
285                })
286                .collect();
287            console.table(
288                ["Version", "Status", "Client", "Last used", "Days used"],
289                table,
290            );
291            Ok(0)
292        }
293    }
294
295    /// Create an API key and show it once.
296    #[derive(clap::Parser)]
297    #[command(name = "api:key:create")]
298    pub struct CreateApiKey {
299        /// What the key is for, such as "Billing service".
300        name: String,
301        /// A scope to grant; repeat for several, or * for every scope.
302        #[arg(long = "scope")]
303        scopes: Vec<String>,
304        /// The version to pin the key to. Defaults to the latest version.
305        #[arg(long)]
306        pin: Option<String>,
307        /// Create an fs_test_ key.
308        #[arg(long)]
309        test: bool,
310    }
311
312    #[laravel::console::command]
313    impl CreateApiKey {
314        async fn handle(self, console: &mut Console) -> laravel::Result<()> {
315            let version = self.pin.clone().or_else(|| {
316                state()
317                    .ok()
318                    .and_then(|state| state.registry.as_ref())
319                    .map(|registry| registry.latest.to_string())
320            });
321            let (id, plain) = api_keys::issue(api_keys::Issue {
322                name: self.name,
323                scopes: self.scopes.clone(),
324                version: version.clone(),
325                rate_limit_tier: None,
326                test: self.test,
327            })
328            .await?;
329            console.info(format!(
330                "Created API key {id}. Copy it now: it is not stored and cannot be shown again."
331            ));
332            console.line(format!("  {plain}"));
333            console.new_line();
334            let scopes = if self.scopes.is_empty() {
335                "none".to_owned()
336            } else {
337                self.scopes.join(", ")
338            };
339            detail(console, "Scopes", &scopes);
340            detail(
341                console,
342                "Pinned version",
343                version.as_deref().unwrap_or("the default version"),
344            );
345            Ok(())
346        }
347    }
348
349    /// Change the API version a key is pinned to, such as when its owner upgrades.
350    #[derive(clap::Parser)]
351    #[command(name = "api:key:pin")]
352    pub struct PinApiKey {
353        /// The API key ID.
354        key: i64,
355        /// The version to pin it to. Defaults to the latest version.
356        version: Option<String>,
357    }
358
359    #[laravel::console::command]
360    impl PinApiKey {
361        async fn handle(self, console: &mut Console) -> laravel::Result<u8> {
362            let row: Option<Row> = db::table("api_keys")
363                .select(["id", "name", "version"])
364                .filter(col("id").eq(self.key))
365                .first()
366                .await?;
367            let Some(row) = row else {
368                console.error(format!("There is no API key [{}].", self.key));
369                return Ok(1);
370            };
371            let registry = state()?.registry.as_ref();
372            let version = match (registry, &self.version) {
373                (Some(registry), None) => Some(registry.latest.clone()),
374                (Some(registry), Some(name)) => registry.named(name),
375                (None, _) => None,
376            }
377            .filter(|version| registry.is_some_and(|r| !r.is_retired(version, crate::time::now())));
378            let Some(version) = version else {
379                console.error(format!(
380                    "[{}] is not a released, unretired version. Run api:version:list to see them.",
381                    self.version.unwrap_or_default()
382                ));
383                return Ok(1);
384            };
385            let previous = Some(text(&row, "version"))
386                .filter(|v| !v.is_empty())
387                .unwrap_or_else(|| "the default version".to_owned());
388            api_keys::pin_to(self.key, Some(&version.to_string())).await?;
389            console.info(format!(
390                "API key {} ({}) moved from {previous} to {version}.",
391                self.key,
392                text(&row, "name")
393            ));
394            Ok(0)
395        }
396    }
397
398    /// Register a webhook endpoint and show its signing secret.
399    #[derive(clap::Parser)]
400    #[command(name = "api:webhook:create")]
401    pub struct CreateWebhookEndpoint {
402        /// Where to send the webhooks.
403        url: String,
404        /// An event type to subscribe to, such as order.created or order.*; repeat for several.
405        /// Defaults to every event.
406        #[arg(long = "event")]
407        events: Vec<String>,
408        /// The version to pin the endpoint to. Defaults to the latest version.
409        #[arg(long)]
410        pin: Option<String>,
411        /// What the endpoint is for.
412        #[arg(long)]
413        description: Option<String>,
414    }
415
416    #[laravel::console::command]
417    impl CreateWebhookEndpoint {
418        async fn handle(self, console: &mut Console) -> laravel::Result<()> {
419            let events: Vec<&str> = if self.events.is_empty() {
420                vec!["*"]
421            } else {
422                self.events.iter().map(String::as_str).collect()
423            };
424            let id = crate::webhooks::register(
425                &self.url,
426                &events,
427                self.pin.as_deref(),
428                self.description.as_deref(),
429            )
430            .await?;
431            let row: Option<Row> = db::table("webhook_endpoints")
432                .select(["version"])
433                .filter(col("id").eq(id))
434                .first()
435                .await?;
436            let version = row
437                .map(|row| text(&row, "version"))
438                .filter(|v| !v.is_empty())
439                .unwrap_or_else(|| "the default version".to_owned());
440            console.info(format!(
441                "Registered webhook endpoint {id}. Use this secret to verify its signatures:"
442            ));
443            console.line(crate::webhooks::secret(id).await?);
444            detail(console, "Events", &events.join(", "));
445            detail(console, "Pinned to", &version);
446            Ok(())
447        }
448    }
449}
450
451/// Registers the commands.
452pub(crate) fn register(commands: &mut laravel::console::Commands) {
453    commands
454        .add::<ListVersions>()
455        .add::<Changelog>()
456        .add::<OpenApi>()
457        .add::<LintDocs>();
458    #[cfg(feature = "database")]
459    commands
460        .add::<VersionUsage>()
461        .add::<CreateApiKey>()
462        .add::<PinApiKey>()
463        .add::<CreateWebhookEndpoint>();
464}