loco-rs 1.1.0

The one-person framework for Rust
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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
//! Doctor module for health checks and diagnostics.
//!
//! This module provides health checks for various components of a Loco application.
//!
//! # Initializer Health Checks
//!
//! Initializers can now provide their own health checks by implementing the `check` method
//! on the `Initializer` trait. This allows each initializer to validate its configuration
//! and test its connections during the doctor command.
//!
//! When you run `cargo loco doctor`, any initializers that implement the `check` method
//! will have their health checks executed and displayed in the output.

use colored::Colorize;
use regex::Regex;
use semver::Version;
use std::fmt::Write;
use std::{
    collections::{BTreeMap, HashMap},
    process::Command,
    sync::OnceLock,
};

use crate::{
    bgworker,
    config::{self, Config, QueueConfig},
    depcheck, Error, Result,
};

const SEAORM_INSTALLED: &str = "SeaORM CLI is installed";
const SEAORM_NOT_INSTALLED: &str = "SeaORM CLI was not found";
const SEAORM_NOT_FIX: &str = r"To fix, run:
      $ cargo install sea-orm-cli";
const QUEUE_CONN_OK: &str = "queue connection: success";
const QUEUE_CONN_FAILED: &str = "queue connection: failed";
const QUEUE_NOT_CONFIGURED: &str = "queue not configured?";

// versions health
const MIN_SEAORMCLI_VER: &str = "2.0.0-rc";
static MIN_DEP_VERSIONS: OnceLock<HashMap<&'static str, &'static str>> = OnceLock::new();
static RE_CRATE_VERSION: OnceLock<Regex> = OnceLock::new();

fn get_re_crate_version() -> &'static Regex {
    RE_CRATE_VERSION.get_or_init(|| Regex::new(r#"(?m)^[^"]*"([^"]+)""#).unwrap())
}

fn get_min_dep_versions() -> &'static HashMap<&'static str, &'static str> {
    MIN_DEP_VERSIONS.get_or_init(|| {
        let mut min_vers = HashMap::new();

        min_vers.insert("tokio", "1.33.0");
        min_vers.insert("sea-orm", "2.0.0-rc");
        min_vers.insert("validator", "0.20.0");
        min_vers.insert("axum", "0.8.1");

        min_vers
    })
}

/// Check latest crate version in crates.io
///
/// # Errors
///
/// This function will return an error if it fails
pub fn check_cratesio_version(crate_name: &str, current_version: &str) -> Result<Option<String>> {
    // Use cargo search to get the latest version
    let output = Command::new("cargo")
        .args(["search", crate_name, "--limit", "1"])
        .output()
        .map_err(|e| Error::Message(format!("Failed to run cargo search: {e}")))?;

    let output_str = String::from_utf8(output.stdout)
        .map_err(|e| Error::Message(format!("Invalid output from cargo search: {e}")))?;

    // Parse the version from cargo search output
    // Output format is: crate_name = "version"
    let latest_version = get_re_crate_version()
        .captures(&output_str)
        .and_then(|cap| cap.get(1))
        .map(|m| m.as_str())
        .ok_or_else(|| {
            Error::Message("Could not find version in cargo search output".to_string())
        })?;

    // Parse versions for comparison
    let current = Version::parse(current_version)
        .map_err(|e| Error::Message(format!("Invalid current version: {e}")))?;
    let latest = Version::parse(latest_version)
        .map_err(|e| Error::Message(format!("Invalid latest version: {e}")))?;

    // Compare versions
    if latest > current {
        Ok(Some(latest_version.to_string()))
    } else {
        Ok(None)
    }
}

/// Represents different resources that can be checked.
#[derive(PartialOrd, PartialEq, Eq, Ord, Debug)]
#[non_exhaustive]
pub enum Resource {
    /// Settings that are safe in development and dangerous in production.
    ProductionSafety,
    SeaOrmCLI,
    Database,
    Queue,
    Deps,
    PublishedLocoVersion,
    Initializer(String),
}

/// Represents the status of a resource check.
#[derive(Debug, PartialEq, Eq)]
pub enum CheckStatus {
    Ok,
    NotOk,
    NotConfigure,
}

