snip-sync 0.2.0

gRPC sync server for snp snippet manager
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
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
//! Binary-first self-update support for `snip-sync`.
//!
//! crates.io selects the stable version, while the exact component GitHub tag
//! supplies the binary and checksum. The running server is updated only after
//! the candidate has passed integrity and identity checks.
//!
//! NOTE (Plans 014 and 017): this updater intentionally still shells out to
//! external `curl` instead of sharing `snp`'s in-process eggfetch-core
//! transport. Plan 017's controlled same-toolchain lean `eggfetch-core 0.2.0`
//! trial grew this deliberately small server binary from 3,833,152 to
//! 5,145,224 bytes (+34.23%), past the plan's 10% material-growth gate. The
//! server remains on curl; do not consolidate this adapter without re-running
//! the measurement and preserving equivalent updater behavior.

use semver::Version;
use serde::Deserialize;
use sha2::{Digest, Sha256};
use std::fs::{self, File, OpenOptions};
use std::io::Read;
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

const CRATE_NAME: &str = "snip-sync";
const BINARY_NAME: &str = "snip-sync";
const CRATES_API_URL: &str = "https://crates.io/api/v1/crates/{crate}";
const RELEASE_BASE_URL: &str = "https://github.com/eggstack/snip-it/releases/download";
const MAX_METADATA_BYTES: u64 = 1024 * 1024;
const MAX_BINARY_BYTES: u64 = 256 * 1024 * 1024;

#[derive(Debug, Deserialize)]
struct CratesResponse {
    #[serde(rename = "crate")]
    crate_info: CrateInfo,
}

