larust-cli 0.12.0

A Laravel-shaped web framework for Rust.
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
//! `xr deploy` - builds and publishes a release, according to `DEPLOY_TYPE`
//! (`.env`/the process environment; `"web"` by default). `deploy_web`
//! builds and publishes a production server release, then triggers a live
//! restart handoff against an already-running process - composing
//! machinery that already exists for `xr dev`/`xr restart` rather than
//! reimplementing any of it: `dev::build` (the JSON-artifact-discovery
//! `cargo build` wrapper, `--release` here instead of `xr dev`'s own debug
//! build), `release_slots::publish`/`prune` (the same `storage/releases/`
//! pointer-file convention, under the `"release"` prefix - kept in a
//! separate counting namespace from `xr dev`'s own `"dev"` slots, see
//! `release_slots.rs`'s own doc comment for why that matters), and the
//! same admin-channel `RESTART` protocol `xr restart` speaks. If nothing is
//! listening yet (the very first deploy), `--run` cold-starts the freshly
//! published release in the background instead of just publishing it and
//! waiting for a manual first start (`start_detached`) - every later `xr
//! deploy` finds it listening and hot-swaps it normally. `deploy_app`
//! (`DEPLOY_TYPE=app`) instead builds a native Tauri desktop bundle from
//! `src-tauri/` (scaffolded by `xr new --tauri`/`xr add tauri` - see
//! `scaffold.rs`/`add.rs`) - no restart handoff, since a desktop bundle has
//! no analogue for zero-downtime hot-swap.
//!
//! `--clean` runs `cargo clean --release` only after the web deployment
//! returns success, including any requested startup/restart step. Published
//! release slots survive; the next build recompiles dependencies.
//! `--clean-all` uses plain `cargo clean` to remove debug caches too. Desktop
//! builds reject both flags before building because their bundles live in
//! Cargo's release output directory.
//!
//! `DEPLOY_TYPE` is read directly from `.env`/the process environment,
//! never through `larust_core::Config` - same reasoning as `restart.rs`'s
//! own `APP_NAME` read: this runs in a separate `xr` process, outside the
//! target app's own compiled binary, so it can't call a function only that
//! binary's crate defines.
//!
//! `--service` is `--run`'s systemd-backed sibling for the identical
//! "nothing is listening to hand off to" branch: instead of
//! `start_detached`'s bare, unsupervised background process, it calls
//! `service::install()` (see that module's own doc comment for the full
//! `Restart=on-failure` reasoning) so the very first deploy is already
//! crash-and-reboot-safe, with no separate `xr service:install` step
//! needed afterward. Wins over `--run` when both are passed - starting the
//! app via *both* a bare detached process and a systemd unit would just
//! race each other for the same port. Same "no effect once something is
//! already listening" scope as `--run` - every later `xr deploy` still
//! just hot-swaps whatever's running, systemd-supervised or not.

use crate::admin_client;
use crate::dev::{app_name_default, build, resolve_app_port};
use crate::release_slots;
use crate::restart;
use crate::run::is_listening;
use crate::service;
use anyhow::{Context, Result};
use larust_core::__internal::admin;
use std::path::Path;

/// Separate from `xr dev`'s own `"dev"` prefix - see `release_slots.rs`'s
/// module doc comment for why sharing a namespace would be a real
/// correctness risk (a later dev session could prune away a real
/// production release).
const RELEASE_PREFIX: &str = "release";

pub fn run(run_if_idle: bool, install_service: bool, clean: bool, clean_all: bool) -> Result<()> {
    dotenvy::from_filename(".env").ok();
    let deploy_type = std::env::var("DEPLOY_TYPE").unwrap_or_else(|_| "web".to_string());

    match deploy_type.as_str() {
        "web" => {
            deploy_web(run_if_idle, install_service)?;
            let app_root = std::env::current_dir().context("reading current directory")?;
            if clean || clean_all {
                clean_build_artifacts(&app_root, clean_all)?;
            } else {
                maybe_prompt_and_clean(&app_root)?;
            }
            Ok(())
        }
        "app" => {
            anyhow::ensure!(
                !clean && !clean_all,
                "xr deploy --clean / --clean-all is only supported for DEPLOY_TYPE=web; desktop bundles live in Cargo's release directory and must be preserved"
            );
            if run_if_idle {
                println!(
                    "xr deploy: --run has no effect for DEPLOY_TYPE=app - a desktop bundle \
                     isn't something `xr deploy` starts for you"
                );
            }
            if install_service {
                println!(
                    "xr deploy: --service has no effect for DEPLOY_TYPE=app - a desktop bundle \
                     has no systemd analogue"
                );
            }
            deploy_app()
        }
        other => {
            anyhow::bail!("unrecognized DEPLOY_TYPE {other:?} - expected \"web\" or \"app\"")
        }
    }
}

