shipslip 0.2.2

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
//! Durable local record of a deploy, 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::{
    DeployOutcome, DeployTarget, MaintenancePhase, Preview, RunPlan, SmokeResult, StepStatus,
    WatchResult,
};

const VERSION: u32 = 1;
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 ReceiptStep {
    pub index: usize,
    pub command: String,
    pub status: ReceiptStepStatus,
    pub exit_code: Option<i32>,
    pub output: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Receipt {
    pub version: u32,
    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>,
    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>,
    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>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub warnings: Vec<String>,
    #[serde(default)]
    pub watch: Option<WatchResult>,
    #[serde(default)]
    pub smoke: Option<SmokeResult>,
}

impl Receipt {
    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 {
                index,
                command,
                status: if index > 0 && index < first {
                    ReceiptStepStatus::Skipped
                } else {
                    ReceiptStepStatus::Pending
                },
                exit_code: None,
                output: Vec::new(),
            })
            .collect();
        Self {
            version: VERSION,
            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(),
            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,
            app_left_down: false,
            mutation_started: false,
            outcome: None,
            server_head_at_end: None,
            tree_dirty: None,
            last_message: None,
            warnings: Vec::new(),
            watch: None,
            smoke: None,
        }
    }

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

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> {
        let receipt = Receipt::from_preview(project, repo_root, preview);
        let dir = receipt_dir(root, 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),
        })
    }

    /// 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()
    }

    pub fn set_owner_pid(&self, pid: u32) -> Result<(), ReceiptError> {
        self.update(|receipt| receipt.owner_pid = pid)
    }

    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) -> 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;
            }
        })
    }

    pub fn finish_step(
        &self,
        index: usize,
        status: StepStatus,
        exit_code: Option<i32>,
    ) -> 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;
            }
        })
    }

    pub fn begin_maintenance(&self, phase: MaintenancePhase) -> Result<(), ReceiptError> {
        self.update(|receipt| {
            receipt.phase = match phase {
                MaintenancePhase::Down => ReceiptPhase::MaintenanceDown,
                MaintenancePhase::Up => ReceiptPhase::MaintenanceUp,
            };
            receipt.mutation_started = true;
            if phase == MaintenancePhase::Down {
                receipt.app_left_down = true;
            }
        })
    }

    pub fn finish_maintenance(
        &self,
        phase: MaintenancePhase,
        status: StepStatus,
        exit_code: Option<i32>,
    ) -> 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_done = status == StepStatus::Ok;
                    receipt.app_left_down = crate::event::down_may_have_started(&status);
                }
                MaintenancePhase::Up => {
                    receipt.maintenance_up_status = Some(status.clone());
                    receipt.maintenance_up_exit_code = exit_code;
                    receipt.maintenance_up_done = status == StepStatus::Ok;
                    receipt.app_left_down = status != StepStatus::Ok;
                }
            }
        })
    }

    pub fn output_line(&self, key: &str, line: &str) {
        let mut receipt = self.state.lock().unwrap();
        if let Some(index) = key
            .strip_prefix("step-")
            .and_then(|index| index.parse::<usize>().ok())
        {
            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 fn record_outcome(&self, outcome: DeployOutcome) -> Result<(), ReceiptError> {
        self.update(|receipt| receipt.outcome = Some(outcome))
    }

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

    pub fn history_path(&self) -> PathBuf {
        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");
        root.join("signatures")
            .join(project_dir.file_name().expect("project directory has name"))
            .join(env_dir.file_name().expect("environment directory has name"))
            .join("history.json")
    }

    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);
        })
    }

    fn update(&self, change: impl FnOnce(&mut Receipt)) -> Result<(), ReceiptError> {
        self.claim()?;
        let mut receipt = self.state.lock().unwrap();
        let mut next = receipt.clone();
        change(&mut next);
        write_atomic(&self.path, &next)?;
        *receipt = next;
        Ok(())
    }
}

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`] needs, readable from any receipt version.
#[derive(Deserialize)]
struct ReceiptSummary {
    status: ReceiptStatus,
    repo_root: 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(", "),
        )),
    }
}

fn read_receipt(path: &Path) -> Result<Receipt, ReceiptError> {
    let bytes = fs::read(path).map_err(|source| io_error(path, source))?;
    let receipt: Receipt =
        serde_json::from_slice(&bytes).map_err(|source| ReceiptError::Parse {
            path: path.to_path_buf(),
            source,
        })?;
    if receipt.version != VERSION {
        return Err(ReceiptError::Version(receipt.version));
    }
    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
}

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))
}