#[derive(Debug, Deserialize)]
struct CrateInfo {
    max_version: String,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum HostTarget {
    Prebuilt(&'static str),
    SourceOnly(&'static str),
}

#[derive(Debug)]
enum FetchError {
    NotFound,
    Failed(String),
}

pub fn run(dry_run: bool, _locked: bool) -> Result<(), String> {
    let executable = current_executable()?;
    let current = current_version()?;
    let lifecycle = snip_sync::startup::update_lifecycle()?;

    println!("Checking for snip-sync updates...");
    let latest = latest_crates_version()?;
    if latest <= current {
        println!("snip-sync {current} is already up to date.");
        return Ok(());
    }

    println!("Update available: snip-sync {current} -> {latest}");
    if dry_run {
        print_dry_run(&latest, lifecycle);
        return Ok(());
    }

    ensure_destination_writable(&executable)?;
    let workdir = tempfile::tempdir()
        .map_err(|e| format!("could not create update staging directory: {e}"))?;
    let target = host_target(std::env::consts::OS, std::env::consts::ARCH);
    let (candidate, source) = match target {
        Some(HostTarget::Prebuilt(target)) => {
            match download_candidate(&latest, target, workdir.path())? {
                DownloadedCandidate::Ready(path) => (path, "GitHub release binary"),
                DownloadedCandidate::MissingAsset => {
                    println!("No prebuilt asset is published for {target}; using Cargo fallback.");
                    (cargo_candidate(&latest, workdir.path())?, "Cargo fallback")
                }
            }
        }
        Some(HostTarget::SourceOnly(target)) => {
            println!("Target {target} is source-only; using Cargo fallback.");
            (cargo_candidate(&latest, workdir.path())?, "Cargo fallback")
        }
        None => {
            println!("This host has no supported prebuilt target; using Cargo fallback.");
            (cargo_candidate(&latest, workdir.path())?, "Cargo fallback")
        }
    };
    validate_candidate(&candidate, &latest)?;

    #[cfg(windows)]
    if matches!(
        lifecycle,
        snip_sync::startup::UpdateLifecycle::ManagedRunning(_)
            | snip_sync::startup::UpdateLifecycle::DirectRunning
    ) {
        stop_running_server(&executable)?;
    }

    replace_installed_executable(&candidate, &executable, workdir.path(), lifecycle)?;

    #[cfg(not(windows))]
    if let Err(error) = snip_sync::startup::restart_after_update(&executable, lifecycle, false) {
        return Err(format_partial_restart_error(&error));
    }

    println!("Updated snip-sync {current} -> {latest} (source: {source}).");
    Ok(())
}

fn current_version() -> Result<Version, String> {
    Version::parse(env!("CARGO_PKG_VERSION")).map_err(|e| format!("invalid current version: {e}"))
}

fn print_dry_run(latest: &Version, lifecycle: snip_sync::startup::UpdateLifecycle) {
    match host_target(std::env::consts::OS, std::env::consts::ARCH) {
        Some(HostTarget::Prebuilt(target)) => println!(
            "Dry run: would try snip-sync-{target} at exact tag {}.",
            component_tag(latest)
        ),
        Some(HostTarget::SourceOnly(target)) => println!(
            "Dry run: target {target} is source-only; would run exact-version Cargo fallback."
        ),
        None => {
            println!("Dry run: host target is unsupported; would run exact-version Cargo fallback.")
        }
    }
    println!(
        "Dry run: server lifecycle state is {lifecycle:?}; no files, processes, or services were changed."
    );
}

fn current_executable() -> Result<PathBuf, String> {
    let path = std::env::current_exe()
        .map_err(|e| format!("could not locate the running executable: {e}"))?;
    fs::canonicalize(&path).map_err(|e| {
        format!(
            "could not resolve the running executable {}: {e}",
            path.display()
        )
    })
}

fn update_endpoint(name: &str, default: &str) -> String {
    #[cfg(feature = "test-helpers")]
    {
        std::env::var(name).unwrap_or_else(|_| default.to_owned())
    }
    #[cfg(not(feature = "test-helpers"))]
    {
        let _ = name;
        default.to_owned()
    }
}

fn validate_https_url(url: &str) -> Result<(), FetchError> {
    #[cfg(feature = "test-helpers")]
    if url.starts_with("http://") {
        return Ok(());
    }
    if !url.starts_with("https://") {
        return Err(FetchError::Failed(format!(
            "insecure or unsupported URL scheme rejected: {url}"
        )));
    }
    Ok(())
}

fn curl_protocol() -> &'static str {
    #[cfg(feature = "test-helpers")]
    {
        "=http,https"
    }
    #[cfg(not(feature = "test-helpers"))]
    {
        "=https"
    }
}

fn fetch_bytes(url: &str) -> Result<Vec<u8>, FetchError> {
    validate_https_url(url)?;
    let output = Command::new("curl")
        .args([
            "--silent",
            "--show-error",
            "--location",
            "--proto",
            curl_protocol(),
            "--tlsv1.2",
            "--connect-timeout",
            "10",
            "--max-time",
            "60",
            "--max-filesize",
            &MAX_METADATA_BYTES.to_string(),
            "--user-agent",
            "snip-it-update",
            "--write-out",
            "\n%{http_code}",
            url,
        ])
        .output()
        .map_err(|e| FetchError::Failed(format!("could not run curl: {e}")))?;
    if output.stdout.len() < 4 {
        return Err(FetchError::Failed(format!(
            "curl returned no HTTP status ({}): {}",
            output.status,
            String::from_utf8_lossy(&output.stderr).trim()
        )));
    }
    let status_start = output.stdout.len() - 3;
    let status = String::from_utf8_lossy(&output.stdout[status_start..])
        .parse::<u16>()
        .map_err(|_| FetchError::Failed("curl returned an invalid HTTP status".into()))?;
    let body = &output.stdout[..status_start - 1];
    match status {
        200..=299 => Ok(body.to_vec()),
        404 => Err(FetchError::NotFound),
        _ => Err(FetchError::Failed(format!(
            "HTTP {status}: {}",
            String::from_utf8_lossy(&output.stderr).trim()
        ))),
    }
}

fn fetch_file(url: &str, path: &Path) -> Result<(), FetchError> {
    validate_https_url(url)?;
    let output_path = path
        .to_str()
        .ok_or_else(|| FetchError::Failed("staging path is not UTF-8".into()))?;
    let output = Command::new("curl")
        .args([
            "--silent",
            "--show-error",
            "--location",
            "--proto",
            curl_protocol(),
            "--tlsv1.2",
            "--connect-timeout",
            "10",
            "--max-time",
            "60",
            "--max-filesize",
            &MAX_BINARY_BYTES.to_string(),
            "--user-agent",
            "snip-it-update",
            "--output",
            output_path,
            "--write-out",
            "%{http_code}",
            url,
        ])
        .output()
        .map_err(|e| FetchError::Failed(format!("could not run curl: {e}")))?;
    let status = String::from_utf8_lossy(&output.stdout)
        .trim()
        .parse::<u16>()
        .map_err(|_| FetchError::Failed("curl returned an invalid HTTP status".into()))?;
    match status {
        200..=299 => Ok(()),
        404 => Err(FetchError::NotFound),
        _ => Err(FetchError::Failed(format!(
            "HTTP {status}: {}",
            String::from_utf8_lossy(&output.stderr).trim()
        ))),
    }
}

fn fetch_error_message(error: FetchError) -> String {
    match error {
        FetchError::NotFound => "requested update metadata was not found".into(),
        FetchError::Failed(message) => message,
    }
}

fn latest_crates_version() -> Result<Version, String> {
    let template = update_endpoint("SNIP_UPDATE_CRATES_API_URL", CRATES_API_URL);
    let url = template.replace("{crate}", CRATE_NAME);
    let body = fetch_bytes(&url).map_err(fetch_error_message)?;
    let response: CratesResponse = serde_json::from_slice(&body)
        .map_err(|e| format!("could not parse crates.io response: {e}"))?;
    let version = Version::parse(&response.crate_info.max_version).map_err(|e| {
        format!(
            "crates.io returned invalid version {:?}: {e}",
            response.crate_info.max_version
        )
    })?;
    if !version.pre.is_empty() {
        return Err(format!(
            "crates.io returned prerelease version {}; a stable release is required",
            version
        ));
    }
    Ok(version)
}

pub(crate) fn host_target(os: &str, arch: &str) -> Option<HostTarget> {
    match (os, arch) {
        ("linux", "x86_64") => Some(HostTarget::Prebuilt("x86_64-unknown-linux-gnu")),
        ("linux", "aarch64") => Some(HostTarget::Prebuilt("aarch64-unknown-linux-gnu")),
        ("linux", "arm") => Some(HostTarget::SourceOnly("armv7-unknown-linux-gnueabihf")),
        ("macos", "x86_64") => Some(HostTarget::Prebuilt("x86_64-apple-darwin")),
        ("macos", "aarch64") => Some(HostTarget::Prebuilt("aarch64-apple-darwin")),
        ("windows", "x86_64") => Some(HostTarget::Prebuilt("x86_64-pc-windows-msvc")),
        ("windows", "aarch64") => Some(HostTarget::SourceOnly("aarch64-pc-windows-msvc")),
        _ => None,
    }
}

fn component_tag(version: &Version) -> String {
    format!("snip-sync-v{version}")
}

fn asset_name(target: &str) -> String {
    let suffix = if cfg!(windows) { ".exe" } else { "" };
    format!("{BINARY_NAME}-{target}{suffix}")
}

enum DownloadedCandidate {
    Ready(PathBuf),
    MissingAsset,
}

fn download_candidate(
    version: &Version,
    target: &str,
    staging: &Path,
) -> Result<DownloadedCandidate, String> {
    let asset = asset_name(target);
    let base = update_endpoint("SNIP_UPDATE_RELEASE_BASE_URL", RELEASE_BASE_URL)
        .trim_end_matches('/')
        .to_owned();
    let binary_url = format!("{base}/{}/{asset}", component_tag(version));
    let candidate = staging.join(&asset);
    match fetch_file(&binary_url, &candidate) {
        Err(FetchError::NotFound) => return Ok(DownloadedCandidate::MissingAsset),
        Err(error) => {
            return Err(format!(
                "could not download {asset}: {}",
                fetch_error_message(error)
            ));
        }
        Ok(()) => {}
    }
    let checksum_url = format!("{binary_url}.sha256");
    let checksum = fetch_bytes(&checksum_url).map_err(|error| {
        format!(
            "could not download checksum for {asset}: {}",
            fetch_error_message(error)
        )
    })?;
    verify_checksum(&candidate, &checksum, &asset)?;
    make_executable(&candidate)?;
    Ok(DownloadedCandidate::Ready(candidate))
}

fn verify_checksum(path: &Path, sidecar: &[u8], expected_name: &str) -> Result<(), String> {
    let text = std::str::from_utf8(sidecar)
        .map_err(|_| "checksum sidecar is not valid UTF-8".to_string())?;
    let mut lines = text.lines();
    let line = lines
        .next()
        .ok_or_else(|| "checksum sidecar is empty".to_string())?;
    if lines.next().is_some() {
        return Err("checksum sidecar must contain exactly one line".into());
    }
    let fields: Vec<&str> = line.split_whitespace().collect();
    if fields.len() != 2
        || fields[1] != expected_name
        || fields[0].len() != 64
        || !fields[0].bytes().all(|byte| byte.is_ascii_hexdigit())
    {
        return Err(format!(
            "checksum sidecar has invalid format; expected '<64-hex-digest>  {expected_name}'"
        ));
    }
    let mut file =
        File::open(path).map_err(|e| format!("could not open downloaded candidate: {e}"))?;
    let mut hasher = Sha256::new();
    let mut buffer = [0u8; 64 * 1024];
    loop {
        let count = file
            .read(&mut buffer)
            .map_err(|e| format!("could not hash downloaded candidate: {e}"))?;
        if count == 0 {
            break;
        }
        hasher.update(&buffer[..count]);
    }
    let actual = digest_hex(hasher.finalize().as_ref());
    if !actual.eq_ignore_ascii_case(fields[0]) {
        return Err(format!(
            "SHA-256 mismatch for {expected_name}: expected {}, got {actual}",
            fields[0]
        ));
    }
    Ok(())
}

fn digest_hex(bytes: &[u8]) -> String {
    bytes.iter().map(|byte| format!("{byte:02x}")).collect()
}

fn cargo_candidate(version: &Version, staging: &Path) -> Result<PathBuf, String> {
    let root = staging.join("cargo-root");
    let version_arg = format!("={version}");
    let root_arg = root
        .to_str()
        .ok_or_else(|| "Cargo staging path is not valid UTF-8".to_string())?;
    println!(
        "Running: cargo install {CRATE_NAME} --version {version_arg} --locked --root {root_arg}"
    );
    let status = Command::new("cargo")
        .args(["install", CRATE_NAME, "--version", &version_arg, "--locked", "--root", root_arg])
        .status()
        .map_err(|e| if e.kind() == std::io::ErrorKind::NotFound {
            format!("Cargo is not installed; update manually with `cargo install {CRATE_NAME} --version '={version}' --locked`")
        } else { format!("could not run cargo: {e}") })?;
    if !status.success() {
        return Err(format!("cargo exited with status {status}"));
    }
    let binary = if cfg!(windows) {
        root.join("bin").join("snip-sync.exe")
    } else {
        root.join("bin").join(BINARY_NAME)
    };
    if !binary.is_file() {
        return Err(format!(
            "Cargo completed but did not produce {}",
            binary.display()
        ));
    }
    Ok(binary)
}

fn validate_candidate(path: &Path, version: &Version) -> Result<(), String> {
    let expected = format!("{BINARY_NAME} {version}");
    let mut child = Command::new(path)
        .arg("version")
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .map_err(|e| format!("verified candidate could not run: {e}"))?;
    wait_for_candidate(&mut child, Duration::from_secs(10))?;
    let output = child
        .wait_with_output()
        .map_err(|e| format!("could not collect candidate version output: {e}"))?;
    if !output.status.success() {
        return Err(format!(
            "candidate `version` command failed with {}",
            output.status
        ));
    }
    let identity = String::from_utf8_lossy(&output.stdout).trim().to_owned();
    if identity != expected {
        return Err(format!(
            "candidate identity mismatch: expected {expected:?}, got {identity:?}"
        ));
    }
    Ok(())
}

fn wait_for_candidate(child: &mut Child, timeout: Duration) -> Result<(), String> {
    let deadline = Instant::now() + timeout;
    loop {
        if child
            .try_wait()
            .map_err(|e| format!("could not inspect candidate process: {e}"))?
            .is_some()
        {
            return Ok(());
        }
        if Instant::now() >= deadline {
            let _ = child.kill();
            let _ = child.wait();
            return Err("candidate `version` command timed out".into());
        }
        std::thread::sleep(Duration::from_millis(20));
    }
}

fn make_executable(path: &Path) -> Result<(), String> {
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        fs::set_permissions(path, fs::Permissions::from_mode(0o755))
            .map_err(|e| format!("could not mark candidate executable: {e}"))?;
    }
    Ok(())
}

fn ensure_destination_writable(destination: &Path) -> Result<(), String> {
    let parent = destination
        .parent()
        .ok_or_else(|| "installed executable has no parent directory".to_string())?;
    let name = format!(
        ".snip-sync.update-check-{}-{}",
        std::process::id(),
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_nanos()
    );
    let probe = parent.join(name);
    match OpenOptions::new().write(true).create_new(true).open(&probe) {
        Ok(file) => {
            drop(file);
            let _ = fs::remove_file(probe);
            Ok(())
        }
        Err(error) => Err(format!(
            "cannot replace installed executable before stopping any service ({}): {error}",
            destination.display()
        )),
    }
}

fn replace_installed_executable(
    candidate: &Path,
    destination: &Path,
    _workdir: &Path,
    _lifecycle: snip_sync::startup::UpdateLifecycle,
) -> Result<(), String> {
    #[cfg(unix)]
    {
        let parent = destination
            .parent()
            .ok_or_else(|| "installed executable has no parent directory".to_string())?;
        // The staging name is unguessable and the file is created with
        // `O_EXCL` (`create_new`), so a symlink planted at the staging path
        // is never followed. The previous `fs::copy` opened the destination
        // with `O_WRONLY|O_CREAT|O_TRUNC`, which follows symlinks — an
        // unprivileged local user able to write to the install directory
        // could have won the race and turned the update into an arbitrary
        // file write.
        let staged = parent.join(format!(".snip-sync.update-{}", uuid::Uuid::new_v4()));
        let mut staged_file = match OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(&staged)
        {
            Ok(file) => file,
            Err(error) => {
                return Err(format!(
                    "could not stage candidate beside installed executable: {error}"
                ));
            }
        };
        let copy_result = (|| -> std::io::Result<()> {
            let mut source = File::open(candidate)?;
            std::io::copy(&mut source, &mut staged_file)?;
            Ok(())
        })();
        if let Err(error) = copy_result {
            drop(staged_file);
            let _ = fs::remove_file(&staged);
            return Err(format!(
                "could not stage candidate beside installed executable: {error}"
            ));
        }
        if let Ok(permissions) = fs::metadata(destination).map(|m| m.permissions()) {
            if let Err(error) = fs::set_permissions(&staged, permissions) {
                drop(staged_file);
                let _ = fs::remove_file(&staged);
                return Err(format!(
                    "could not preserve executable permissions: {error}"
                ));
            }
        } else {
            if let Err(error) = make_executable(&staged) {
                drop(staged_file);
                let _ = fs::remove_file(&staged);
                return Err(error);
            }
        }
        if let Err(error) = staged_file.sync_all() {
            drop(staged_file);
            let _ = fs::remove_file(&staged);
            return Err(format!("could not durably stage executable: {error}"));
        }
        drop(staged_file);
        fs::rename(&staged, destination).map_err(|e| {
            let _ = fs::remove_file(&staged);
            format!("could not replace installed executable: {e}")
        })?;
        // The file's data was fsynced before the rename, but the rename
        // itself is only durable once the containing directory is fsynced:
        // without this a power loss right after the rename can leave the
        // install directory pointing at the old binary.
        sync_parent_dir_durable(parent)?;
        Ok(())
    }
    #[cfg(windows)]
    {
        schedule_windows_self_replace(candidate, destination, _workdir, _lifecycle)
    }
    #[cfg(not(any(unix, windows)))]
    {
        let _ = (candidate, destination, _workdir, _lifecycle);
        Err("executable replacement is not supported on this platform".into())
    }
}

/// Make a directory entry durable by fsyncing the directory that contains it.
///
/// Unix only; other platforms cannot fsync a directory through std. A
/// failure is fatal: the replacement already happened, but without the
/// directory fsync it can be lost by a power failure.
fn sync_parent_dir_durable(parent: &Path) -> Result<(), String> {
    #[cfg(unix)]
    {
        let directory = fs::OpenOptions::new()
            .read(true)
            .open(parent)
            .map_err(|e| format!("could not open install directory for fsync: {e}"))?;
        directory
            .sync_all()
            .map_err(|e| format!("could not fsync install directory: {e}"))?;
    }
    #[cfg(not(unix))]
    {
        let _ = parent;
    }
    Ok(())
}

#[cfg(windows)]
fn stop_running_server(executable: &Path) -> Result<(), String> {
    let status = Command::new(executable)
        .args(["stop", "--force"])
        .status()
        .map_err(|e| format!("failed to stop running server before Windows replacement: {e}"))?;
    if status.success() {
        Ok(())
    } else {
        Err("could not stop running server before Windows replacement".into())
    }
}

#[cfg(windows)]
fn schedule_windows_self_replace(
    candidate: &Path,
    destination: &Path,
    workdir: &Path,
    lifecycle: snip_sync::startup::UpdateLifecycle,
) -> Result<(), String> {
    let helper = workdir.join("snip-sync-self-replace-helper.exe");
    let current = std::env::current_exe()
        .map_err(|e| format!("could not locate updater helper source: {e}"))?;
    fs::copy(current, &helper)
        .map_err(|e| format!("could not stage Windows replacement helper: {e}"))?;
    let managed_restart = matches!(
        lifecycle,
        snip_sync::startup::UpdateLifecycle::ManagedRunning(_)
    );
    let restart = matches!(
        lifecycle,
        snip_sync::startup::UpdateLifecycle::ManagedRunning(_)
            | snip_sync::startup::UpdateLifecycle::DirectRunning
    );
    let mut args = vec![
        "__self-replace".to_owned(),
        "--candidate".to_owned(),
        candidate
            .to_str()
            .ok_or_else(|| "candidate path is not UTF-8".to_string())?
            .to_owned(),
        "--destination".to_owned(),
        destination
            .to_str()
            .ok_or_else(|| "destination path is not UTF-8".to_string())?
            .to_owned(),
    ];
    if restart {
        args.push("--restart".to_owned());
    }
    if managed_restart {
        args.push("--managed-restart".to_owned());
    }
    Command::new(&helper)
        .args(&args)
        .spawn()
        .map_err(|e| format!("could not start Windows replacement helper: {e}"))?;
    println!(
        "Verified candidate staged; Windows replacement will complete after this process exits."
    );
    Ok(())
}

pub fn run_self_replace_helper(
    candidate: &Path,
    destination: &Path,
    restart: bool,
    managed_restart: bool,
) -> Result<(), String> {
    #[cfg(windows)]
    {
        use std::os::windows::ffi::OsStrExt;
        use windows_sys::Win32::Storage::FileSystem::{
            MOVEFILE_REPLACE_EXISTING, MOVEFILE_WRITE_THROUGH, MoveFileExW,
        };
        let wide = |path: &Path| {
            path.as_os_str()
                .encode_wide()
                .chain(std::iter::once(0))
                .collect::<Vec<_>>()
        };
        let source = wide(candidate);
        let target = wide(destination);
        let ok = unsafe {
            MoveFileExW(
                source.as_ptr(),
                target.as_ptr(),
                MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH,
            )
        };
        if ok == 0 {
            return Err(format!(
                "Windows replacement failed: {}",
                std::io::Error::last_os_error()
            ));
        }
        let _ = fs::remove_file(candidate);
        println!("Windows executable replacement complete.");
        if restart {
            let mut command = Command::new(destination);
            if managed_restart {
                command.arg("restart");
            } else {
                command.args(["croncheck", "--verbose"]);
            }
            let status = command.status().map_err(|e| {
                format!("new snip-sync binary installed, but restart could not be started: {e}")
            })?;
            if !status.success() {
                return Err(format_partial_restart_error(
                    "new snip-sync binary installed, but restart failed",
                ));
            }
        }
        Ok(())
    }
    #[cfg(not(windows))]
    {
        let _ = (candidate, destination, restart, managed_restart);
        Err("internal Windows replacement command is only supported on Windows".into())
    }
}

fn format_partial_restart_error(error: &str) -> String {
    format!(
        "new snip-sync version is installed on disk, but restart failed: {error}. The old process may still be active; run `snip-sync restart` manually"
    )
}

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