/// Cargo resolves workspace/custom target directories and holds its build
/// lock. Web releases are already copied outside Cargo's build output.
fn clean_build_artifacts(app_root: &Path, all: bool) -> Result<()> {
    let command_label = if all {
        "cargo clean"
    } else {
        "cargo clean --release"
    };
    println!("xr deploy: cleaning build artifacts ({command_label})...");
    let mut command = std::process::Command::new("cargo");
    command.arg("clean").current_dir(app_root);
    if !all {
        command.arg("--release");
    }
    let status = command
        .status()
        .with_context(|| format!("release was deployed, but failed to run `{command_label}`"))?;
    anyhow::ensure!(
        status.success(),
        "release was deployed, but `{command_label}` exited with a non-zero status"
    );
    if all {
        println!("xr deploy: all build artifacts cleaned; development and deployment builds will rebuild dependencies");
    } else {
        println!(
            "xr deploy: release build artifacts cleaned; the next deploy will rebuild dependencies"
        );
    }
    Ok(())
}

/// The interactive counterpart to `--clean`/`--clean-all`, requested
/// directly alongside the `boot_release`/corrupted-release-fallback work
/// in this file: a deploy script that's easy to forget to pass either
/// flag to every time, when the operator would often just say "yes,
/// clean it" if actually asked. Reached only when *neither* flag was
/// already given - an explicit flag always wins outright and never
/// prompts, matching every other optional-confirmation flag already in
/// this crate (`xr upgrade --stop-running`, `xr add`'s own prompts).
///
/// Guarded on `stdin` actually being a real terminal - this is the one
/// load-bearing difference from `wizard.rs`'s/`add.rs`'s own
/// `dialoguer::Confirm` prompts, which never need this guard since those
/// commands are inherently interactive-only. `xr deploy` is routinely run
/// from CI, cron, or a deploy script's own non-interactive shell; asking
/// a question nobody can answer would either hang forever waiting for
/// input that will never arrive, or (piped from `/dev/null`) immediately
/// error - either way, a real regression for every automated deploy that
/// works fine today with no flag at all. Silently skips the prompt
/// (behaving exactly as today: no cleaning) in that case.
fn maybe_prompt_and_clean(app_root: &Path) -> Result<()> {
    use std::io::IsTerminal;
    if !std::io::stdin().is_terminal() {
        return Ok(());
    }

    // An interact() failure (an unusual terminal, an interrupted read)
    // is treated the same as "no" - this is an optional nicety layered on
    // top of an already-successful deploy, never something that should
    // make the overall command report failure.
    let should_clean = dialoguer::Confirm::with_theme(&dialoguer::theme::ColorfulTheme::default())
        .with_prompt("Clean up dev build artifacts (cargo clean --release) to save disk space?")
        .default(false)
        .interact()
        .unwrap_or(false);

    if should_clean {
        clean_build_artifacts(app_root, false)?;
    }
    Ok(())
}

