shipslip 0.14.0

Deploy Laravel apps over SSH with a preview, a deploy lock, and a receipt.
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
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
//! Durable local record of a deploy or of bringing the app up, written
//! before every remote mutation.

use std::fs::{self, File, OpenOptions};
use std::io;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use std::time::{SystemTime, UNIX_EPOCH};

use fs2::FileExt;
use serde::{Deserialize, Serialize};

use crate::{
    ConnectionTarget, DeployEvent, DeployOutcome, DeployTarget, MaintenancePhase, Preview, RunPlan,
    SmokeResult, StepStatus, StepTimes, WatchResult,
};

mod history;
pub(crate) mod markdown;
mod overview;

pub(crate) use history::list_checkout;
pub use history::{find, list, Found, Listed, Listing, MIN_ID_LEN};
pub use markdown::markdown;
pub use overview::{
    compare_envs, compare_envs_with, comparison_text, overview, AttemptSummary, CellRef, CodeState,
    EnvCell, EnvComparison, Evidence, Mark, NewerElsewhere, NotKnownReason, Overview, Problem,
    ProblemKind, Qualifier, RepoRow, StaleHint, WALK_LIMIT,
};

/// Deploy receipts keep version 1 so older releases still read them.
const DEPLOY_VERSION: u32 = 1;
/// Up receipts are version 2, which older releases report as unreadable
/// instead of misreading as a deploy.
const UP_VERSION: u32 = 2;
const OUTPUT_LINES: usize = 200;
const OUTPUT_LINE_BYTES: usize = 16 * 1024;