    #[test]
    fn host_mapping_matches_release_contract() {
        assert_eq!(
            host_target("linux", "x86_64"),
            Some(HostTarget::Prebuilt("x86_64-unknown-linux-gnu"))
        );
        assert_eq!(
            host_target("linux", "arm"),
            Some(HostTarget::SourceOnly("armv7-unknown-linux-gnueabihf"))
        );
        assert_eq!(
            host_target("windows", "aarch64"),
            Some(HostTarget::SourceOnly("aarch64-pc-windows-msvc"))
        );
        assert_eq!(host_target("freebsd", "x86_64"), None);
    }

    #[test]
    fn component_tag_and_checksum_contract_are_exact() {
        let version = Version::new(1, 2, 3);
        assert_eq!(component_tag(&version), "snip-sync-v1.2.3");
        let expected = if cfg!(windows) {
            "snip-sync-x86_64-unknown-linux-gnu.exe"
        } else {
            "snip-sync-x86_64-unknown-linux-gnu"
        };
        assert_eq!(asset_name("x86_64-unknown-linux-gnu"), expected);
        let file = tempfile::NamedTempFile::new().unwrap();
        fs::write(file.path(), b"hello").unwrap();
        let mut hasher = Sha256::new();
        hasher.update(b"hello");
        let digest = digest_hex(hasher.finalize().as_ref());
        verify_checksum(
            file.path(),
            format!("{digest}  candidate\n").as_bytes(),
            "candidate",
        )
        .unwrap();
        assert!(
            verify_checksum(
                file.path(),
                format!("{digest} candidate\nextra\n").as_bytes(),
                "candidate"
            )
            .is_err()
        );
    }