fn deploy_web(run_if_idle: bool, install_service: bool) -> Result<()> {
    let app_root = std::env::current_dir().context("reading current directory")?;

    build_frontend_assets(&app_root)?;

    println!("xr deploy: building release...");
    let binary = build(&app_root, true)?
        .context("release build produced no binary artifact - check your app's [[bin]] target")?;

    let generation = release_slots::next_generation(&app_root, RELEASE_PREFIX);
    let slot = release_slots::publish(&app_root, &binary, RELEASE_PREFIX, generation)
        .context("failed to publish the release")?;
    release_slots::prune(&app_root, RELEASE_PREFIX, generation);
    println!(
        "xr deploy: published release {generation} at {}",
        slot.display()
    );

    let bytes = std::fs::metadata(&slot)
        .context("reading published release size")?
        .len();
    println!(
        "xr deploy: executable size {:.2} MiB; target/ is a build cache, not part of the runtime release",
        bytes as f64 / (1024.0 * 1024.0)
    );

    let app_name = std::env::var("APP_NAME").unwrap_or_else(|_| app_name_default());
    let address = admin::channel_address(&app_name);
    match admin_client::send_command(&address, admin::RESTART_COMMAND) {
        Ok(response) => restart::report(&response),
        Err(_) => {
            handle_unreachable_app(&app_root, &slot, generation, run_if_idle, install_service)
        }
    }
}

/// Reached whenever the admin-channel `RESTART` handoff above fails -
/// which, on its own, is ambiguous between two very different situations
/// this splits apart by actually checking the app's own port, rather than
/// treating both the same way the original, single-branch version of this
/// function used to:
///
/// - **Nothing is listening at all**: the legitimate, expected case for a
///   brand new app's very first deploy. The release is published and
///   ready; `--run`/`--service` start it, or the existing hint tells the
///   operator how to start it themselves. Still `Ok(())` - there's
///   genuinely nothing wrong here.
/// - **Something *is* listening on the port, but never answered the
///   admin-channel handoff**: reported directly, from a real production
///   incident - a release gets published, this prints a friendly-looking
///   message, and `xr deploy` exits `0`, while the actually-running app
///   keeps serving the *previous* release indefinitely, with nothing
///   about the command's own output or exit code distinguishing that from
///   a real, successful hot-swap. The most common cause: this app's own
///   `serve()` never opted into `GracefulShutdown { restart_channel:
///   true, .. }` in the first place (see `docs/deployment-and-desktop-
///   apps.md`'s "Opting into zero-downtime restarts" - deliberately not
///   enabled by `xr new` itself). A real error now, not a println - a
///   deploy that silently fails to actually update the live app is
///   exactly the kind of failure an automated pipeline must not read as
///   success.
fn handle_unreachable_app(
    app_root: &Path,
    slot: &Path,
    generation: u64,
    run_if_idle: bool,
    install_service: bool,
) -> Result<()> {
    let app_port = resolve_app_port(
        None,
        std::env::var("APP_PORT").ok().as_deref(),
        std::env::var("APP_URL").ok().as_deref(),
    );
    let addr = format!("127.0.0.1:{app_port}");

    if is_listening(&addr) {
        anyhow::bail!(
            "xr deploy: published release {generation}, but something is already listening on \
             {addr} that never responded on its admin channel - the release is ready, but the \
             LIVE APP WAS NOT UPDATED. The most likely cause: this app's own `serve()` hasn't \
             opted into `GracefulShutdown {{ restart_channel: true, .. }}` yet (see \
             docs/deployment-and-desktop-apps.md#opting-into-zero-downtime-restarts) - every \
             later `xr deploy` will hand off automatically once it has. Until then, restart \
             whatever's running on {addr} yourself to actually pick up this release."
        );
    }

    // Nothing listening at all - the ordinary "never started yet" case.
    // `install_service` checked first - see this module's own doc comment
    // for why it wins over `--run` when both are passed.
    if install_service {
        return service::install(None);
    }
    if run_if_idle {
        return start_detached(slot, app_root);
    }
    println!(
        "xr deploy: no running app found to hand off to - the release is published and ready. \
         Start the app once manually to pick it up, re-run with `--run` to have `xr deploy` \
         start it for you, or `--service` to also register it with systemd (crash- and \
         reboot-safe from the start); every later `xr deploy` will hand off to it with zero \
         downtime regardless."
    );
    Ok(())
}