#[derive(Debug, thiserror::Error)]
pub enum ReceiptError {
    #[error("receipt I/O at `{path}`: {source}")]
    Io { path: PathBuf, source: io::Error },
    #[error("invalid receipt `{path}`: {source}")]
    Parse {
        path: PathBuf,
        source: serde_json::Error,
    },
    #[error("could not serialize receipt: {0}")]
    Serialize(#[from] serde_json::Error),
    #[error("unsupported receipt schema version {0}")]
    Version(u32),
    #[error("invalid receipt: {0}")]
    Invalid(String),
    #[error("multiple unfinished receipts for this environment: {0}")]
    MultipleOpen(String),
    #[error("another process is already using receipt `{0}`")]
    Claimed(PathBuf),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ReceiptStatus {
    InProgress,
    Final,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ReceiptPhase {
    Preview,
    MaintenanceDown,
    Step(usize),
    MaintenanceUp,
    BetweenSteps,
    Finished,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ReceiptStepStatus {
    Pending,
    Running,
    Ok,
    Failed,
    Unknown,
    NotStarted,
    Skipped,
}

impl From<StepStatus> for ReceiptStepStatus {
    fn from(status: StepStatus) -> Self {
        match status {
            StepStatus::Ok => Self::Ok,
            StepStatus::Failed => Self::Failed,
            StepStatus::Unknown => Self::Unknown,
            StepStatus::NotStarted => Self::NotStarted,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConnectionGap {
    /// When the server was last heard, not when the loss was noticed.
    pub lost_at_ms: u128,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reattached_at_ms: Option<u128>,
    pub detail: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReceiptStep {
    pub index: usize,
    pub command: String,
    pub status: ReceiptStepStatus,
    pub exit_code: Option<i32>,
    pub output: Vec<String>,
    /// This Mac's clock; missing in receipts written before step times.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub started_at_ms: Option<u128>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub finished_at_ms: Option<u128>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub result_seen_at_ms: Option<u128>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub connection_gaps: Vec<ConnectionGap>,
}

impl ReceiptStep {
    pub fn times(&self) -> StepTimes {
        StepTimes {
            started_at_ms: self.started_at_ms,
            finished_at_ms: self.finished_at_ms,
            result_seen_at_ms: self.result_seen_at_ms,
        }
    }
}

/// Why this Mac stopped watching a run that is still open, as recorded at
/// the time. Absent when nothing was recorded, for example after a crash.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum UnfinishedCause {
    /// The user detached; the running step kept running on the server.
    Detached,
    /// The front-end closed without detaching.
    AppClosed,
    /// The connection was lost and Shipslip could not re-attach.
    ConnectionLost,
}

/// What a run did on the server.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ReceiptKind {
    #[default]
    Deploy,
    /// `php artisan up` on its own; the code on the server did not change.
    Up,
}

impl ReceiptKind {
    fn is_deploy(&self) -> bool {
        *self == Self::Deploy
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Receipt {
    pub version: u32,
    /// Receipts written before kinds existed are deploys.
    #[serde(default, skip_serializing_if = "ReceiptKind::is_deploy")]
    pub kind: ReceiptKind,
    pub project: String,
    pub repo_root: String,
    pub run_id: String,
    pub owner_pid: u32,
    pub confirmed: bool,
    pub started_at_ms: u128,
    pub finished_at_ms: Option<u128>,
    pub status: ReceiptStatus,
    pub phase: ReceiptPhase,
    pub target: DeployTarget,
    pub run_plan: RunPlan,
    pub from_sha: String,
    pub target_sha: String,
    pub commits: Vec<String>,
    /// Commits in the range beyond those listed in `commits`.
    #[serde(default, skip_serializing_if = "is_zero")]
    pub more_commits: usize,
    pub recipe_hash: String,
    pub steps: Vec<ReceiptStep>,
    pub maintenance_down_done: bool,
    pub maintenance_up_done: bool,
    pub maintenance_down_status: Option<StepStatus>,
    pub maintenance_down_exit_code: Option<i32>,
    pub maintenance_up_status: Option<StepStatus>,
    pub maintenance_up_exit_code: Option<i32>,
    /// This Mac's clock; missing in receipts written before maintenance times.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub maintenance_down_started_at_ms: Option<u128>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub maintenance_down_finished_at_ms: Option<u128>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub maintenance_up_started_at_ms: Option<u128>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub maintenance_up_finished_at_ms: Option<u128>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub maintenance_down_result_seen_at_ms: Option<u128>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub maintenance_up_result_seen_at_ms: Option<u128>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub maintenance_down_connection_gaps: Vec<ConnectionGap>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub maintenance_up_connection_gaps: Vec<ConnectionGap>,
    pub app_left_down: bool,
    pub mutation_started: bool,
    pub outcome: Option<DeployOutcome>,
    pub server_head_at_end: Option<String>,
    pub tree_dirty: Option<bool>,
    pub last_message: Option<String>,
    /// Absent in receipts written before it was recorded.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub unfinished_cause: Option<UnfinishedCause>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub warnings: Vec<String>,
    #[serde(default)]
    pub watch: Option<WatchResult>,
    #[serde(default)]
    pub smoke: Option<SmokeResult>,
    /// Applies to the smoke check and post-run log watch; absent in older receipts.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub checks_skip_reason: Option<crate::observation::CheckSkipReason>,
    /// Who started the run; `None` in receipts written before it was recorded.
    #[serde(default)]
    pub actor: Option<Actor>,
}

/// The local user and Git identity that started a run. Each part is best
/// effort and never blocks a deploy.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Actor {
    pub user: Option<String>,
    pub git_name: Option<String>,
    pub git_email: Option<String>,
}

impl Actor {
    pub fn local(repo_root: &Path) -> Self {
        let git = crate::git::Git::new(PathBuf::from("git"));
        let config = |key: &str| {
            git.run(repo_root, &["config", "--get", key])
                .ok()
                .map(|value| value.trim().to_owned())
                .filter(|value| !value.is_empty())
        };
        Self {
            user: std::env::var("USER").ok().filter(|user| !user.is_empty()),
            git_name: config("user.name"),
            git_email: config("user.email"),
        }
    }
}

impl Receipt {
    pub fn maintenance_down_times(&self) -> StepTimes {
        StepTimes {
            started_at_ms: self.maintenance_down_started_at_ms,
            finished_at_ms: self.maintenance_down_finished_at_ms,
            result_seen_at_ms: self.maintenance_down_result_seen_at_ms,
        }
    }

    pub fn maintenance_up_times(&self) -> StepTimes {
        StepTimes {
            started_at_ms: self.maintenance_up_started_at_ms,
            finished_at_ms: self.maintenance_up_finished_at_ms,
            result_seen_at_ms: self.maintenance_up_result_seen_at_ms,
        }
    }

    fn from_preview(project: &str, repo_root: &Path, preview: &Preview) -> Self {
        let target = preview.target().clone();
        let run_plan = preview.run_plan();
        let first = run_plan.first_recipe_step();
        let steps = crate::engine::plan_steps(&target, run_plan, preview.target_sha())
            .into_iter()
            .map(|(index, command)| ReceiptStep {
                result_seen_at_ms: None,
                connection_gaps: Vec::new(),
                index,
                command,
                status: if index > 0 && index < first {
                    ReceiptStepStatus::Skipped
                } else {
                    ReceiptStepStatus::Pending
                },
                exit_code: None,
                output: Vec::new(),
                started_at_ms: None,
                finished_at_ms: None,
            })
            .collect();
        Self {
            version: DEPLOY_VERSION,
            kind: ReceiptKind::Deploy,
            project: project.into(),
            repo_root: repo_root.to_string_lossy().into_owned(),
            run_id: preview.run_id().into(),
            owner_pid: std::process::id(),
            confirmed: false,
            started_at_ms: now_ms(),
            finished_at_ms: None,
            status: ReceiptStatus::InProgress,
            phase: ReceiptPhase::Preview,
            target,
            run_plan,
            from_sha: preview.from_sha().into(),
            target_sha: preview.target_sha().into(),
            commits: preview.commits().to_vec(),
            more_commits: preview.more_commits(),
            recipe_hash: preview.recipe_hash().into(),
            steps,
            maintenance_down_done: false,
            maintenance_up_done: false,
            maintenance_down_status: None,
            maintenance_down_exit_code: None,
            maintenance_up_status: None,
            maintenance_up_exit_code: None,
            maintenance_down_started_at_ms: None,
            maintenance_down_finished_at_ms: None,
            maintenance_up_started_at_ms: None,
            maintenance_up_finished_at_ms: None,
            maintenance_down_result_seen_at_ms: None,
            maintenance_up_result_seen_at_ms: None,
            maintenance_down_connection_gaps: Vec::new(),
            maintenance_up_connection_gaps: Vec::new(),
            app_left_down: false,
            mutation_started: false,
            outcome: None,
            server_head_at_end: None,
            tree_dirty: None,
            last_message: None,
            unfinished_cause: None,
            warnings: Vec::new(),
            watch: None,
            smoke: None,
            checks_skip_reason: None,
            actor: Some(Actor::local(repo_root)),
        }
    }

    /// A receipt for `php artisan up` on `target`, whose server checkout is
    /// at `head`. Its only step records the maintenance command and output.
    fn for_up(
        project: &str,
        repo_root: &Path,
        target: &DeployTarget,
        head: &str,
        run_id: &str,
        script_hash: &str,
    ) -> Self {
        Self {
            version: UP_VERSION,
            kind: ReceiptKind::Up,
            project: project.into(),
            repo_root: repo_root.to_string_lossy().into_owned(),
            run_id: run_id.into(),
            owner_pid: std::process::id(),
            // The front-end asked the user before starting it.
            confirmed: true,
            started_at_ms: now_ms(),
            finished_at_ms: None,
            status: ReceiptStatus::InProgress,
            phase: ReceiptPhase::Preview,
            target: target.clone(),
            run_plan: RunPlan::Deploy,
            from_sha: head.into(),
            target_sha: head.into(),
            commits: Vec::new(),
            more_commits: 0,
            recipe_hash: script_hash.into(),
            steps: vec![ReceiptStep {
                result_seen_at_ms: None,
                connection_gaps: Vec::new(),
                index: 0,
                command: "php artisan up".into(),
                status: ReceiptStepStatus::NotStarted,
                exit_code: None,
                output: Vec::new(),
                started_at_ms: None,
                finished_at_ms: None,
            }],
            maintenance_down_done: false,
            maintenance_up_done: false,
            maintenance_down_status: None,
            maintenance_down_exit_code: None,
            maintenance_up_status: None,
            maintenance_up_exit_code: None,
            maintenance_down_started_at_ms: None,
            maintenance_down_finished_at_ms: None,
            maintenance_up_started_at_ms: None,
            maintenance_up_finished_at_ms: None,
            maintenance_down_result_seen_at_ms: None,
            maintenance_up_result_seen_at_ms: None,
            maintenance_down_connection_gaps: Vec::new(),
            maintenance_up_connection_gaps: Vec::new(),
            // Up runs because the app may be down.
            app_left_down: true,
            mutation_started: false,
            outcome: None,
            server_head_at_end: None,
            tree_dirty: None,
            last_message: None,
            unfinished_cause: None,
            warnings: Vec::new(),
            watch: None,
            smoke: None,
            checks_skip_reason: None,
            actor: Some(Actor::local(repo_root)),
        }
    }

    pub fn last_completed_step(&self) -> Option<usize> {
        self.steps
            .iter()
            .filter(|step| step.status == ReceiptStepStatus::Ok)
            .map(|step| step.index)
            .max()
    }
}

#[derive(Debug)]
pub struct ReceiptJournal {
    path: PathBuf,
    state: Mutex<Receipt>,
    claim: Mutex<Option<File>>,
}

impl Drop for ReceiptJournal {
    fn drop(&mut self) {
        self.release_claim();
    }
}

impl ReceiptJournal {
    pub fn create(
        root: &Path,
        project: &str,
        repo_root: &Path,
        preview: &Preview,
    ) -> Result<Self, ReceiptError> {
        Self::write_new(root, Receipt::from_preview(project, repo_root, preview))
    }

    /// Writes the receipt for bringing the app up and claims it.
    pub(crate) fn create_up(
        root: &Path,
        project: &str,
        repo_root: &Path,
        target: &DeployTarget,
        head: &str,
        run_id: &str,
        script_hash: &str,
    ) -> Result<Self, ReceiptError> {
        let receipt = Receipt::for_up(project, repo_root, target, head, run_id, script_hash);
        Self::write_new(root, receipt)
    }

    fn write_new(root: &Path, receipt: Receipt) -> Result<Self, ReceiptError> {
        let dir = receipt_dir(root, &receipt.project, &receipt.target.env);
        fs::create_dir_all(&dir).map_err(|source| io_error(&dir, source))?;
        private_dir(&dir)?;
        let path = dir.join(format!("{}-{}.json", receipt.started_at_ms, receipt.run_id));
        write_atomic(&path, &receipt)?;
        let journal = Self {
            path,
            state: Mutex::new(receipt),
            claim: Mutex::new(None),
        };
        journal.claim()?;
        Ok(journal)
    }

    pub fn load(path: &Path) -> Result<Self, ReceiptError> {
        let receipt = read_receipt(path)?;
        Ok(Self {
            path: path.to_path_buf(),
            state: Mutex::new(receipt),
            claim: Mutex::new(None),
        })
    }

    /// Checks an existing sidecar without creating it or taking over the journal.
    /// A successful non-blocking lock is released before this returns.
    pub fn is_claimed(path: &Path) -> Result<bool, ReceiptError> {
        let lock_path = path.with_extension("json.lock");
        let file = match File::open(&lock_path) {
            Ok(file) => file,
            Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(false),
            Err(source) => return Err(io_error(&lock_path, source)),
        };
        match file.try_lock_exclusive() {
            Ok(()) => {
                FileExt::unlock(&file).map_err(|source| io_error(&lock_path, source))?;
                Ok(false)
            }
            Err(error) if error.kind() == io::ErrorKind::WouldBlock => Ok(true),
            Err(source) => Err(io_error(&lock_path, source)),
        }
    }

    /// Holds an OS file lock until this journal is dropped. A killed process
    /// releases it automatically, while the receipt remains available.
    pub fn claim(&self) -> Result<(), ReceiptError> {
        let mut claim = self.claim.lock().unwrap();
        if claim.is_some() {
            return Ok(());
        }
        let lock_path = self.path.with_extension("json.lock");
        let mut options = OpenOptions::new();
        options.read(true).write(true).create(true);
        #[cfg(unix)]
        {
            use std::os::unix::fs::OpenOptionsExt;
            options.mode(0o600);
        }
        let file = options
            .open(&lock_path)
            .map_err(|source| io_error(&lock_path, source))?;
        match file.try_lock_exclusive() {
            Ok(()) => {}
            Err(error) if error.kind() == io::ErrorKind::WouldBlock => {
                return Err(ReceiptError::Claimed(self.path.clone()));
            }
            Err(source) => return Err(io_error(&lock_path, source)),
        }
        *self.state.lock().unwrap() = read_receipt(&self.path)?;
        *claim = Some(file);
        Ok(())
    }

    pub(crate) fn release_claim(&self) {
        if let Some(file) = self
            .claim
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .take()
        {
            let _ = FileExt::unlock(&file);
        }
    }

    pub fn path(&self) -> &Path {
        &self.path
    }

    pub fn snapshot(&self) -> Receipt {
        self.state.lock().unwrap().clone()
    }

    /// A new session takes over the run; why the last one let go no longer
    /// describes it.
    pub fn set_owner_pid(&self, pid: u32) -> Result<(), ReceiptError> {
        self.update(|receipt| {
            receipt.owner_pid = pid;
            receipt.unfinished_cause = None;
        })
    }

    pub fn confirm(&self) -> Result<(), ReceiptError> {
        self.update(|receipt| receipt.confirmed = true)
    }

    pub fn warning(&self, message: String) -> Result<(), ReceiptError> {
        self.update(|receipt| {
            if receipt.warnings.len() < 20 {
                receipt.warnings.push(message);
            }
        })
    }

    pub fn begin_step(&self, index: usize, started_at_ms: u128) -> Result<(), ReceiptError> {
        self.update(|receipt| {
            receipt.phase = ReceiptPhase::Step(index);
            receipt.mutation_started = true;
            if let Some(step) = receipt.steps.iter_mut().find(|step| step.index == index) {
                step.status = ReceiptStepStatus::Running;
                step.started_at_ms = Some(started_at_ms);
            }
        })
    }

    pub fn finish_step(
        &self,
        index: usize,
        status: StepStatus,
        exit_code: Option<i32>,
        times: StepTimes,
    ) -> Result<(), ReceiptError> {
        self.update(|receipt| {
            receipt.phase = ReceiptPhase::BetweenSteps;
            if let Some(step) = receipt.steps.iter_mut().find(|step| step.index == index) {
                step.status = status.into();
                step.exit_code = exit_code;
                step.started_at_ms = times.started_at_ms;
                step.finished_at_ms = times.finished_at_ms;
                step.result_seen_at_ms = times.result_seen_at_ms;
            }
        })
    }

    pub fn begin_maintenance(
        &self,
        phase: MaintenancePhase,
        started_at_ms: u128,
    ) -> Result<(), ReceiptError> {
        self.update(|receipt| {
            receipt.phase = match phase {
                MaintenancePhase::Down => ReceiptPhase::MaintenanceDown,
                MaintenancePhase::Up => ReceiptPhase::MaintenanceUp,
            };
            receipt.mutation_started = true;
            match phase {
                MaintenancePhase::Down => {
                    receipt.maintenance_down_started_at_ms = Some(started_at_ms);
                }
                MaintenancePhase::Up => {
                    receipt.maintenance_up_started_at_ms = Some(started_at_ms);
                }
            }
            if receipt.kind == ReceiptKind::Up {
                if let Some(step) = receipt.steps.first_mut() {
                    step.status = ReceiptStepStatus::Running;
                    step.started_at_ms = Some(started_at_ms);
                }
            }
            if phase == MaintenancePhase::Down {
                receipt.app_left_down = true;
            }
        })
    }

    pub fn finish_maintenance(
        &self,
        phase: MaintenancePhase,
        status: StepStatus,
        exit_code: Option<i32>,
        times: StepTimes,
    ) -> Result<(), ReceiptError> {
        self.update(|receipt| {
            receipt.phase = ReceiptPhase::BetweenSteps;
            match phase {
                MaintenancePhase::Down => {
                    receipt.maintenance_down_status = Some(status.clone());
                    receipt.maintenance_down_exit_code = exit_code;
                    receipt.maintenance_down_started_at_ms = times.started_at_ms;
                    receipt.maintenance_down_finished_at_ms = times.finished_at_ms;
                    receipt.maintenance_down_result_seen_at_ms = times.result_seen_at_ms;
                    receipt.maintenance_down_done = status == StepStatus::Ok;
                    receipt.app_left_down = crate::event::down_may_have_started(&status);
                }
                MaintenancePhase::Up => {
                    if receipt.kind == ReceiptKind::Up {
                        if let Some(step) = receipt.steps.first_mut() {
                            step.status = status.clone().into();
                            step.exit_code = exit_code;
                            step.started_at_ms = times.started_at_ms;
                            step.finished_at_ms = times.finished_at_ms;
                            step.result_seen_at_ms = times.result_seen_at_ms;
                        }
                    }
                    receipt.maintenance_up_status = Some(status.clone());
                    receipt.maintenance_up_exit_code = exit_code;
                    receipt.maintenance_up_started_at_ms = times.started_at_ms;
                    receipt.maintenance_up_finished_at_ms = times.finished_at_ms;
                    receipt.maintenance_up_result_seen_at_ms = times.result_seen_at_ms;
                    receipt.maintenance_up_done = status == StepStatus::Ok;
                    receipt.app_left_down = status != StepStatus::Ok;
                }
            }
        })
    }

    pub(crate) fn interrupted(&self, reason: &str) -> Result<String, ReceiptError> {
        let mut message = reason.to_string();
        self.update(|receipt| {
            let gaps = match receipt.phase {
                ReceiptPhase::Step(index) => receipt
                    .steps
                    .iter_mut()
                    .find(|step| step.index == index)
                    .map(|step| &mut step.connection_gaps),
                ReceiptPhase::MaintenanceDown => {
                    Some(&mut receipt.maintenance_down_connection_gaps)
                }
                ReceiptPhase::MaintenanceUp => Some(&mut receipt.maintenance_up_connection_gaps),
                _ if receipt.kind == ReceiptKind::Up => {
                    Some(&mut receipt.maintenance_up_connection_gaps)
                }
                _ => None,
            };
            if let Some(gap) = gaps
                .and_then(|gaps| gaps.last_mut())
                .filter(|gap| gap.reattached_at_ms.is_none())
            {
                if gap.detail != reason {
                    gap.detail.push_str(&format!("\n{reason}"));
                }
                message = "The connection was lost. Shipslip could not re-attach. \
                           The step's result is not known."
                    .into();
            }
            if receipt.kind == ReceiptKind::Up {
                if let Some(step) = receipt.steps.first_mut() {
                    step.connection_gaps
                        .clone_from(&receipt.maintenance_up_connection_gaps);
                }
            }
            receipt.last_message = Some(message.clone());
            keep_app_closed(receipt, UnfinishedCause::ConnectionLost);
        })?;
        Ok(message)
    }

    pub fn connection_event(&self, event: &DeployEvent) -> Result<(), ReceiptError> {
        let (target, at_ms, detail) = match event {
            DeployEvent::ConnectionLost {
                target,
                at_ms,
                detail,
            } => (*target, *at_ms, Some(detail)),
            DeployEvent::Reattached { target, at_ms } => (*target, *at_ms, None),
            _ => return Ok(()),
        };
        self.update(|receipt| {
            let update = |gaps: &mut Vec<ConnectionGap>| {
                if let Some(detail) = detail {
                    gaps.push(ConnectionGap {
                        lost_at_ms: at_ms,
                        reattached_at_ms: None,
                        detail: detail.clone(),
                    });
                } else if let Some(gap) =
                    gaps.last_mut().filter(|gap| gap.reattached_at_ms.is_none())
                {
                    gap.reattached_at_ms = Some(at_ms);
                }
            };
            match target {
                ConnectionTarget::Step { index } => {
                    if let Some(step) = receipt.steps.iter_mut().find(|step| step.index == index) {
                        update(&mut step.connection_gaps);
                    }
                }
                ConnectionTarget::Maintenance {
                    phase: MaintenancePhase::Down,
                } => update(&mut receipt.maintenance_down_connection_gaps),
                ConnectionTarget::Maintenance {
                    phase: MaintenancePhase::Up,
                } => {
                    update(&mut receipt.maintenance_up_connection_gaps);
                    if receipt.kind == ReceiptKind::Up {
                        if let Some(step) = receipt.steps.first_mut() {
                            update(&mut step.connection_gaps);
                        }
                    }
                }
                ConnectionTarget::LogWatch => {}
            }
            if detail.is_some() {
                let warning = format!(
                    "The connection was lost while watching {target}. The step was not run again."
                );
                if !receipt.warnings.contains(&warning) {
                    receipt.warnings.push(warning);
                }
            }
        })
    }

    pub fn output_line(&self, key: &str, line: &str) {
        let mut receipt = self.state.lock().unwrap();
        let index = if receipt.kind == ReceiptKind::Up && key == "maintenance-up" {
            Some(0)
        } else {
            key.strip_prefix("step-")
                .and_then(|index| index.parse::<usize>().ok())
        };
        if let Some(index) = index {
            if let Some(step) = receipt.steps.iter_mut().find(|step| step.index == index) {
                if step.output.len() == OUTPUT_LINES {
                    step.output.remove(0);
                }
                let mut end = line.len().min(OUTPUT_LINE_BYTES);
                while !line.is_char_boundary(end) {
                    end -= 1;
                }
                step.output.push(line[..end].to_string());
            }
        }
    }

    pub fn server_state(
        &self,
        head: Option<String>,
        dirty: Option<bool>,
    ) -> Result<(), ReceiptError> {
        self.update(|receipt| {
            receipt.server_head_at_end = head;
            receipt.tree_dirty = dirty;
        })
    }

    pub fn message(&self, message: String) -> Result<(), ReceiptError> {
        self.update(|receipt| receipt.last_message = Some(message))
    }

    pub(crate) fn detached(&self, message: String) -> Result<(), ReceiptError> {
        self.update(|receipt| {
            receipt.last_message = Some(message);
            keep_app_closed(receipt, UnfinishedCause::Detached);
        })
    }

    /// Records that the front-end is closing without detaching. Does nothing
    /// once the run has let go of the receipt, so a run that already ended
    /// keeps its own record.
    pub(crate) fn app_closed(&self) -> Result<(), ReceiptError> {
        let claim = self
            .claim
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        if claim.is_none() {
            return Ok(());
        }
        if self.state.lock().unwrap().status == ReceiptStatus::Final {
            return Ok(());
        }
        self.write(|next| {
            next.last_message = Some(match next.phase {
                ReceiptPhase::Step(index) => {
                    format!("The app closed while step {index} was running.")
                }
                ReceiptPhase::MaintenanceDown => {
                    "The app closed while maintenance mode was being turned on.".into()
                }
                ReceiptPhase::MaintenanceUp => {
                    "The app closed while maintenance mode was being turned off.".into()
                }
                _ => "The app closed before the run finished.".into(),
            });
            next.unfinished_cause = Some(UnfinishedCause::AppClosed);
        })
    }

    pub fn record_outcome(&self, outcome: DeployOutcome) -> Result<(), ReceiptError> {
        self.update(|receipt| receipt.outcome = Some(outcome))
    }

    pub fn observation(
        &self,
        watch: Option<WatchResult>,
        smoke: Option<SmokeResult>,
        skip_reason: Option<crate::observation::CheckSkipReason>,
    ) -> Result<(), ReceiptError> {
        // `None` keeps what an earlier attach recorded.
        self.update(|receipt| {
            if watch.is_some() {
                receipt.watch = watch;
            }
            if smoke.is_some() {
                receipt.smoke = smoke;
            }
            receipt.checks_skip_reason = skip_reason;
        })
    }

    pub(crate) fn smoke(&self, smoke: SmokeResult) -> Result<(), ReceiptError> {
        self.update(|receipt| receipt.smoke = Some(smoke))
    }

    /// Where this env's log signature history lives: beside the receipts
    /// root, so a project named `signatures` cannot collide with it.
    pub fn history_paths(&self) -> HistoryPaths {
        let env_dir = self
            .path
            .parent()
            .expect("receipt has environment directory");
        let project_dir = env_dir.parent().expect("receipt has project directory");
        let root = project_dir.parent().expect("receipt has root directory");
        let tail = Path::new(project_dir.file_name().expect("project directory has name"))
            .join(env_dir.file_name().expect("environment directory has name"))
            .join("history.json");
        HistoryPaths {
            current: root
                .parent()
                .expect("receipts root has a parent")
                .join("signatures")
                .join(&tail),
            legacy: root.join("signatures").join(tail),
        }
    }

    pub fn finish(&self, outcome: DeployOutcome) -> Result<(), ReceiptError> {
        self.update(|receipt| {
            receipt.status = ReceiptStatus::Final;
            receipt.phase = ReceiptPhase::Finished;
            receipt.finished_at_ms = Some(now_ms());
            receipt.outcome = Some(outcome);
            receipt.unfinished_cause = None;
        })
    }

    fn update(&self, change: impl FnOnce(&mut Receipt)) -> Result<(), ReceiptError> {
        self.claim()?;
        self.write(change)
    }

    /// Writes a change durably. The caller holds the claim.
    fn write(&self, change: impl FnOnce(&mut Receipt)) -> Result<(), ReceiptError> {
        let mut receipt = self.state.lock().unwrap();
        let mut next = receipt.clone();
        change(&mut next);
        write_atomic(&self.path, &next)?;
        *receipt = next;
        Ok(())
    }
}

/// Signature history file, and where releases up to 0.5.3 kept it inside the
/// receipts root. The legacy file is read when the current one is missing and
/// moved on the next write; no directory is ever removed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HistoryPaths {
    pub current: PathBuf,
    pub legacy: PathBuf,
}

/// The run may end on its own while the app is exiting; the app closing is
/// still why nobody watched it finish.
fn keep_app_closed(receipt: &mut Receipt, cause: UnfinishedCause) {
    if receipt.unfinished_cause != Some(UnfinishedCause::AppClosed) {
        receipt.unfinished_cause = Some(cause);
    }
}

fn is_zero(value: &usize) -> bool {
    *value == 0
}

pub fn default_receipts_root() -> Result<PathBuf, ReceiptError> {
    let home =
        std::env::var_os("HOME").ok_or_else(|| ReceiptError::Invalid("HOME is not set".into()))?;
    let home = PathBuf::from(home);
    #[cfg(target_os = "macos")]
    let path = home.join("Library/Application Support/Shipslip/receipts");
    #[cfg(not(target_os = "macos"))]
    let path = home.join(".local/share/shipslip/receipts");
    Ok(path)
}

/// The fields [`find_open`] and the release map need, readable from any
/// receipt version.
#[derive(Deserialize)]
struct ReceiptSummary {
    status: ReceiptStatus,
    repo_root: String,
    #[serde(default)]
    project: Option<String>,
}

pub fn find_open(
    root: &Path,
    project: &str,
    env: &str,
    repo_root: &Path,
) -> Result<Option<PathBuf>, ReceiptError> {
    let dir = receipt_dir(root, project, env);
    let entries = match fs::read_dir(&dir) {
        Ok(entries) => entries,
        Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
        Err(source) => return Err(io_error(&dir, source)),
    };
    let mut open = Vec::new();
    for entry in entries {
        let entry = entry.map_err(|source| io_error(&dir, source))?;
        let path = entry.path();
        if path.extension().and_then(|ext| ext.to_str()) != Some("json") {
            continue;
        }
        // Only the summary must parse, so finished receipts from other
        // versions and stray files do not block attach.
        let bytes = fs::read(&path).map_err(|source| io_error(&path, source))?;
        let Ok(summary) = serde_json::from_slice::<ReceiptSummary>(&bytes) else {
            continue;
        };
        if summary.status != ReceiptStatus::InProgress
            || summary.repo_root != repo_root.to_string_lossy()
        {
            continue;
        }
        read_receipt(&path).map_err(|error| {
            ReceiptError::Invalid(format!(
                "unfinished receipt `{}` cannot be resumed: {error}",
                path.display()
            ))
        })?;
        open.push(path);
    }
    match open.len() {
        0 => Ok(None),
        1 => Ok(open.pop()),
        _ => Err(ReceiptError::MultipleOpen(
            open.iter()
                .map(|path| path.display().to_string())
                .collect::<Vec<_>>()
                .join(", "),
        )),
    }
}

/// Reads a receipt this version of Shipslip can fully interpret.
pub fn read(path: &Path) -> Result<Receipt, ReceiptError> {
    read_receipt(path)
}

#[derive(Deserialize)]
struct VersionProbe {
    version: u32,
}

fn read_receipt(path: &Path) -> Result<Receipt, ReceiptError> {
    let bytes = fs::read(path).map_err(|source| io_error(path, source))?;
    // Check the version first so a newer receipt reports its version
    // instead of a field error.
    let probe: VersionProbe =
        serde_json::from_slice(&bytes).map_err(|source| ReceiptError::Parse {
            path: path.to_path_buf(),
            source,
        })?;
    if probe.version != DEPLOY_VERSION && probe.version != UP_VERSION {
        return Err(ReceiptError::Version(probe.version));
    }
    let receipt: Receipt =
        serde_json::from_slice(&bytes).map_err(|source| ReceiptError::Parse {
            path: path.to_path_buf(),
            source,
        })?;
    if (receipt.kind == ReceiptKind::Up) != (receipt.version == UP_VERSION) {
        return Err(ReceiptError::Invalid(
            "receipt kind does not match its schema version".into(),
        ));
    }
    if receipt.run_id.is_empty()
        || !receipt
            .run_id
            .bytes()
            .all(|byte| byte.is_ascii_hexdigit() || byte == b'-')
    {
        return Err(ReceiptError::Invalid("invalid run id".into()));
    }
    Ok(receipt)
}

fn receipt_dir(root: &Path, project: &str, env: &str) -> PathBuf {
    root.join(safe_component(project)).join(safe_component(env))
}

fn safe_component(value: &str) -> String {
    let mut output = String::new();
    for byte in value.bytes() {
        if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_') {
            output.push(byte as char);
        } else {
            output.push_str(&format!("~{byte:02x}"));
        }
    }
    output
}

/// Removes color sequences (`ESC [ digits/semicolons m`) that tools like
/// Composer and Artisan write, so stored output reads as plain text. Other
/// control characters remain for the caller to escape.
pub fn strip_color(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    let mut rest = text;
    while let Some(start) = rest.find("\x1b[") {
        out.push_str(&rest[..start]);
        let after = &rest[start + 2..];
        let params = after
            .find(|c: char| !(c.is_ascii_digit() || c == ';'))
            .unwrap_or(after.len());
        if after[params..].starts_with('m') {
            rest = &after[params + 1..];
        } else {
            out.push('\x1b');
            rest = &rest[start + 1..];
        }
    }
    out.push_str(rest);
    out
}

/// `2026-10-07 14:02:11Z`.
pub fn format_utc(millis: u128) -> String {
    let secs = millis / 1000;
    let days = (secs / 86_400) as i64;
    let time = secs % 86_400;
    // Days since 1970-01-01 to a civil date (Howard Hinnant's algorithm).
    let z = days + 719_468;
    let era = z.div_euclid(146_097);
    let doe = z.rem_euclid(146_097);
    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let day = doy - (153 * mp + 2) / 5 + 1;
    let month = if mp < 10 { mp + 3 } else { mp - 9 };
    let year = yoe + era * 400 + i64::from(month <= 2);
    format!(
        "{year:04}-{month:02}-{day:02} {:02}:{:02}:{:02}Z",
        time / 3600,
        time / 60 % 60,
        time % 60
    )
}

/// `2m 44s`, `1h 3m`, or `850 ms`.
pub fn format_duration(millis: u128) -> String {
    let secs = millis / 1000;
    match secs {
        0 => format!("{millis} ms"),
        1..60 => format!("{secs}s"),
        60..3600 => format!("{}m {}s", secs / 60, secs % 60),
        _ => format!("{}h {}m", secs / 3600, secs / 60 % 60),
    }
}

/// ` in 2m 44s` for a step with both times, otherwise nothing.
pub fn duration_suffix(times: StepTimes) -> String {
    times
        .duration_ms()
        .map(|millis| format!(" in {}", format_duration(millis)))
        .unwrap_or_default()
}

/// The duration for a step with both times, or `, started 14:02:11Z, end not
/// known` for one whose end this Mac did not see.
pub fn timing_suffix(times: StepTimes, time_of_day: impl Fn(u128) -> String) -> String {
    if let Some(seen) = times.result_seen_at_ms {
        return format!(
            "{}, result seen {}",
            match times.started_at_ms {
                Some(started) => format!(", started {}, end not known", time_of_day(started)),
                None => ", end not known".into(),
            },
            time_of_day(seen)
        );
    }
    match (times.started_at_ms, times.finished_at_ms) {
        (Some(started), None) => format!(", started {}, end not known", time_of_day(started)),
        _ => duration_suffix(times),
    }
}

pub(crate) fn now_ms() -> u128 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|duration| duration.as_millis())
        .unwrap_or_default()
}

fn io_error(path: &Path, source: io::Error) -> ReceiptError {
    ReceiptError::Io {
        path: path.to_path_buf(),
        source,
    }
}

fn private_dir(path: &Path) -> Result<(), ReceiptError> {
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        fs::set_permissions(path, fs::Permissions::from_mode(0o700))
            .map_err(|source| io_error(path, source))?;
    }
    Ok(())
}

fn write_atomic(path: &Path, receipt: &Receipt) -> Result<(), ReceiptError> {
    let mut bytes = serde_json::to_vec_pretty(receipt)?;
    bytes.push(b'\n');
    crate::private_file::write_atomic(path, &bytes).map_err(|source| io_error(path, source))
}

#[cfg(test)]
pub(crate) mod tests;