    #[cfg(windows)]
    #[test]
    fn windows_helper_replaces_a_temporary_copy() {
        let directory = tempfile::tempdir().unwrap();
        let candidate = directory.path().join("candidate.exe");
        let destination = directory.path().join("destination.exe");
        fs::write(&candidate, b"new executable").unwrap();
        fs::write(&destination, b"old executable").unwrap();
        run_self_replace_helper(&candidate, &destination, false, false).unwrap();
        assert_eq!(fs::read(&destination).unwrap(), b"new executable");
        assert!(!candidate.exists());
    }

    #[cfg(unix)]
    #[test]
    fn self_update_staging_never_follows_a_planted_symlink() {
        use std::os::unix::fs::symlink;

        let directory = tempfile::tempdir().unwrap();
        let candidate = directory.path().join("candidate");
        let destination = directory.path().join("snip-sync");
        let victim = directory.path().join("victim");
        fs::write(&candidate, b"new executable").unwrap();
        fs::write(&destination, b"old executable").unwrap();
        fs::write(&victim, b"victim contents").unwrap();

        // The staging name used to be derived from the process id. Plant a
        // symlink at that path: an update must not follow it and truncate
        // the symlink's target.
        let planted = directory
            .path()
            .join(format!(".snip-sync.update-{}", std::process::id()));
        symlink(&victim, &planted).unwrap();

        replace_installed_executable(
            &candidate,
            &destination,
            directory.path(),
            snip_sync::startup::UpdateLifecycle::NotRunning,
        )
        .unwrap();

        assert_eq!(fs::read(&destination).unwrap(), b"new executable");
        assert_eq!(
            fs::read(&victim).unwrap(),
            b"victim contents",
            "the planted symlink target must not be overwritten"
        );
        assert!(
            planted.exists(),
            "the planted symlink must be left untouched"
        );
    }