/// Represents the result of a resource check.
#[derive(Debug)]
pub struct Check {
    /// The status of the check.
    pub status: CheckStatus,
    /// A message describing the result of the check.
    pub message: String,
    /// Additional information or instructions related to the check.
    pub description: Option<String>,
}

impl Check {
    #[must_use]
    pub fn valid(&self) -> bool {
        self.status != CheckStatus::NotOk
    }
    /// Convert to a Result type
    ///
    /// # Errors
    ///
    /// This function will return an error if Check fails
    pub fn to_result(&self) -> Result<()> {
        if self.valid() {
            Ok(())
        } else {
            Err(Error::Message(format!(
                "{} {}",
                self.message,
                self.description.clone().unwrap_or_default()
            )))
        }
    }
}

impl std::fmt::Display for Check {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let icon = match self.status {
            CheckStatus::Ok => "",
            CheckStatus::NotOk => "",
            CheckStatus::NotConfigure => "⚠️",
        };

        write!(
            f,
            "{} {}{}",
            icon,
            self.message,
            self.description
                .as_ref()
                .map(|d| format!("\n   {d}"))
                .unwrap_or_default()
        )
    }
}

/// Runs checks for all configured resources.
/// # Errors
/// Error when one of the checks fail
pub async fn run_all<H: crate::app::Hooks>(
    app_context: &crate::app::AppContext,
    production: bool,
) -> Result<BTreeMap<Resource, Check>> {
    let mut checks = BTreeMap::from(
        #[cfg(feature = "with-db")]
        [(
            Resource::Database,
            check_db(&app_context.config.database).await,
        )],
        #[cfg(not(feature = "with-db"))]
        [],
    );

    if app_context.config.workers.mode == config::WorkerMode::BackgroundQueue {
        checks.insert(Resource::Queue, check_queue(&app_context.config).await);
    }

    // Add initializer checks
    if let Ok(initializers) = H::initializers(app_context).await {
        for initializer in initializers {
            if let Ok(Some(mut check)) = initializer.check(app_context).await {
                // Format the message to include "Initializer [name]: " prefix
                check.message = format!("Initializer {}: {}", initializer.name(), check.message);
                checks.insert(Resource::Initializer(initializer.name()), check);
            }
        }
    }

    if production {
        checks.insert(
            Resource::ProductionSafety,
            check_production_safety(&app_context.config),
        );
    } else {
        checks.insert(Resource::Deps, check_deps()?);
        checks.insert(Resource::SeaOrmCLI, check_seaorm_cli()?);
        checks.insert(
            Resource::PublishedLocoVersion,
            check_published_loco_version()?,
        );
    }

    Ok(checks)
}

/// Flags configuration that is fine in development and harmful in production.
///
/// The checks skipped in production — the dependency audit, the `sea-orm-cli`
/// probe, the crates.io version lookup — are all about the machine you develop
/// on, and they have nothing to say about a server. Dropping them without
/// putting anything in their place left `doctor` doing *less* work in the one
/// environment where being wrong is expensive. These are the settings that make
/// a production app unreachable, wipe its data, or leak its internals.
#[must_use]
pub fn check_production_safety(config: &Config) -> Check {
    let mut problems = Vec::new();

    // Loopback inside a container or VM is unreachable from anywhere else, and
    // the symptom — connection refused through the proxy — points at the proxy.
    let binding = config.server.binding.as_str();
    if binding == "localhost" || binding == "127.0.0.1" || binding == "::1" {
        problems.push(format!(
            "server.binding is `{binding}`, which only accepts connections from the machine \
             itself. Use `0.0.0.0` to serve traffic from outside it."
        ));
    }

    if config.logger.pretty_backtrace {
        problems.push(
            "logger.pretty_backtrace sets RUST_BACKTRACE=1, which costs performance and puts \
             source paths into your logs."
                .to_string(),
        );
    }

    #[cfg(feature = "with-db")]
    {
        if config.database.dangerously_truncate {
            problems
                .push("database.dangerously_truncate empties every table on startup.".to_string());
        }
        if config.database.dangerously_recreate {
            problems.push("database.dangerously_recreate drops the schema on startup.".to_string());
        }
    }

    if config
        .queue
        .as_ref()
        .is_some_and(QueueConfig::dangerously_flush)
    {
        problems.push("the queue is configured to flush all jobs on startup.".to_string());
    }

    if problems.is_empty() {
        Check {
            status: CheckStatus::Ok,
            message: "production settings: safe".to_string(),
            description: None,
        }
    } else {
        Check {
            status: CheckStatus::NotOk,
            message: "production settings: unsafe".to_string(),
            description: Some(problems.join("\n   ")),
        }
    }
}

