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
//! Manages the app's `storage/releases/` directory: after each successful
//! build, the freshly-linked binary is copied to a fresh, monotonically-
//! increasing slot (`{prefix}-1`, `{prefix}-2`, …), and `storage/releases/
//! current` is updated to point at it - reusing the exact same pointer
//! convention a real production deploy uses (see `larust_core::
//! __internal::handoff::resolve_binary_path`).
//!
//! `prefix` keeps `xr dev`'s own throwaway slots (`"dev"`) and `xr
//! deploy`'s real production releases (`"release"`) in separate counting
//! namespaces, sharing one `storage/releases/` directory and one pointer
//! file - without it, a dev session started *after* a real deploy could
//! increment past (and then `prune` away) the production release slot the
//! pointer file still points at.
//!
//! Never reuses a slot: a 2-slot rotation would let generation 3 try to
//! overwrite the file generation 1 is still running from - only
//! *eventually* freed once generation 1 finishes draining, not guaranteed
//! by the time a fast incremental rebuild completes. A monotonic counter
//! makes that race structurally impossible, at the cost of leaving old
//! slots behind - cleaned up separately by `prune`.

use anyhow::{Context, Result};
use larust_core::__internal::handoff::RELEASE_POINTER_PATH;
use std::path::{Path, PathBuf};

/// How many of the most recent generations to keep on disk. Anything
/// older is pruned best-effort after each publish - old enough that the
/// process still running from it (bounded by the dev-specific, short
/// drain timeout) has almost certainly already exited by the time it
/// would be pruned, but pruning is never load-bearing for correctness
/// either way (a still-open file handle on a to-be-deleted slot just
/// means that prune attempt no-ops).
const KEEP_GENERATIONS: u64 = 3;

pub(crate) fn releases_dir(app_root: &Path) -> PathBuf {
    app_root.join("storage").join("releases")
}

fn slot_path(releases_dir: &Path, prefix: &str, generation: u64, source: &Path) -> PathBuf {
    let mut name = format!("{prefix}-{generation}");
    if let Some(ext) = source.extension().and_then(|e| e.to_str()) {
        name.push('.');
        name.push_str(ext);
    }
    releases_dir.join(name)
}

/// The next unused generation number for `prefix` - one past the highest
/// of whatever [`existing_generations`] finds already on disk. Unlike `xr
/// dev`'s own in-memory counter (kept for the lifetime of one long-running
/// watch session), `xr deploy` is a one-shot process with nothing to
/// remember a counter in between invocations, so it has to ask disk
/// instead. `1` if nothing matching `prefix` exists yet.
pub(crate) fn next_generation(app_root: &Path, prefix: &str) -> u64 {
    existing_generations(app_root, prefix)
        .first()
        .map_or(1, |(generation, _)| generation + 1)
}

/// Every existing `{prefix}-N[.ext]` slot already on disk, sorted by
/// generation *descending* (most recent first) - the order
/// `boot_release`'s own validate-and-fall-back walk needs: try the
/// pointer's own generation first, then progressively older ones until
/// one actually passes. An empty vec if the releases directory doesn't
/// exist yet (nothing ever published) is not an error - every caller
/// here already treats "no slots at all" as a normal, unremarkable case.
pub(crate) fn existing_generations(app_root: &Path, prefix: &str) -> Vec<(u64, PathBuf)> {
    let releases_dir = releases_dir(app_root);
    let Ok(entries) = std::fs::read_dir(&releases_dir) else {
        return Vec::new();
    };

    let mut generations: Vec<(u64, PathBuf)> = entries
        .flatten()
        .filter_map(|entry| {
            let name = entry.file_name();
            let name = name.to_str()?.to_string();
            let rest = name.strip_prefix(prefix)?.strip_prefix('-')?;
            let generation_str = rest.split('.').next().unwrap_or(rest);
            let generation = generation_str.parse::<u64>().ok()?;
            Some((generation, entry.path()))
        })
        .collect();
    generations.sort_by_key(|(generation, _)| std::cmp::Reverse(*generation));
    generations
}

/// Copies `source` (the file `cargo build`'s linker just wrote to) into a
/// fresh release slot and updates the pointer to it. Returns the slot's
/// path - the caller spawns the running server from *this* path, never
/// from `source` directly, so the next build's linker never finds that
/// exact file held open by a running process.
pub(crate) fn publish(
    app_root: &Path,
    source: &Path,
    prefix: &str,
    generation: u64,
) -> Result<PathBuf> {
    let releases_dir = releases_dir(app_root);
    std::fs::create_dir_all(&releases_dir)
        .with_context(|| format!("failed to create {}", releases_dir.display()))?;

    let slot = slot_path(&releases_dir, prefix, generation, source);
    std::fs::copy(source, &slot)
        .with_context(|| format!("failed to copy {} to {}", source.display(), slot.display()))?;
    set_executable(&slot)
        .with_context(|| format!("failed to make {} executable", slot.display()))?;

    let pointer = app_root.join(RELEASE_POINTER_PATH);
    std::fs::write(&pointer, slot.to_string_lossy().as_bytes())
        .with_context(|| format!("failed to write {}", pointer.display()))?;

    Ok(slot)
}