/// Cold-starts a just-published release when nothing was running to hand
/// off to (`--run`, only ever reached on an app's very first deploy - every
/// later `xr deploy` finds this process listening on the admin channel and
/// hot-swaps it normally instead, the ordinary path above). Deliberately
/// detached, not supervised the way `lifecycle::handoff`'s own replacement-
/// spawning is (see that module's own doc comment on job-object linkage):
/// this process needs to keep running *after* `xr deploy` itself exits -
/// the opposite lifetime relationship a live handoff's replacement has to
/// its predecessor. No readiness confirmation is attempted (an ordinary
/// cold boot never announces one - see `Application::serve`'s own comment,
/// "a no-op on any ordinary boot" - that protocol exists only for the
/// handoff case) - same "fire and start it, no confirmation" bar the
/// existing "start the app once manually" message already sets.
///
/// `unmark_stdio_inheritable` (Windows only, called *before* `spawn`) is
/// not optional polish - without it, any caller that captures `xr deploy`'s
/// own stdout/stderr through a pipe (`Command::output()`, a CI step piping
/// its logs, `xr deploy --run > log.txt`) hangs forever waiting for that
/// pipe to reach EOF. Found via this exact scenario in this crate's own
/// `deploy_e2e.rs` test, not hypothetically: `CreateProcess`'s handle
/// inheritance is all-or-nothing per call, not per-handle - passing even
/// one `Stdio::null()` (needed so the detached child doesn't print into
/// whatever `xr deploy`'s own stdout happens to be) forces
/// `bInheritHandles = TRUE` for the *whole* spawn, which silently
/// duplicates every other currently-inheritable handle in this process
/// too, including the inherited write end of the caller's own capture
/// pipe - a handle this process needs to keep using, but never wanted the
/// long-lived detached child to also hold a stray copy of forever. A
/// plain `Stdio::null()` on the child's own three streams only controls
/// *which* handle occupies its stdio slots; it does nothing to stop this
/// unrelated duplication. No equivalent problem on Unix - `fork`+`exec`
/// there only inherits file descriptors explicitly kept open across
/// `exec`, not "every inheritable handle in the process" the way Win32
/// does.
pub(crate) fn start_detached(binary: &Path, app_root: &Path) -> Result<()> {
    #[cfg(windows)]
    unmark_stdio_inheritable();

    let child = std::process::Command::new(binary)
        .current_dir(app_root)
        .stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        // Read by `larust_core::Application::new()` (bare string literal
        // there too, matching `LARUST_DEV_RELOAD`'s own precedent - see
        // its own doc comment): defaults `LOG_CHANNEL` to `"file"` when
        // the user never set it explicitly, since the `Stdio::null()`
        // above means plain `stdout` logging would otherwise be silently
        // discarded for this app's entire life, not just this one
        // process - every later zero-downtime restart-handoff replacement
        // inherits its own stdout from its immediate predecessor, and
        // inherits this env var the same automatic way `Command` always
        // propagates its parent's environment.
        .env("LARUST_STDIO_DETACHED", "1")
        .spawn()
        .with_context(|| format!("failed to start {}", binary.display()))?;
    println!(
        "xr deploy: started the app in the background (pid {}) - give it a moment to finish \
         binding its port; every later `xr deploy` will hand off to it with zero downtime.",
        child.id()
    );
    Ok(())
}

/// Clears `HANDLE_FLAG_INHERIT` on this process's own stdout/stderr
/// handles - see `start_detached`'s own doc comment for why. Only ever
/// affects whether a *future* child inherits these handles, not whether
/// this process can keep writing to them, so there's nothing to restore
/// afterward: `xr deploy` has nothing left to print through them that
/// matters once the detached child is on its way up. `GetStdHandle`
/// returning `INVALID_HANDLE_VALUE`/null (stdout/stderr redirected to
/// something that was never a real inheritable handle to begin with, or
/// simply absent) is left alone rather than treated as an error - there is
/// then nothing this needs to protect.
#[cfg(windows)]
fn unmark_stdio_inheritable() {
    use windows_sys::Win32::Foundation::SetHandleInformation;
    use windows_sys::Win32::Foundation::{HANDLE, HANDLE_FLAG_INHERIT, INVALID_HANDLE_VALUE};
    use windows_sys::Win32::System::Console::{GetStdHandle, STD_ERROR_HANDLE, STD_OUTPUT_HANDLE};

    for which in [STD_OUTPUT_HANDLE, STD_ERROR_HANDLE] {
        // SAFETY: `GetStdHandle`/`SetHandleInformation` are ordinary Win32
        // calls with no preconditions beyond a valid handle value, which
        // this checks for before use.
        unsafe {
            let handle: HANDLE = GetStdHandle(which);
            if handle != INVALID_HANDLE_VALUE && !handle.is_null() {
                SetHandleInformation(handle, HANDLE_FLAG_INHERIT, 0);
            }
        }
    }
}