/// Checks "blessed" / major dependencies in a Loco app Cargo.toml, and
/// recommend to update.
/// Only if a dep exists, we check it against a min version
/// # Errors
/// Returns error if fails
pub fn check_deps() -> Result<Check> {
    let crate_statuses =
        depcheck::check_crate_versions("Cargo.lock", get_min_dep_versions().clone())?;
    let mut report = String::new();
    let _ = write!(report, "Dependencies");
    let mut all_ok = true;

    for status in &crate_statuses {
        if let depcheck::VersionStatus::Invalid {
            version,
            min_version,
        } = &status.status
        {
            let _ = writeln!(
                report,
                "     {}: version {} does not meet minimum version {}",
                status.crate_name.yellow(),
                version.red(),
                min_version.green()
            );

            all_ok = false;
        }
    }
    Ok(Check {
        status: if all_ok {
            CheckStatus::Ok
        } else {
            CheckStatus::NotOk
        },
        message: report,
        description: None,
    })
}

/// Checks the database connection.
#[cfg(feature = "with-db")]
pub async fn check_db(config: &crate::config::Database) -> Check {
    let db_connection_failed = "DB connection: fails";
    let db_connection_success = "DB connection: success";
    match crate::db::connect(config).await {
        Ok(conn) => match conn.ping().await {
            Ok(()) => match crate::db::verify_access(&conn).await {
                Ok(()) => Check {
                    status: CheckStatus::Ok,
                    message: db_connection_success.to_string(),
                    description: None,
                },
                Err(err) => Check {
                    status: CheckStatus::NotOk,
                    message: db_connection_failed.to_string(),
                    description: Some(err.to_string()),
                },
            },
            Err(err) => Check {
                status: CheckStatus::NotOk,
                message: db_connection_failed.to_string(),
                description: Some(err.to_string()),
            },
        },
        Err(err) => Check {
            status: CheckStatus::NotOk,
            message: db_connection_failed.to_string(),
            description: Some(err.to_string()),
        },
    }
}

/// Checks the Redis connection.
pub async fn check_queue(config: &Config) -> Check {
    match bgworker::create_queue_provider(config).await {
        Ok(Some(queue)) => match queue.ping().await {
            Ok(()) => Check {
                status: CheckStatus::Ok,
                message: format!("{}: {}", queue.describe(), QUEUE_CONN_OK),
                description: None,
            },
            Err(err) => Check {
                status: CheckStatus::NotOk,
                message: format!("{}: {}", queue.describe(), QUEUE_CONN_FAILED),
                description: Some(err.to_string()),
            },
        },
        _ => Check {
            status: CheckStatus::NotConfigure,
            message: QUEUE_NOT_CONFIGURED.to_string(),
            description: None,
        },
    }
}

/// Checks the presence and version of `SeaORM` CLI.
/// # Panics
/// On illegal regex
/// # Errors
/// Fails when cannot check version
pub fn check_seaorm_cli() -> Result<Check> {
    match Command::new("sea-orm-cli").arg("--version").output() {
        Ok(out) => {
            let input = String::from_utf8_lossy(&out.stdout);
            // Extract the version from the input string
            let re = Regex::new(r"(\d+\.\d+\.\d+)").unwrap();

            let version_str = re
                .captures(&input)
                .and_then(|caps| caps.get(0))
                .map(|m| m.as_str())
                .ok_or("SeaORM CLI version not found")
                .map_err(Box::from)?;

            // Parse the extracted version using semver
            let version = Version::parse(version_str).map_err(Box::from)?;

            // Parse the minimum version for comparison
            let min_version = Version::parse(MIN_SEAORMCLI_VER).map_err(Box::from)?;

            // Compare the extracted version with the minimum version
            if version >= min_version {
                Ok(Check {
                    status: CheckStatus::Ok,
                    message: SEAORM_INSTALLED.to_string(),
                    description: None,
                })
            } else {
                Ok(Check {
                    status: CheckStatus::NotOk,
                    message: format!(
                        "SeaORM CLI minimal version is `{min_version}` (you have `{version}`). \
                         Run `cargo install sea-orm-cli` to update."
                    ),
                    description: Some(SEAORM_NOT_FIX.to_string()),
                })
            }
        }
        Err(_) => Ok(Check {
            status: CheckStatus::NotOk,
            message: SEAORM_NOT_INSTALLED.to_string(),
            description: Some(SEAORM_NOT_FIX.to_string()),
        }),
    }
}