    #[cfg(unix)]
    #[test]
    fn self_update_leaves_no_staging_file_behind() {
        let directory = tempfile::tempdir().unwrap();
        let candidate = directory.path().join("candidate");
        let destination = directory.path().join("snip-sync");
        fs::write(&candidate, b"new executable").unwrap();
        fs::write(&destination, b"old executable").unwrap();

        replace_installed_executable(
            &candidate,
            &destination,
            directory.path(),
            snip_sync::startup::UpdateLifecycle::NotRunning,
        )
        .unwrap();

        let leftovers: Vec<_> = fs::read_dir(directory.path())
            .unwrap()
            .filter_map(|entry| entry.ok())
            .map(|entry| entry.file_name().to_string_lossy().into_owned())
            .filter(|name| name.starts_with(".snip-sync.update-"))
            .collect();
        assert!(
            leftovers.is_empty(),
            "staging files must not survive the replacement: {leftovers:?}"
        );
    }

    #[test]
    fn parent_directory_fsync_surfaces_failures() {
        let directory = tempfile::tempdir().unwrap();
        // The replacement path fsyncs the install directory so the rename
        // survives a crash.
        sync_parent_dir_durable(directory.path()).unwrap();
        let missing = directory.path().join("missing");
        assert!(sync_parent_dir_durable(&missing).is_err());
    }
}