/// Builds a native desktop bundle via Tauri (`cargo tauri build`, run from
/// `src-tauri/`) - no release-slot publish or restart handoff (`deploy_web`'s
/// own second half): that machinery is zero-downtime hot-swap for an
/// already-running *server* process, which has no analogue for a desktop
/// bundle the user installs fresh each time.
fn deploy_app() -> Result<()> {
    let app_root = std::env::current_dir().context("reading current directory")?;

    let tauri_dir = app_root.join("src-tauri");
    anyhow::ensure!(
        tauri_dir.is_dir(),
        "DEPLOY_TYPE=app but this app has no src-tauri/ directory yet - run `xr add tauri` first"
    );

    // `cargo tauri build`'s bundler needs real icon files - `xr new --tauri`/
    // `xr add tauri` deliberately don't generate placeholder ones (see
    // `scaffold.rs`'s `write_tauri_scaffold` doc comment), so this is the
    // first point that actually needs them and fails with an install-style
    // hint, mirroring `audit()`'s own "if cargo-audit isn't installed" hint
    // in `main.rs`, rather than surfacing whatever cryptic error the
    // bundler itself would produce.
    let icons_present = tauri_dir
        .join("icons")
        .read_dir()
        .map(|mut entries| entries.next().is_some())
        .unwrap_or(false);
    anyhow::ensure!(
        icons_present,
        "no icons found in src-tauri/icons/ - run `cargo tauri icon <path-to-a-logo.png>` from \
         src-tauri/ once before your first build (generates every size the bundler needs)"
    );

    build_frontend_assets(&app_root)?;

    println!("xr deploy: building desktop bundle (cargo tauri build)...");
    let status = std::process::Command::new("cargo")
        .args(["tauri", "build"])
        .current_dir(&tauri_dir)
        .status()
        .context("failed to run `cargo tauri build`")?;

    if !status.success() {
        eprintln!(
            "\nIf tauri-cli isn't installed yet: cargo install tauri-cli --version \"^2.0.0\""
        );
        anyhow::bail!("cargo tauri build exited with a non-zero status");
    }

    println!("xr deploy: desktop bundle(s) published under src-tauri/target/release/bundle/");
    Ok(())
}

/// `node_modules` existing is the signal that this app actually uses the
/// Vite asset pipeline (`@vite(...)`/`@vitex(...)`, `xr convert`'s own
/// `package.json`/`vite.config.js` copy - see `convert.rs`'s notes on
/// that) and has already had `npm install` run at least once - an app
/// with no JS tooling at all has no `node_modules` and this is a silent
/// no-op for it, same as today. Called from `deploy_web` (runs before the
/// Rust release build - fail fast on the cheaper step, and on failure
/// stops the deploy outright, since a broken asset build, Tailwind
/// included, must never let a release ship with stale or missing CSS/JS)
/// and from `xr build` (`build.rs`), standalone - not `deploy`-specific
/// despite living in this module, so its own printed message doesn't
/// assume which command called it.
pub(crate) fn build_frontend_assets(app_root: &Path) -> Result<()> {
    if !app_root.join("node_modules").is_dir() {
        return Ok(());
    }

    println!("xr: building frontend assets (npm run build)...");
    // On Windows, `npm` is a `.cmd` shim, not a real `.exe` -
    // `Command::new("npm")` fails with "program not found" because
    // `CreateProcess` doesn't consult `PATHEXT` the way a shell's own
    // command lookup does; `npm.cmd` (still resolved via `PATH`) is the
    // fix. Elsewhere `npm` is a real executable, so the bare name works.
    let npm = if cfg!(windows) { "npm.cmd" } else { "npm" };
    let status = std::process::Command::new(npm)
        .args(["run", "build"])
        .current_dir(app_root)
        .status()
        .with_context(|| format!("failed to run `{npm} run build`"))?;

    anyhow::ensure!(
        status.success(),
        "`npm run build` exited with a non-zero status"
    );
    Ok(())
}