/// Check for the latest Loco version
///
/// # Errors
///
/// This function will return an error if it fails
pub fn check_published_loco_version() -> Result<Check> {
    let compiled_version = env!("CARGO_PKG_VERSION");
    match check_cratesio_version("loco-rs", compiled_version) {
        Ok(Some(v)) => Ok(Check {
            status: CheckStatus::NotOk,
            message: format!("Loco version: `{compiled_version}`, latest version: `{v}`"),
            description: Some("It is recommended to upgrade your main Loco version.".to_string()),
        }),
        Ok(None) => Ok(Check {
            status: CheckStatus::Ok,
            message: "Loco version: latest".to_string(),
            description: None,
        }),
        Err(e) => Ok(Check {
            status: CheckStatus::NotOk,
            message: format!("Checking Loco version failed: {e}"),
            description: None,
        }),
    }
}

#[cfg(test)]
mod tests {
    use super::{check_production_safety, CheckStatus};
    use crate::config::Config;

    /// A production config with nothing wrong with it.
    fn config(overrides: &str) -> Config {
        let base = format!(
            "
logger:
  enable: true
  pretty_backtrace: false
  level: info
  format: json
server:
  port: 5150
  binding: 0.0.0.0
  host: https://example.com
  middlewares: {{}}
database:
  uri: sqlite://app.sqlite?mode=rwc
  enable_logging: false
  connect_timeout: 500
  idle_timeout: 500
  min_connections: 1
  max_connections: 10
  auto_migrate: true
  dangerously_truncate: false
  dangerously_recreate: false
{overrides}"
        );
        serde_yaml::from_str(&base).expect("test config parses")
    }

    #[test]
    fn a_sound_production_config_passes() {
        assert_eq!(check_production_safety(&config("")).status, CheckStatus::Ok);
    }

    /// The failure the deploy guide's "all green" used to hide: an app bound to
    /// loopback answers on the host and refuses every connection from outside it.
    #[test]
    fn a_loopback_binding_is_reported() {
        for binding in ["localhost", "127.0.0.1", "::1"] {
            let mut cfg = config("");
            cfg.server.binding = binding.to_string();
            let check = check_production_safety(&cfg);
            assert_eq!(
                check.status,
                CheckStatus::NotOk,
                "`{binding}` should be reported as unreachable from outside the host"
            );
            assert!(check.description.unwrap().contains("0.0.0.0"));
        }
    }

    #[test]
    fn destructive_database_flags_are_reported() {
        let mut cfg = config("");
        cfg.database.dangerously_truncate = true;
        let check = check_production_safety(&cfg);
        assert_eq!(check.status, CheckStatus::NotOk);
        assert!(check.description.unwrap().contains("empties every table"));

        let mut cfg = config("");
        cfg.database.dangerously_recreate = true;
        assert_eq!(check_production_safety(&cfg).status, CheckStatus::NotOk);
    }

    #[test]
    fn pretty_backtrace_is_reported() {
        let mut cfg = config("");
        cfg.logger.pretty_backtrace = true;
        let check = check_production_safety(&cfg);
        assert_eq!(check.status, CheckStatus::NotOk);
        assert!(check.description.unwrap().contains("RUST_BACKTRACE"));
    }

    /// Every problem is reported at once, so a deploy is not a sequence of
    /// one-at-a-time discoveries.
    #[test]
    fn all_problems_are_reported_together() {
        let mut cfg = config("");
        cfg.server.binding = "localhost".to_string();
        cfg.logger.pretty_backtrace = true;
        cfg.database.dangerously_truncate = true;

        let description = check_production_safety(&cfg)
            .description
            .expect("problems are described");
        assert_eq!(description.lines().count(), 3, "got:\n{description}");
    }
}