/// `std::fs::copy` already preserves the source file's own permission bits
/// on Unix (confirmed against its own documented behavior) - in the
/// ordinary case, `cargo build`'s own output is already executable, so
/// this is usually a no-op in practice. Set explicitly anyway, not left to
/// chance: reported directly, from a real production incident, that an
/// unrelated admin-panel "fix account permissions" tool reset an entire
/// deployed app's files to `644` (no execute bit at all) well *after*
/// publish - `systemd` then failed every subsequent restart with
/// `status=203/EXEC`, with no way to recover short of a human noticing and
/// manually `chmod +x`-ing the release by hand. This can't undo something
/// that already happened to an *old*, already-published release sitting on
/// disk, but it does mean every *new* publish - the next `xr deploy`, which
/// is also the actual fix for a release an external tool broke this way -
/// unconditionally produces a runnable binary regardless of whatever the
/// copied file's own permissions happened to be, rather than silently
/// inheriting a non-executable source (a restrictive `umask` in the build
/// environment would hit this on the *first* deploy, not just after some
/// later external interference).
///
/// A no-op on Windows - there's no executable-bit concept to set there at
/// all (a `.exe` extension is what makes a file runnable, unaffected by
/// anything this function could do).
fn set_executable(path: &Path) -> Result<()> {
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755))?;
    }
    #[cfg(not(unix))]
    {
        let _ = path;
    }
    Ok(())
}

