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,
};
const DEPLOY_VERSION: u32 = 1;
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 {
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>,
#[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,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum UnfinishedCause {
Detached,
AppClosed,
ConnectionLost,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ReceiptKind {
#[default]
Deploy,
Up,
}
impl ReceiptKind {
fn is_deploy(&self) -> bool {
*self == Self::Deploy
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Receipt {
pub version: u32,
#[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>,
#[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>,
#[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>,
#[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>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub checks_skip_reason: Option<crate::observation::CheckSkipReason>,
#[serde(default)]
pub actor: Option<Actor>,
}
#[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)),
}
}
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(),
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(),
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))
}
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),
})
}
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)),
}
}
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;
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);
})
}
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> {
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))
}
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)
}
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(())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HistoryPaths {
pub current: PathBuf,
pub legacy: PathBuf,
}
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)
}
#[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;
}
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(", "),
)),
}
}
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))?;
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
}
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
}
pub fn format_utc(millis: u128) -> String {
let secs = millis / 1000;
let days = (secs / 86_400) as i64;
let time = secs % 86_400;
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
)
}
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),
}
}
pub fn duration_suffix(times: StepTimes) -> String {
times
.duration_ms()
.map(|millis| format!(" in {}", format_duration(millis)))
.unwrap_or_default()
}
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;