/// Best-effort: deletes any `{prefix}-*` slot older than the last
/// `KEEP_GENERATIONS`. Never fails the caller - a slot that can't be
/// removed (e.g. still held open on Windows by a process that hasn't
/// finished draining yet) is reported and left for the next prune attempt. The current pointer is
/// always preserved even if it references an older generation.
pub(crate) fn prune(app_root: &Path, prefix: &str, current_generation: u64) {
    if current_generation <= KEEP_GENERATIONS {
        return;
    }
    let oldest_to_keep = current_generation - (KEEP_GENERATIONS - 1);
    let releases_dir = releases_dir(app_root);
    let entries = match std::fs::read_dir(&releases_dir) {
        Ok(entries) => entries,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return,
        Err(error) => {
            eprintln!(
                "xr: could not inspect {} for old releases: {error}",
                releases_dir.display()
            );
            return;
        }
    };

    // Preserve the published pointer even when it references an older slot.
    let current = match std::fs::read_to_string(app_root.join(RELEASE_POINTER_PATH)) {
        Ok(path) => {
            let path = PathBuf::from(path.trim());
            let path = if path.is_absolute() {
                path
            } else {
                app_root.join(path)
            };
            Some(path.canonicalize().unwrap_or(path))
        }
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
        Err(error) => {
            eprintln!("xr: could not read the current release pointer: {error}; skipping pruning");
            return;
        }
    };

    for entry in entries.flatten() {
        let name = entry.file_name();
        let Some(name) = name.to_str() else { continue };
        let Some(generation_str) = name
            .strip_prefix(prefix)
            .and_then(|rest| rest.strip_prefix('-'))
            .map(|rest| rest.split('.').next().unwrap_or(rest))
        else {
            continue;
        };
        let Ok(generation) = generation_str.parse::<u64>() else {
            continue;
        };
        let path = entry.path();
        if generation < oldest_to_keep
            && current.as_ref() != Some(&path.canonicalize().unwrap_or_else(|_| path.clone()))
        {
            if let Err(error) = std::fs::remove_file(&path) {
                eprintln!(
                    "xr: could not prune old release {}: {error}; cleanup will retry on the next prune pass",
                    path.display()
                );
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn publish_copies_to_a_monotonic_slot_and_updates_the_pointer() {
        let app_root = tempfile::tempdir().unwrap();
        let source = app_root.path().join("built.exe");
        std::fs::write(&source, b"generation-1-binary").unwrap();

        let slot = publish(app_root.path(), &source, "dev", 1).unwrap();
        assert_eq!(slot, releases_dir(app_root.path()).join("dev-1.exe"));
        assert_eq!(std::fs::read(&slot).unwrap(), b"generation-1-binary");

        let pointer = app_root.path().join(RELEASE_POINTER_PATH);
        assert_eq!(
            std::fs::read_to_string(&pointer).unwrap(),
            slot.to_string_lossy()
        );
    }

    /// The actual regression guard for the real incident `set_executable`'s
    /// own doc comment describes: even when the *source* file isn't
    /// executable at all (a restrictive build-environment `umask`, or -
    /// the case actually reported - some other tool having already reset
    /// permissions), `publish` must still hand back a runnable binary,
    /// not silently inherit the source's own non-executable state via a
    /// bare `std::fs::copy`.
    #[cfg(unix)]
    #[test]
    fn publish_makes_the_release_executable_even_when_the_source_was_not() {
        use std::os::unix::fs::PermissionsExt;

        let app_root = tempfile::tempdir().unwrap();
        let source = app_root.path().join("built");
        std::fs::write(&source, b"gen-1").unwrap();
        std::fs::set_permissions(&source, std::fs::Permissions::from_mode(0o644)).unwrap();

        let slot = publish(app_root.path(), &source, "dev", 1).unwrap();

        let mode = std::fs::metadata(&slot).unwrap().permissions().mode();
        assert_eq!(
            mode & 0o777,
            0o755,
            "published release must be executable regardless of the source file's own mode"
        );
    }

    #[test]
    fn publish_never_reuses_a_slot_across_generations() {
        let app_root = tempfile::tempdir().unwrap();
        let source = app_root.path().join("built");
        std::fs::write(&source, b"gen-1").unwrap();
        let slot_1 = publish(app_root.path(), &source, "dev", 1).unwrap();

        std::fs::write(&source, b"gen-2").unwrap();
        let slot_2 = publish(app_root.path(), &source, "dev", 2).unwrap();

        assert_ne!(slot_1, slot_2);
        // The first slot's own contents are untouched by the second publish
        // -- exactly the property that keeps a still-running generation-1
        // process safe to keep serving from while generation 2 is copied.
        assert_eq!(std::fs::read(&slot_1).unwrap(), b"gen-1");
        assert_eq!(std::fs::read(&slot_2).unwrap(), b"gen-2");
    }

    #[test]
    fn publish_keeps_dev_and_release_slots_in_separate_namespaces() {
        // The whole reason `publish`/`prune`/`next_generation` take a
        // `prefix`: a real deploy's release must never collide with (or
        // be pruned away by) a `dev-N` slot counted independently.
        let app_root = tempfile::tempdir().unwrap();
        let source = app_root.path().join("built");
        std::fs::write(&source, b"prod-1").unwrap();

        let dev_slot = publish(app_root.path(), &source, "dev", 1).unwrap();
        let release_slot = publish(app_root.path(), &source, "release", 1).unwrap();

        assert_ne!(dev_slot, release_slot);
        assert_eq!(
            release_slot,
            releases_dir(app_root.path()).join("release-1")
        );
    }

    #[test]
    fn next_generation_starts_at_one_with_nothing_on_disk() {
        let app_root = tempfile::tempdir().unwrap();
        assert_eq!(next_generation(app_root.path(), "release"), 1);
    }

    #[test]
    fn next_generation_continues_from_the_highest_existing_slot() {
        let app_root = tempfile::tempdir().unwrap();
        let source = app_root.path().join("built.exe");
        std::fs::write(&source, b"x").unwrap();
        publish(app_root.path(), &source, "release", 1).unwrap();
        publish(app_root.path(), &source, "release", 2).unwrap();

        assert_eq!(next_generation(app_root.path(), "release"), 3);
        // A `dev-N` slot in the same directory doesn't affect the
        // `release` prefix's own counting namespace.
        publish(app_root.path(), &source, "dev", 9).unwrap();
        assert_eq!(next_generation(app_root.path(), "release"), 3);
        assert_eq!(next_generation(app_root.path(), "dev"), 10);
    }

    #[test]
    fn existing_generations_is_empty_with_nothing_on_disk() {
        let app_root = tempfile::tempdir().unwrap();
        assert_eq!(existing_generations(app_root.path(), "release"), vec![]);
    }

    #[test]
    fn existing_generations_sorts_descending_and_ignores_other_prefixes() {
        let app_root = tempfile::tempdir().unwrap();
        let source = app_root.path().join("built.exe");
        std::fs::write(&source, b"x").unwrap();
        publish(app_root.path(), &source, "release", 1).unwrap();
        publish(app_root.path(), &source, "release", 3).unwrap();
        publish(app_root.path(), &source, "release", 2).unwrap();
        publish(app_root.path(), &source, "dev", 99).unwrap();

        let generations: Vec<u64> = existing_generations(app_root.path(), "release")
            .into_iter()
            .map(|(generation, _)| generation)
            .collect();
        assert_eq!(generations, vec![3, 2, 1]);
    }

    #[test]
    fn prune_removes_slots_older_than_the_keep_window() {
        let app_root = tempfile::tempdir().unwrap();
        let releases_dir = releases_dir(app_root.path());
        std::fs::create_dir_all(&releases_dir).unwrap();
        for generation in 1..=5u64 {
            std::fs::write(releases_dir.join(format!("dev-{generation}")), b"x").unwrap();
        }

        prune(app_root.path(), "dev", 5);

        // KEEP_GENERATIONS == 3, current generation 5 -> oldest kept is 3.
        assert!(!releases_dir.join("dev-1").exists());
        assert!(!releases_dir.join("dev-2").exists());
        assert!(releases_dir.join("dev-3").exists());
        assert!(releases_dir.join("dev-4").exists());
        assert!(releases_dir.join("dev-5").exists());
    }

    #[test]
    fn prune_does_nothing_while_still_within_the_keep_window() {
        let app_root = tempfile::tempdir().unwrap();
        let releases_dir = releases_dir(app_root.path());
        std::fs::create_dir_all(&releases_dir).unwrap();
        std::fs::write(releases_dir.join("dev-1"), b"x").unwrap();

        prune(app_root.path(), "dev", 2);

        assert!(releases_dir.join("dev-1").exists());
    }

    #[test]
    fn prune_ignores_non_matching_file_names() {
        let app_root = tempfile::tempdir().unwrap();
        let releases_dir = releases_dir(app_root.path());
        std::fs::create_dir_all(&releases_dir).unwrap();
        std::fs::write(releases_dir.join("current"), b"whatever").unwrap();

        prune(app_root.path(), "dev", 10);

        assert!(releases_dir.join("current").exists());
    }

    #[test]
    fn prune_with_one_prefix_never_removes_another_prefixs_slots() {
        let app_root = tempfile::tempdir().unwrap();
        let releases_dir = releases_dir(app_root.path());
        std::fs::create_dir_all(&releases_dir).unwrap();
        std::fs::write(releases_dir.join("release-1"), b"x").unwrap();
        for generation in 1..=5u64 {
            std::fs::write(releases_dir.join(format!("dev-{generation}")), b"x").unwrap();
        }

        prune(app_root.path(), "dev", 5);

        // A real production release is never touched by `xr dev`'s own
        // prune pass, regardless of generation number.
        assert!(releases_dir.join("release-1").exists());
    }
    #[test]
    fn pruning_after_each_publish_keeps_exactly_three_slots() {
        let root = tempfile::tempdir().unwrap();
        let source = root.path().join("built.exe");
        std::fs::write(&source, b"binary").unwrap();
        for generation in 1..=20 {
            publish(root.path(), &source, "dev", generation).unwrap();
            prune(root.path(), "dev", generation);
        }
        let dir = releases_dir(root.path());
        let slots = std::fs::read_dir(&dir)
            .unwrap()
            .flatten()
            .filter(|entry| entry.file_name().to_string_lossy().starts_with("dev-"))
            .count();
        assert_eq!(slots, 3);
        for generation in 18..=20 {
            assert!(dir.join(format!("dev-{generation}.exe")).exists());
        }
    }

    #[test]
    fn prune_preserves_an_old_slot_referenced_by_current() {
        let root = tempfile::tempdir().unwrap();
        let source = root.path().join("built.exe");
        std::fs::write(&source, b"binary").unwrap();
        let old = publish(root.path(), &source, "dev", 1).unwrap();
        let dir = releases_dir(root.path());
        std::fs::write(dir.join("dev-2.exe"), b"stale").unwrap();
        prune(root.path(), "dev", 10);
        assert!(old.exists());
        assert!(!dir.join("dev-2.exe").exists());
    }

    #[test]
    fn prune_retries_a_previously_unremovable_slot() {
        let root = tempfile::tempdir().unwrap();
        let dir = releases_dir(root.path());
        std::fs::create_dir_all(dir.join("dev-1")).unwrap();
        // remove_file cannot remove a directory; failure must not abort pruning.
        std::fs::write(dir.join("dev-2"), b"stale").unwrap();
        prune(root.path(), "dev", 10);
        assert!(dir.join("dev-1").exists());
        assert!(!dir.join("dev-2").exists());
        std::fs::remove_dir(dir.join("dev-1")).unwrap();
        std::fs::write(dir.join("dev-1"), b"unlocked").unwrap();
        prune(root.path(), "dev", 10);
        assert!(!dir.join("dev-1").exists());
    }
}