use std::fs::{self, OpenOptions};
use std::io::{Read as _, Write as _};
use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use anyhow::{Context, Result, bail};
use serde_json::Value;
use crate::cli::{
AccuracyArgs, BoundsArgs, FetchArgs, PublishArgs, RefreshArgs, UploadArgs, VerifyArgs,
};
use crate::config::{DatasetConfig, PeriodKind, Reader};
use crate::exit::Exit;
use crate::layout::{
self, Settings, build_prefix, current_key, data_root, format_utc_millis, read_json, repo_root,
settings, unix_seconds,
};
use crate::period::{Period, period_end_of};
use crate::prune;
use crate::remote;
use crate::s3::S3;
use crate::settings::{self, Deployment};
use crate::{accuracy, bounds, fetch, run as run_verb, verify};
pub const GATES: [&str; 14] = [
"plan",
"sources",
"build",
"verify",
"accuracy",
"bounds",
"boundaries",
"stage",
"upload-plan",
"upload",
"remote",
"publish",
"pointer",
"live",
];
pub const LOCK_STALE_SECS: i64 = 12 * 60 * 60;
pub const LOGS_KEPT: usize = 60;
pub const PROBE_TIMEOUT_MILLIS: u64 = 10 * 60 * 1000;
pub const PROBE_INTERVAL_MILLIS: u64 = 30 * 1000;
const CONF_DIR: &str = "packages/dataset-builder/data/datasets";
const UNKNOWN: &str = "unknown";
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Status {
Prelim,
Final,
}
impl Status {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Prelim => "prelim",
Self::Final => "final",
}
}
const fn rank(self) -> u8 {
match self {
Self::Prelim => 0,
Self::Final => 1,
}
}
fn parse(text: &str) -> Option<Self> {
match text {
"prelim" => Some(Self::Prelim),
"final" => Some(Self::Final),
_ => None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Candidate {
pub key: String,
pub period_end: String,
pub status: Status,
pub file: String,
pub name: String,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Pointer {
pub build_id: String,
pub period_end: String,
pub status: Option<String>,
pub boundary_release: Option<String>,
pub boundary_tiles_revision: Option<u8>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SeriesRef {
pub period_end: String,
pub status: Option<String>,
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Decision {
NothingNew {
reason: String,
candidate: Option<Candidate>,
},
New {
candidate: Candidate,
},
Upgrade {
candidate: Candidate,
},
}
impl Decision {
#[must_use]
pub const fn candidate(&self) -> Option<&Candidate> {
match self {
Self::NothingNew { .. } => None,
Self::New { candidate } | Self::Upgrade { candidate } => Some(candidate),
}
}
#[must_use]
pub const fn kind(&self) -> &'static str {
match self {
Self::NothingNew { .. } => "nothing-new",
Self::New { .. } => "new",
Self::Upgrade { .. } => "upgrade",
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct HistoryEntry {
pub at: String,
pub dataset: String,
pub country: String,
pub action: String,
pub build: Option<String>,
pub period: Option<String>,
pub seconds: f64,
pub bytes: u64,
}
#[must_use]
pub fn history_line(entry: &HistoryEntry) -> String {
fn quoted(text: &str) -> String {
serde_json::to_string(text).unwrap_or_else(|_| "\"\"".to_owned())
}
fn optional(value: Option<&str>) -> String {
value.map_or_else(|| "null".to_owned(), quoted)
}
format!(
"{{\"at\":{},\"dataset\":{},\"country\":{},\"action\":{},\"build\":{},\"period\":{},\"seconds\":{:.1},\"bytes\":{}}}\n",
quoted(&entry.at),
quoted(&entry.dataset),
quoted(&entry.country),
quoted(&entry.action),
optional(entry.build.as_deref()),
optional(entry.period.as_deref()),
entry.seconds,
entry.bytes
)
}
#[must_use]
pub fn log_name(millis: i128) -> String {
let text = format_utc_millis(millis);
let stamp: String = text
.chars()
.filter(|c| !matches!(c, '-' | ':' | '.'))
.collect();
let head: String = stamp.chars().take(15).collect();
format!("refresh-{head}Z.log")
}
#[must_use]
pub fn logs_to_prune(names: &[String], keep: usize) -> Vec<String> {
let mut logs: Vec<String> = names
.iter()
.filter(|name| name.starts_with("refresh-") && name.ends_with(".log"))
.cloned()
.collect();
logs.sort();
let excess = logs.len().saturating_sub(keep);
logs.into_iter().take(excess).collect()
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LockInfo {
pub pid: i64,
pub host: String,
pub started: String,
pub command: String,
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Holder {
None,
Live(LockInfo),
Stale(Option<LockInfo>),
}
#[must_use]
pub fn parse_lock(text: &str) -> Option<LockInfo> {
let mut pid = None;
let mut host = UNKNOWN;
let mut started = UNKNOWN;
let mut command = UNKNOWN;
for line in text.split('\n') {
let Some((name, value)) = line.split_once('=') else {
continue;
};
let value = value.trim();
match name.trim() {
"pid" => pid = value.parse::<i64>().ok(),
"host" => host = value,
"started" => started = value,
"command" => command = value,
_ => {}
}
}
let pid = pid?;
if pid <= 0 {
return None;
}
Some(LockInfo {
pid,
host: host.to_owned(),
started: started.to_owned(),
command: command.to_owned(),
})
}
#[must_use]
pub fn lock_text(info: &LockInfo) -> String {
format!(
"pid={}\nhost={}\nstarted={}\ncommand={}\n",
info.pid, info.host, info.started, info.command
)
}
#[must_use]
pub fn lock_is_stale(
info: Option<&LockInfo>,
host: &str,
started_secs: i64,
now: i64,
stale_secs: i64,
alive: impl Fn(i64) -> bool,
) -> bool {
if now - started_secs > stale_secs {
return true;
}
let Some(info) = info else {
return true;
};
if info.host != host {
return false;
}
!alive(info.pid)
}
#[derive(Debug)]
pub struct Lock {
dir: PathBuf,
}
impl Drop for Lock {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.dir);
}
}
impl Lock {
pub fn acquire(
dir: &Path,
now_secs: i64,
command: &str,
log: &mut dyn FnMut(&str),
) -> Result<Self> {
if let Some(parent) = dir.parent() {
fs::create_dir_all(parent).with_context(|| format!("creating {}", parent.display()))?;
}
match fs::create_dir(dir) {
Ok(()) => {
write_lock(dir, now_secs, command)?;
return Ok(Self {
dir: dir.to_path_buf(),
});
}
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {}
Err(error) => {
return Err(error).with_context(|| format!("creating {}", dir.display()));
}
}
let held = holder(dir, now_secs)?;
let Holder::Stale(info) = &held else {
let (pid, host, started) = held_fields(&held);
let refusal = format!(
"another refresh holds {} (pid {pid} on {host} since {started})",
dir.display()
);
log(&refusal);
eprintln!("refresh: {refusal}");
bail!(Exit(2));
};
let pid = info
.as_ref()
.map_or_else(|| UNKNOWN.to_owned(), |held| held.pid.to_string());
log(&format!("lock: moved the stale {pid} lock aside"));
let name = dir.file_name().map_or_else(
|| "refresh.lock".to_owned(),
|n| n.to_string_lossy().into_owned(),
);
let stamp: String = format_utc_millis(i128::from(now_secs) * 1000)
.chars()
.filter(|c| !matches!(c, '-' | ':' | '.'))
.collect();
let aside = {
let mut attempt = 0_u32;
loop {
let suffix = if attempt == 0 {
format!("{name}.stale-{stamp}-{}", std::process::id())
} else {
format!("{name}.stale-{stamp}-{}-{attempt}", std::process::id())
};
let candidate = dir.with_file_name(suffix);
if !candidate.exists() {
break candidate;
}
attempt += 1;
}
};
fs::rename(dir, &aside)
.with_context(|| format!("moving {} to {}", dir.display(), aside.display()))?;
fs::create_dir(dir).with_context(|| format!("creating {}", dir.display()))?;
write_lock(dir, now_secs, command)?;
Ok(Self {
dir: dir.to_path_buf(),
})
}
}
fn held_fields(holder: &Holder) -> (String, String, String) {
match holder {
Holder::Live(info) | Holder::Stale(Some(info)) => (
info.pid.to_string(),
info.host.clone(),
info.started.clone(),
),
Holder::Stale(None) | Holder::None => ("?".to_owned(), "?".to_owned(), "?".to_owned()),
}
}
fn write_lock(dir: &Path, now_secs: i64, command: &str) -> Result<()> {
let info = LockInfo {
pid: i64::from(std::process::id()),
host: hostname(),
started: format_utc_millis(i128::from(now_secs) * 1000),
command: command.to_owned(),
};
let path = dir.join("lock");
fs::write(&path, lock_text(&info)).with_context(|| format!("writing {}", path.display()))
}
pub fn holder(dir: &Path, now_secs: i64) -> Result<Holder> {
if !dir.exists() {
return Ok(Holder::None);
}
let text = fs::read_to_string(dir.join("lock")).unwrap_or_default();
let info = parse_lock(&text);
let started = info
.as_ref()
.and_then(|held| parse_iso_secs(&held.started))
.or_else(|| {
layout::modified_millis(dir)
.ok()
.map(|millis| i64::try_from(millis / 1000).unwrap_or(0))
})
.unwrap_or(0);
let host = hostname();
if lock_is_stale(
info.as_ref(),
&host,
started,
now_secs,
LOCK_STALE_SECS,
pid_alive,
) {
return Ok(Holder::Stale(info));
}
Ok(Holder::Live(info.unwrap_or(LockInfo {
pid: 0,
host,
started: UNKNOWN.to_owned(),
command: UNKNOWN.to_owned(),
})))
}
#[must_use]
pub fn hostname() -> String {
if let Some(name) = &deployment().run.hostname {
return name.clone();
}
Command::new("/bin/hostname")
.output()
.ok()
.map(|out| String::from_utf8_lossy(&out.stdout).trim().to_owned())
.filter(|name| !name.is_empty())
.unwrap_or_else(|| UNKNOWN.to_owned())
}
fn pid_alive(pid: i64) -> bool {
Command::new("/bin/kill")
.args(["-0", &pid.to_string()])
.output()
.map_or(true, |out| out.status.success())
}
#[must_use]
fn parse_iso_secs(text: &str) -> Option<i64> {
let (date, time) = text.split_once('T')?;
let days = layout::days_of_date(date)?;
let time = time.trim_end_matches('Z');
let time = time.split('.').next()?;
let mut parts = time.split(':');
let hour: i64 = parts.next()?.parse().ok()?;
let minute: i64 = parts.next()?.parse().ok()?;
let second: i64 = parts.next()?.parse().ok()?;
if parts.next().is_some() {
return None;
}
Some(days * 86_400 + hour * 3_600 + minute * 60 + second)
}
pub fn candidates(text: &str, kind: PeriodKind) -> Result<Vec<Candidate>> {
let mut out = Vec::new();
for line in text.split('\n') {
let text = line.trim();
if text.is_empty() || text.starts_with('#') {
continue;
}
let parts: Vec<&str> = text.split_whitespace().collect();
let status = parts
.first()
.and_then(|word| Status::parse(word))
.with_context(|| format!("not a final/prelim list line: {text}"))?;
let file = parts.get(1).copied().unwrap_or_default();
let name = parts.get(2).copied().map_or_else(
|| {
Path::new(file)
.file_name()
.map_or_else(String::new, |n| n.to_string_lossy().into_owned())
},
str::to_owned,
);
let (year, month, index) = period_in_name(&name)
.or_else(|| period_in_name(file))
.with_context(|| format!("no period in the list line: {text}"))?;
if kind == PeriodKind::Dekad && index > 3 {
bail!("pentad {index} in a dekad list line: {text}");
}
let key = format!("{year:04}.{month:02}.{index}");
let period_end = key_end(&key, kind)?;
out.push(Candidate {
key,
period_end,
status,
file: file.to_owned(),
name,
});
}
Ok(out)
}
fn period_in_name(name: &str) -> Option<(i64, u8, u8)> {
let base = name
.strip_suffix(".cog")
.or_else(|| name.strip_suffix(".tif"))?;
let mut parts = base.rsplit('.');
let index: u8 = parts.next()?.parse().ok()?;
let month: u8 = parts.next()?.parse().ok()?;
let year = parts.next()?;
if year.len() != 4 {
return None;
}
if !(1..=12).contains(&month) || !(1..=6).contains(&index) {
return None;
}
Some((year.parse().ok()?, month, index))
}
pub fn key_end(key: &str, kind: PeriodKind) -> Result<String> {
let mut parts = key.split('.');
let year: i64 = parts
.next()
.and_then(|part| part.parse().ok())
.with_context(|| format!("not a period key YYYY.MM.P: {key}"))?;
let month: u8 = parts
.next()
.and_then(|part| part.parse().ok())
.with_context(|| format!("not a period key YYYY.MM.P: {key}"))?;
let index: u8 = parts
.next()
.and_then(|part| part.parse().ok())
.with_context(|| format!("not a period key YYYY.MM.P: {key}"))?;
if parts.next().is_some() || !(1..=12).contains(&month) || !(1..=6).contains(&index) {
bail!("not a period key YYYY.MM.P: {key}");
}
let per = match kind {
PeriodKind::Pentad => 6,
PeriodKind::Dekad => 3,
};
Ok(period_end_of(Period { year, month, index }, per))
}
#[must_use]
pub fn decide(
list: &[Candidate],
pointer: Option<&Pointer>,
published: Option<&[SeriesRef]>,
) -> Decision {
let Some(newest) = newest(list) else {
return Decision::NothingNew {
reason: "the source list is empty".to_owned(),
candidate: None,
};
};
let Some(pointer) = pointer else {
return Decision::New {
candidate: newest.clone(),
};
};
if newest.period_end > pointer.period_end {
return Decision::New {
candidate: newest.clone(),
};
}
if newest.period_end == pointer.period_end
&& newest.status == Status::Final
&& pointer.status.as_deref() != Some("final")
{
return Decision::Upgrade {
candidate: newest.clone(),
};
}
if let Some(published) = published {
for period in published.iter().rev() {
if period.status.as_deref() == Some("final") {
continue;
}
if let Some(found) = list.iter().find(|candidate| {
candidate.status == Status::Final && candidate.period_end == period.period_end
}) {
return Decision::Upgrade {
candidate: found.clone(),
};
}
}
}
let reason = if newest.period_end < pointer.period_end {
format!(
"the newest source period ends {}, before the published {}",
newest.period_end, pointer.period_end
)
} else {
format!(
"the published {} already holds the {} period ending {}",
pointer.build_id,
pointer.status.as_deref().unwrap_or("published"),
pointer.period_end
)
};
Decision::NothingNew {
reason,
candidate: Some(newest.clone()),
}
}
fn newest(list: &[Candidate]) -> Option<&Candidate> {
list.iter().max_by(|a, b| {
a.period_end
.cmp(&b.period_end)
.then_with(|| a.status.rank().cmp(&b.status.rank()))
.then_with(|| a.key.cmp(&b.key))
})
}
pub trait Flow {
fn label(&self) -> &str;
fn dataset(&self) -> &str;
fn country(&self) -> &str;
fn period(&self) -> PeriodKind;
fn dry_run(&self) -> bool;
fn src(&self) -> &Path;
fn lists(&mut self) -> Result<()>;
fn list_text(&mut self) -> Result<String>;
fn pointer(&mut self) -> Result<Option<Pointer>>;
fn published_series(&mut self) -> Result<Option<Vec<SeriesRef>>>;
fn download(&mut self) -> Result<()>;
fn sources(&mut self, files: &[PathBuf]) -> Result<()>;
fn build(&mut self) -> Result<String>;
fn verify(&mut self, id: &str) -> Result<()>;
fn accuracy(&mut self, id: &str) -> Result<()>;
fn bounds(&mut self, id: &str) -> Result<()>;
fn boundaries(&mut self, id: &str) -> Result<()>;
fn stage(&mut self, id: &str) -> Result<()>;
fn upload_plan(&mut self, id: &str) -> Result<u64>;
fn upload(&mut self, id: &str) -> Result<u64>;
fn remote(&mut self, id: &str) -> Result<()>;
fn publish(&mut self, id: &str) -> Result<()>;
fn read_back(&mut self) -> Result<Option<Pointer>>;
fn live(&mut self, id: &str) -> Result<()>;
fn rollback(&mut self, id: &str) -> Result<()>;
fn log(&mut self, line: &str);
fn notify(&mut self, text: &str);
fn now(&self) -> i64;
}
#[derive(Debug)]
pub struct GateFailure {
pub gate: &'static str,
pub reason: String,
}
impl std::fmt::Display for GateFailure {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}: {}", self.gate, self.reason)
}
}
impl std::error::Error for GateFailure {}
struct Run<'a> {
flow: &'a mut dyn Flow,
began: i64,
dataset: String,
build: Option<String>,
period: Option<String>,
candidate: Option<Candidate>,
previous: Option<Pointer>,
published: bool,
publish_attempted: bool,
bytes: u64,
}
impl<'a> Run<'a> {
fn new(flow: &'a mut dyn Flow) -> Self {
let began = flow.now();
let dataset = flow.dataset().to_owned();
Self {
flow,
began,
dataset,
build: None,
period: None,
candidate: None,
previous: None,
published: false,
publish_attempted: false,
bytes: 0,
}
}
fn step(
&mut self,
name: &'static str,
run: impl FnOnce(&mut Self) -> Result<()>,
) -> std::result::Result<(), GateFailure> {
let line = format!("{} {name}: dry run, skipped", self.dataset);
if self.flow.dry_run() {
self.flow.log(&line);
return Ok(());
}
run(self).map_err(|error| GateFailure {
gate: name,
reason: error.to_string(),
})
}
fn entry(&self, action: String, build: Option<String>, period: Option<String>) -> HistoryEntry {
let now = self.flow.now();
HistoryEntry {
at: format_utc_millis(i128::from(now) * 1000),
dataset: self.dataset.clone(),
country: self.flow.country().to_owned(),
action,
build,
period,
seconds: elapsed(self.began, now),
bytes: self.bytes,
}
}
fn execute(mut self) -> HistoryEntry {
match self.plan() {
Ok(Some(entry)) => entry,
Ok(None) => match self.gates() {
Ok(()) => {
let build = self.build.clone();
let period = self.period.clone();
self.entry("published".to_owned(), build, period)
}
Err(failure) => self.failed(failure),
},
Err(failure) => self.failed(failure),
}
}
fn plan(&mut self) -> std::result::Result<Option<HistoryEntry>, GateFailure> {
self.plan_inner().map_err(|error| GateFailure {
gate: "plan",
reason: error.to_string(),
})
}
fn plan_inner(&mut self) -> Result<Option<HistoryEntry>> {
let dataset = self.dataset.clone();
self.flow
.log(&format!("{dataset} plan: listing the sources"));
self.flow.lists()?;
let listed = self.flow.list_text()?;
self.previous = self.flow.pointer()?;
let published = self.flow.published_series()?;
let decision = decide(
&candidates(&listed, self.flow.period())?,
self.previous.as_ref(),
published.as_deref(),
);
let detail = match &decision {
Decision::NothingNew { reason, .. } => format!(" ({reason})"),
Decision::New { candidate } | Decision::Upgrade { candidate } => {
format!(" {} {}", candidate.period_end, candidate.status.as_str())
}
};
self.flow
.log(&format!("{dataset} plan: {}{detail}", decision.kind()));
let Some(candidate) = decision.candidate().cloned() else {
return Ok(Some(self.nothing_new()));
};
self.period = Some(candidate.period_end.clone());
if self.flow.dry_run() {
let rest = GATES[1..].join(", ");
self.flow.log(&format!(
"{dataset} would publish {} ({}) through {rest}",
candidate.period_end,
candidate.status.as_str()
));
let period = self.period.clone();
return Ok(Some(self.entry("dry-run".to_owned(), None, period)));
}
self.candidate = Some(candidate);
Ok(None)
}
fn nothing_new(&self) -> HistoryEntry {
let build = self.previous.as_ref().map(|held| held.build_id.clone());
let period = self.previous.as_ref().map(|held| held.period_end.clone());
self.entry("nothing-new".to_owned(), build, period)
}
fn gates(&mut self) -> std::result::Result<(), GateFailure> {
let Some(candidate) = self.candidate.clone() else {
return Ok(());
};
let src = self.flow.src().to_path_buf();
self.step("sources", |run| {
run.flow.download()?;
let files = candidate_files(&src, &candidate);
if files.is_empty() {
bail!(
"{} is not in {}/final or {}/prelim",
candidate.name,
src.display(),
src.display()
);
}
run.flow.sources(&files)
})?;
self.step("build", |run| {
let built = run.flow.build()?;
if !is_build_id(&built) {
bail!("build printed no build id: {built}");
}
run.build = Some(built);
Ok(())
})?;
self.step("verify", |run| {
let id = run.build_id()?.to_owned();
run.flow.verify(&id)
})?;
self.step("accuracy", |run| {
let id = run.build_id()?.to_owned();
run.flow.accuracy(&id)
})?;
self.step("bounds", |run| {
let id = run.build_id()?.to_owned();
run.flow.bounds(&id)
})?;
self.step("boundaries", |run| {
let id = run.build_id()?.to_owned();
run.flow.boundaries(&id)
})?;
self.step("stage", |run| {
let id = run.build_id()?.to_owned();
run.flow.stage(&id)
})?;
self.step("upload-plan", |run| {
let id = run.build_id()?.to_owned();
let keys = run.flow.upload_plan(&id)?;
if keys == 0 {
bail!("the upload plan is empty");
}
run.bytes = keys;
Ok(())
})?;
self.step("upload", |run| {
let id = run.build_id()?.to_owned();
run.bytes = run.flow.upload(&id)?;
Ok(())
})?;
self.step("remote", |run| {
let id = run.build_id()?.to_owned();
run.flow.remote(&id)
})?;
self.step("publish", |run| {
run.publish_attempted = true;
let id = run.build_id()?.to_owned();
run.flow.publish(&id)?;
run.published = true;
Ok(())
})?;
self.step("pointer", |run| {
let build = run.build.clone().unwrap_or_default();
let now = run.flow.read_back()?;
if now.as_ref().map(|held| held.build_id.as_str()) != Some(build.as_str()) {
bail!(
"the bucket pointer names {}, not {build}",
now.as_ref()
.map_or_else(|| "nothing".to_owned(), |held| held.build_id.clone())
);
}
Ok(())
})?;
self.step("live", |run| {
let id = run.build_id()?.to_owned();
run.flow.live(&id)
})?;
Ok(())
}
fn build_id(&self) -> Result<&str> {
self.build.as_deref().context("the build gate ran no build")
}
fn failed(mut self, failure: GateFailure) -> HistoryEntry {
self.flow.log(&format!(
"{} failed at {}: {}",
self.dataset, failure.gate, failure.reason
));
if !self.published && self.publish_attempted {
match self.flow.read_back() {
Err(error) => {
let manual = self.previous.as_ref().map_or_else(
|| "geolith dataset publish <previous build-id> --rollback".to_owned(),
|held| format!("geolith dataset publish {} --rollback", held.build_id),
);
self.flow.log(&format!(
"{} publish outcome unknown ({error}): check the pointer, then run {manual}",
self.dataset
));
self.flow.notify(&format!(
"{}: publish failed and the pointer cannot be read: run {manual}",
self.dataset
));
let build = self.build.clone();
let period = self.period.clone();
return self.entry(format!("failed-at-{}", failure.gate), build, period);
}
Ok(live) => {
let still_previous = self.previous.as_ref().is_some_and(|held| {
held.build_id == live.as_ref().map_or("", |now| &now.build_id)
});
if !still_previous {
self.published = true;
if self.previous.is_none() {
self.flow.log(&format!(
"{} publish wrote {} and there is no previous build to return to: check the live page by hand",
self.dataset,
live.as_ref()
.map_or_else(|| "nothing".to_owned(), |now| now.build_id.clone())
));
}
}
}
}
}
if self.published
&& let Some(previous) = self.previous.clone()
{
self.flow.log(&format!(
"{} rollback: publishing {} again",
self.dataset, previous.build_id
));
match self.flow.rollback(&previous.build_id) {
Ok(()) => {
self.flow.log(&format!(
"{} rollback: pointer back at {}",
self.dataset, previous.build_id
));
self.flow.notify(&format!(
"{}: {} failed, rolled back to {}",
self.dataset, failure.gate, previous.build_id
));
return self.entry(
"rolled-back".to_owned(),
Some(previous.build_id),
Some(previous.period_end),
);
}
Err(error) => {
self.flow.notify(&format!(
"{}: {} failed and the rollback failed: publish {} by hand",
self.dataset, failure.gate, previous.build_id
));
self.flow.log(&format!(
"{} failed at {}: {}; rollback failed: {error}",
self.dataset, failure.gate, failure.reason
));
let build = self.build.clone();
let period = self.period.clone();
return self.entry(format!("failed-at-{}", failure.gate), build, period);
}
}
}
self.flow.notify(&format!(
"{}: refresh failed at {}: {}",
self.dataset,
failure.gate,
truncate(&failure.reason, 120)
));
let build = self.build.clone();
let period = self.period.clone();
self.entry(format!("failed-at-{}", failure.gate), build, period)
}
}
fn candidate_files(src: &Path, candidate: &Candidate) -> Vec<PathBuf> {
let mut files = Vec::with_capacity(2);
for status in [Status::Prelim, Status::Final] {
let path = src.join(status.as_str()).join(&candidate.name);
if path.is_file() {
files.push(path);
}
}
files
}
#[must_use]
pub fn is_build_id(text: &str) -> bool {
let Some((date, rest)) = text.split_once('.') else {
return false;
};
if layout::days_of_date(date).is_none() {
return false;
}
let Some(stamp) = rest.strip_suffix('Z') else {
return false;
};
let Some((day, time)) = stamp.split_once('T') else {
return false;
};
day.len() == 8
&& day.bytes().all(|b| b.is_ascii_digit())
&& time.len() == 4
&& time.bytes().all(|b| b.is_ascii_digit())
}
fn truncate(text: &str, count: usize) -> String {
text.chars().take(count).collect()
}
fn elapsed(began: i64, now: i64) -> f64 {
f64::from(i32::try_from(now.saturating_sub(began)).unwrap_or(i32::MAX))
}
#[must_use]
pub fn pair_label(dataset: &str, country: &str, single_country: bool) -> String {
if single_country {
dataset.to_owned()
} else {
format!("{dataset}/{country}")
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Pair {
pub dataset: String,
pub country: String,
}
pub fn published_pairs(
candidates: &[Pair],
read: &dyn Fn(&Pair) -> Result<Option<Pointer>>,
report: &mut dyn FnMut(&str),
) -> Vec<Pair> {
let mut pairs = Vec::new();
for pair in candidates {
match read(pair) {
Ok(None) => {
report(&format!(
"{}/{}: not published, skipped",
pair.dataset, pair.country
));
continue;
}
Err(error) => report(&format!(
"{}/{}: cannot read the pointer ({error}), kept",
pair.dataset, pair.country
)),
Ok(Some(_)) => {}
}
pairs.push(pair.clone());
}
pairs
}
pub fn run_all(
flows: Vec<Box<dyn Flow + '_>>,
write: &mut dyn FnMut(&HistoryEntry) -> Result<()>,
) -> Result<(Vec<HistoryEntry>, bool)> {
let mut entries = Vec::with_capacity(flows.len());
let mut failed = false;
for mut flow in flows {
let label = flow.label().to_owned();
flow.log(&format!("{label}: refresh start"));
let entry = run_dataset(flow.as_mut());
write(&entry)?;
let build = entry
.build
.as_ref()
.map_or_else(String::new, |id| format!(" {id}"));
flow.log(&format!(
"{label}: {}{build} ({:.0}s)",
entry.action, entry.seconds
));
if entry.action.starts_with("failed") || entry.action == "rolled-back" {
failed = true;
}
entries.push(entry);
}
Ok((entries, failed))
}
pub fn run_dataset(flow: &mut dyn Flow) -> HistoryEntry {
Run::new(flow).execute()
}
pub fn run(args: &RefreshArgs) -> Result<()> {
let root = data_root()?;
let repo = repo_root()?;
let refresh_dir = root.join("datasets/refresh");
let log_dir = refresh_dir.join("logs");
rotate_logs(&log_dir)?;
let log_path = log_dir.join(log_name(now_millis()));
let dry_run = args.dry_run;
let datasets = match &args.dataset {
Some(id) => vec![id.clone()],
None => prune::published_datasets(&repo.join(CONF_DIR))?,
};
let countries = match &args.country {
Some(cc) => vec![cc.to_lowercase()],
None => match &deployment().run.country {
Some(cc) if !cc.is_empty() => vec![cc.to_lowercase()],
_ => countries_of(&repo)?,
},
};
let single_country = countries.len() == 1;
if let Some(refusal) = preflight(deployment(), dry_run) {
let ctx = Ctx {
refresh_dir: refresh_dir.clone(),
log_path,
};
ctx.log(&format!("preflight: {refusal}"));
notify(&format!(
"datasets refresh cannot start: {}",
truncate(&refusal, 120)
));
append_history(
&ctx.refresh_dir,
&HistoryEntry {
at: format_utc_millis(now_millis()),
dataset: "-".to_owned(),
country: "-".to_owned(),
action: "failed-at-preflight".to_owned(),
build: None,
period: None,
seconds: 0.0,
bytes: 0,
},
)?;
eprintln!("refresh: {refusal}");
bail!(Exit(1));
}
let ctx = Ctx {
refresh_dir,
log_path,
};
let client = match remote::connect(None) {
Ok(client) => Some(client),
Err(error) if dry_run => {
ctx.log(&format!(
"storage: {error:#}; planning against the local stages"
));
None
}
Err(error) => return Err(error),
};
let candidates: Vec<Pair> = datasets
.into_iter()
.flat_map(|dataset| {
countries.iter().map(move |country| Pair {
dataset: dataset.clone(),
country: country.clone(),
})
})
.collect();
let mut report = |line: &str| ctx.log(line);
let readable = |pair: &Pair| -> Result<Option<Pointer>> {
let s = settings(Some(&pair.dataset), Some(&pair.country))?;
match &client {
Some(client) => read_pointer(client, &s),
None => read_local_pointer(&s),
}
};
let pairs = published_pairs(&candidates, &readable, &mut report);
if pairs.is_empty() {
ctx.log("no pair is published: nothing to do");
}
let lock_dir = ctx.refresh_dir.join("refresh.lock");
let command = std::env::args().skip(2).collect::<Vec<_>>().join(" ");
let mut lock_log = |line: &str| ctx.log(line);
let _lock = Lock::acquire(&lock_dir, unix_seconds(), &command, &mut lock_log)?;
let mut flows: Vec<Box<dyn Flow + '_>> = Vec::with_capacity(pairs.len());
for pair in &pairs {
let label = pair_label(&pair.dataset, &pair.country, single_country);
match RealFlow::new(&ctx, pair, label, client.as_ref(), dry_run) {
Ok(flow) => flows.push(Box::new(flow)),
Err(error) => {
ctx.log(&format!(
"{}/{}: cannot start ({error}), kept as a failure",
pair.dataset, pair.country
));
}
}
}
let mut write = |entry: &HistoryEntry| append_history(&ctx.refresh_dir, entry);
let (entries, mut failed) = run_all(flows, &mut write)?;
failed |= entries.len() != pairs.len();
let published_any = entries.iter().any(|entry| entry.action == "published");
if published_any && !dry_run {
ctx.log("prune: starting");
let plan = prune::plan(&prune::collect(&root, &repo)?);
let (deleted, bytes) = prune::apply(&plan)?;
ctx.log(&format!(
"prune: deleted {deleted} items, {}",
prune::human_bytes(bytes)
));
} else {
ctx.log("prune: skipped (nothing published)");
}
let actions = entries
.iter()
.map(|entry| {
format!(
"{} {}",
pair_label(&entry.dataset, &entry.country, single_country),
entry.action
)
})
.collect::<Vec<_>>()
.join(", ");
ctx.log(&format!("done: {actions}"));
if failed {
bail!(Exit(1));
}
Ok(())
}
struct Ctx {
refresh_dir: PathBuf,
log_path: PathBuf,
}
impl Ctx {
fn log(&self, line: &str) {
let text = format!("{} {line}\n", format_utc_millis(now_millis()));
print!("{text}");
let appended = OpenOptions::new()
.create(true)
.append(true)
.open(&self.log_path)
.and_then(|mut file| file.write_all(text.as_bytes()));
let _ = appended;
}
}
struct RealFlow<'a> {
ctx: &'a Ctx,
pair: Pair,
label: String,
s: Settings,
config: DatasetConfig,
client: Option<&'a S3>,
dry_run: bool,
src: PathBuf,
cached: Option<Option<Pointer>>,
}
impl<'a> RealFlow<'a> {
fn new(
ctx: &'a Ctx,
pair: &Pair,
label: String,
client: Option<&'a S3>,
dry_run: bool,
) -> Result<Self> {
let s = settings(Some(&pair.dataset), Some(&pair.country))?;
let config = DatasetConfig::load(&s.config_path)?;
let base = s.data_root.join("datasets").join(&pair.dataset).join("src");
let src = if config.reader == Reader::Windowed {
base.join(&pair.country)
} else {
base
};
Ok(Self {
ctx,
pair: pair.clone(),
label,
s,
config,
client,
dry_run,
src,
cached: None,
})
}
fn lists_dir(&self) -> PathBuf {
self.s
.data_root
.join("datasets")
.join(&self.pair.dataset)
.join(&self.pair.country)
.join("lists")
}
fn client(&self) -> Result<&'a S3> {
self.client
.context("storage is not configured: this step needs the bucket")
}
fn publish_args(&self, id: &str, rollback: bool) -> PublishArgs {
PublishArgs {
build_id: id.to_owned(),
dry_run: false,
bucket: None,
rollback,
dataset: Some(self.pair.dataset.clone()),
country: Some(self.pair.country.clone()),
}
}
}
impl Flow for RealFlow<'_> {
fn label(&self) -> &str {
&self.label
}
fn dataset(&self) -> &str {
&self.pair.dataset
}
fn country(&self) -> &str {
&self.pair.country
}
fn period(&self) -> PeriodKind {
self.config.period
}
fn dry_run(&self) -> bool {
self.dry_run
}
fn src(&self) -> &Path {
&self.src
}
fn lists(&mut self) -> Result<()> {
if self.config.reader == Reader::Windowed {
crate::cdse::source_lists(&self.s, true).map(|_| ())?;
return Ok(());
}
fetch::source_lists(&self.s, true).map(|_| ())
}
fn list_text(&mut self) -> Result<String> {
let path = self.lists_dir().join("series.txt");
fs::read_to_string(&path).with_context(|| format!("reading {}", path.display()))
}
fn pointer(&mut self) -> Result<Option<Pointer>> {
if let Some(cached) = &self.cached {
return Ok(cached.clone());
}
let read = match self.client {
Some(client) => read_pointer(client, &self.s)?,
None => read_local_pointer(&self.s)?,
};
self.cached = Some(read.clone());
Ok(read)
}
fn published_series(&mut self) -> Result<Option<Vec<SeriesRef>>> {
let Some(pointer) = self.pointer()? else {
return Ok(None);
};
let path = self
.s
.stage_root
.join(&pointer.build_id)
.join(build_prefix(&self.s, &pointer.build_id))
.join("series.json");
if !path.is_file() {
return Ok(None);
}
let value = read_json(&path)?;
let periods = value
.get("periods")
.and_then(Value::as_array)
.cloned()
.unwrap_or_default();
Ok(Some(
periods
.iter()
.map(|period| SeriesRef {
period_end: period
.get("period_end")
.and_then(Value::as_str)
.unwrap_or_default()
.to_owned(),
status: period
.get("status")
.and_then(Value::as_str)
.map(str::to_owned),
})
.collect(),
))
}
fn download(&mut self) -> Result<()> {
fetch::run(&FetchArgs {
baseline: false,
boundaries: false,
mode: None,
country: self.pair.country.clone(),
dataset: Some(self.pair.dataset.clone()),
})
}
fn sources(&mut self, files: &[PathBuf]) -> Result<()> {
gate_sources(&self.pair.dataset, files)
}
fn build(&mut self) -> Result<String> {
let dir = run_verb::build(&self.s, false)?;
Ok(dir
.file_name()
.map_or_else(String::new, |name| name.to_string_lossy().into_owned()))
}
fn verify(&mut self, id: &str) -> Result<()> {
verify::run(&VerifyArgs {
build_id: Some(id.to_owned()),
dataset: Some(self.pair.dataset.clone()),
country: Some(self.pair.country.clone()),
})
}
fn accuracy(&mut self, id: &str) -> Result<()> {
accuracy::run(&AccuracyArgs {
build: id.to_owned(),
dataset: Some(self.pair.dataset.clone()),
country: Some(self.pair.country.clone()),
})
}
fn bounds(&mut self, id: &str) -> Result<()> {
bounds::run(&BoundsArgs {
build: id.to_owned(),
dataset: Some(self.pair.dataset.clone()),
country: Some(self.pair.country.clone()),
})
}
fn boundaries(&mut self, id: &str) -> Result<()> {
let stage = self.s.stage_root.join(id);
let current_path = stage.join(current_key(&self.s));
let current = parse_pointer(&read_json(¤t_path)?).with_context(|| {
format!(
"{} lacks the boundary constants of the stage",
current_path.display()
)
})?;
let published = self.pointer()?;
let (kind, detail) = boundary_gate(¤t, published.as_ref());
let line = format!("{} boundaries: {kind} ({detail})", self.pair.dataset);
self.ctx.log(&line);
Ok(())
}
fn stage(&mut self, id: &str) -> Result<()> {
let dir = self.s.stage_root.join(id);
if !dir.join("stage.json").is_file() {
bail!("no stage.json in {}", dir.display());
}
let top = self.s.key_top();
if !dir.join(top).is_dir() {
bail!("no {top}/ in {}", dir.display());
}
Ok(())
}
fn upload_plan(&mut self, id: &str) -> Result<u64> {
let keys = gate_upload_plan(&self.s, id, self.client()?)?;
self.ctx.log(&format!(
"{} upload-plan: {keys} keys, 0 overwrites",
self.pair.dataset
));
Ok(keys)
}
fn upload(&mut self, id: &str) -> Result<u64> {
remote::upload(&UploadArgs {
build_id: id.to_owned(),
dry_run: false,
bucket: None,
dataset: Some(self.pair.dataset.clone()),
country: Some(self.pair.country.clone()),
})?;
uploaded_bytes(&self.s, id)
}
fn remote(&mut self, id: &str) -> Result<()> {
let checked = remote::check_remote(&self.s, id, self.client()?)?;
self.ctx.log(&format!(
"{} remote: {checked} keys match (sizes, and md5 of the large files)",
self.pair.dataset
));
Ok(())
}
fn publish(&mut self, id: &str) -> Result<()> {
remote::publish(&self.publish_args(id, false))
}
fn read_back(&mut self) -> Result<Option<Pointer>> {
read_pointer(self.client()?, &self.s)
}
fn live(&mut self, id: &str) -> Result<()> {
let current = deployment();
let (api, page) = current.publish_urls(&self.pair.dataset, &self.pair.country, id);
if api.is_none() && page.is_none() {
println!("live: skipped (no publish URLs configured)");
return Ok(());
}
let key = current.publish_key()?;
let agent: ureq::Agent = ureq::Agent::config_builder()
.timeout_global(Some(Duration::from_secs(30)))
.http_status_as_error(false)
.build()
.into();
let get = |url: &str| -> Result<(u16, String)> {
let mut request = agent.get(url);
if let Some(key) = &key
&& api.as_deref() == Some(url)
{
request = request.header("authorization", &format!("Bearer {key}"));
}
let mut response = request.call().with_context(|| format!("reading {url}"))?;
let status = response.status().as_u16();
let body = response
.body_mut()
.with_config()
.limit(8 * 1024 * 1024)
.read_to_string()
.unwrap_or_default();
Ok((status, body))
};
let timeout = probe_timeout_millis();
let deadline = now_millis() + i128::from(timeout);
let sleep = |millis: u64| std::thread::sleep(Duration::from_millis(millis));
self.ctx.log(&format!(
"{} live: waiting for the site to name {id}",
self.pair.dataset
));
probe_live(&get, api.as_deref(), page.as_deref(), id, deadline, &sleep)
}
fn rollback(&mut self, id: &str) -> Result<()> {
remote::publish(&self.publish_args(id, true))
}
fn log(&mut self, line: &str) {
self.ctx.log(line);
}
fn notify(&mut self, text: &str) {
notify(text);
}
fn now(&self) -> i64 {
unix_seconds()
}
}
fn _unused(_flow: &RealFlow<'_>) {}
pub fn gate_sources(dataset: &str, files: &[PathBuf]) -> Result<()> {
let floor = if dataset == "rainfall" {
100_000
} else {
1_000_000
};
let mut failures: Vec<String> = Vec::new();
for file in files {
let name = file
.file_name()
.map_or_else(String::new, |n| n.to_string_lossy().into_owned());
let Ok(meta) = fs::metadata(file) else {
failures.push(format!("{name} is missing"));
continue;
};
if meta.len() < floor {
failures.push(format!("{name} is {} bytes (floor {floor})", meta.len()));
}
let mut header = [0_u8; 4];
let read = fs::File::open(file)
.and_then(|mut handle| handle.read_exact(&mut header))
.is_ok();
let tiff = read
&& ((header[0] == b'I' && header[1] == b'I')
|| (header[0] == b'M' && header[1] == b'M'));
if !tiff {
failures.push(format!(
"{name} is not a TIFF (header {:02x}{:02x}{:02x}{:02x})",
header[0], header[1], header[2], header[3]
));
}
let info = Command::new("gdalinfo").args(["-json"]).arg(file).output();
let Ok(info) = info else {
failures.push(format!("{name}: gdalinfo is not on PATH"));
continue;
};
if !info.status.success() {
failures.push(format!(
"{name}: gdalinfo failed: {}",
last_lines(&String::from_utf8_lossy(&info.stderr), 8)
));
continue;
}
let Ok(parsed) = serde_json::from_slice::<Value>(&info.stdout) else {
failures.push(format!("{name}: gdalinfo printed no JSON"));
continue;
};
let sized = parsed
.get("size")
.and_then(Value::as_array)
.is_some_and(|size| {
size.len() == 2
&& size
.iter()
.all(|edge| edge.as_f64().is_some_and(|edge| edge > 0.0))
});
if !sized {
failures.push(format!("{name}: gdalinfo reports no raster size"));
}
if parsed.get("geoTransform").is_none() {
failures.push(format!("{name}: gdalinfo reports no geotransform"));
}
let wkt = parsed
.get("coordinateSystem")
.and_then(|system| system.get("wkt"))
.and_then(Value::as_str)
.unwrap_or_default();
if !wkt.contains("ID[\"EPSG\",4326]]") && !wkt.contains("WGS 84") {
failures.push(format!(
"{name}: coordinate system is not WGS 84 (EPSG:4326)"
));
}
}
if !failures.is_empty() {
for failure in &failures {
eprintln!("sources: {failure}");
}
bail!("{} source file(s) fail the sanity checks", files.len());
}
Ok(())
}
fn last_lines(text: &str, count: usize) -> String {
let lines: Vec<&str> = text.trim_end().lines().collect();
let from = lines.len().saturating_sub(count);
lines[from..].join("\n")
}
#[must_use]
pub fn boundary_gate(current: &Pointer, published: Option<&Pointer>) -> (&'static str, String) {
let Some(published) = published else {
return ("same", "first publish".to_owned());
};
let was = format!(
"{} r{}",
published.boundary_release.as_deref().unwrap_or("none"),
published
.boundary_tiles_revision
.map_or_else(|| "?".to_owned(), |revision| revision.to_string())
);
let now = format!(
"{} r{}",
current.boundary_release.as_deref().unwrap_or("none"),
current
.boundary_tiles_revision
.map_or_else(|| "?".to_owned(), |revision| revision.to_string())
);
if current.boundary_release == published.boundary_release
&& current.boundary_tiles_revision == published.boundary_tiles_revision
{
return ("same", now);
}
(
"changed",
format!("{was} -> {now}: the repo's boundary constants changed"),
)
}
pub fn gate_upload_plan(s: &Settings, id: &str, client: &S3) -> Result<u64> {
let (objects, _copy) = remote::upload_plan(s, id, client)?;
if objects.is_empty() {
bail!("the upload plan is empty");
}
if let Some(foreign) = foreign_key(s, id, objects.iter().map(|file| file.key.as_str())) {
bail!("the plan names keys of another build: {foreign}");
}
Ok(objects.len() as u64)
}
fn foreign_key<'a>(
s: &Settings,
id: &str,
keys: impl IntoIterator<Item = &'a str>,
) -> Option<&'a str> {
let own = format!("/{id}/");
let boundaries = crate::layout::boundaries_prefix(s);
keys.into_iter()
.find(|key| !key.contains(&own) && !key.starts_with(&boundaries))
}
pub fn uploaded_bytes(s: &Settings, id: &str) -> Result<u64> {
let path = s.stage_root.join(id).join("uploaded.json");
let marker = read_json(&path)?;
Ok(marker.get("bytes").and_then(Value::as_u64).unwrap_or(0))
}
#[must_use]
pub fn probe_timeout_millis() -> u64 {
deployment()
.run
.probe_timeout_ms
.unwrap_or(PROBE_TIMEOUT_MILLIS)
}
pub fn probe_live(
get: &dyn Fn(&str) -> Result<(u16, String)>,
api: Option<&str>,
page: Option<&str>,
build: &str,
deadline_millis: i128,
sleep: &dyn Fn(u64),
) -> Result<()> {
let mut api_ok = api.is_none();
let mut page_ok = page.is_none();
let mut last = String::new();
while now_millis() < deadline_millis {
if let (false, Some(api)) = (api_ok, api) {
let (status, body) = get(api)?;
api_ok = status == 200 && body.contains(build);
last = format!("api {status}");
}
if let (false, Some(page)) = (page_ok, page) {
let (status, body) = get(page)?;
page_ok = status == 200 && body.contains(build);
last = format!("{last} page {status}");
}
if api_ok && page_ok {
break;
}
sleep(PROBE_INTERVAL_MILLIS);
}
let word = |ok: bool, url: Option<&str>| match (ok, url) {
(_, None) => "skipped",
(true, Some(_)) => "200",
(false, Some(_)) => "no",
};
println!(
"live: api {} page {} ({build})",
word(api_ok, api),
word(page_ok, page)
);
if !(api_ok && page_ok) {
bail!("live: the site does not name {build} yet ({last})");
}
Ok(())
}
pub fn read_pointer(client: &S3, s: &Settings) -> Result<Option<Pointer>> {
let key = current_key(s);
if client.head(&key)?.is_none() {
return Ok(None);
}
let text = client.get(&key)?;
if text.iter().all(u8::is_ascii_whitespace) {
return Ok(None);
}
let value: Value = serde_json::from_slice(&text)
.with_context(|| format!("{key} is not JSON: unreadable pointer: fix it by hand"))?;
Ok(Some(parse_pointer(&value).with_context(|| {
format!("{key} lacks a build_id or a period_end: unreadable pointer: fix it by hand")
})?))
}
pub fn read_local_pointer(s: &Settings) -> Result<Option<Pointer>> {
let key = current_key(s);
for id in layout::complete_stages(&s.stage_root).iter().rev() {
let path = s.stage_root.join(id).join(&key);
if !path.is_file() {
continue;
}
let value = read_json(&path)?;
let pointer = parse_pointer(&value)
.with_context(|| format!("{} lacks a build_id or a period_end", path.display()))?;
return Ok(Some(pointer));
}
Ok(None)
}
pub fn parse_pointer(value: &Value) -> Result<Pointer> {
let text = |name: &str| {
value
.get(name)
.and_then(Value::as_str)
.filter(|field| !field.is_empty())
.map(str::to_owned)
};
Ok(Pointer {
build_id: text("build_id").context("the pointer has no build_id")?,
period_end: text("period_end").context("the pointer has no period_end")?,
status: text("status"),
boundary_release: text("boundary_release"),
boundary_tiles_revision: value
.get("boundary_tiles_revision")
.and_then(Value::as_u64)
.and_then(|revision| u8::try_from(revision).ok()),
})
}
pub fn countries_of(repo: &Path) -> Result<Vec<String>> {
let dir = repo.join(CONF_DIR).join("countries");
let entries = fs::read_dir(&dir).with_context(|| format!("reading {}", dir.display()))?;
let mut codes: Vec<String> = entries
.flatten()
.map(|entry| entry.file_name().to_string_lossy().into_owned())
.filter_map(|name| name.strip_suffix(".json").map(str::to_lowercase))
.collect();
codes.sort();
Ok(codes)
}
#[must_use]
pub fn preflight(deployment: &Deployment, dry_run: bool) -> Option<String> {
let files = [
deployment.storage.credentials_file.as_deref(),
deployment.publish.credentials_file.as_deref(),
];
let refusals: Vec<String> = files
.into_iter()
.flatten()
.filter_map(credential_refusal)
.collect();
if !refusals.is_empty() {
return Some(refusals.join("; "));
}
if !dry_run {
if let Err(error) = deployment.target() {
return Some(format!("{error:#}"));
}
if let Err(error) = deployment.publish_key() {
return Some(format!("{error:#}"));
}
}
None
}
#[must_use]
pub fn credential_refusal(path: &Path) -> Option<String> {
let meta = fs::metadata(path).ok()?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt as _;
let mode = meta.permissions().mode() & 0o777;
if mode != 0o600 {
return Some(format!(
"{} is mode {mode:o}, not 600 (chmod 600 {})",
path.display(),
path.display()
));
}
}
None
}
fn deployment() -> &'static Deployment {
settings::current()
}
fn rotate_logs(log_dir: &Path) -> Result<()> {
fs::create_dir_all(log_dir).with_context(|| format!("creating {}", log_dir.display()))?;
let entries =
fs::read_dir(log_dir).with_context(|| format!("reading {}", log_dir.display()))?;
let names: Vec<String> = entries
.flatten()
.map(|entry| entry.file_name().to_string_lossy().into_owned())
.collect();
for name in logs_to_prune(&names, LOGS_KEPT) {
let path = log_dir.join(name);
fs::remove_file(&path).with_context(|| format!("removing {}", path.display()))?;
}
Ok(())
}
fn append_history(refresh_dir: &Path, entry: &HistoryEntry) -> Result<()> {
fs::create_dir_all(refresh_dir)
.with_context(|| format!("creating {}", refresh_dir.display()))?;
let path = refresh_dir.join("history.jsonl");
let mut file = OpenOptions::new()
.create(true)
.append(true)
.open(&path)
.with_context(|| format!("opening {}", path.display()))?;
file.write_all(history_line(entry).as_bytes())
.with_context(|| format!("writing {}", path.display()))
}
fn notify(message: &str) {
if !deployment().macos_notification {
return;
}
if std::env::consts::OS != "macos" {
return;
}
let text = message.replace('"', "'");
let script = format!("display notification \"{text}\" with title \"geolith datasets\"");
let _ = Command::new("/usr/bin/osascript")
.args(["-e", &script])
.status();
}
fn now_millis() -> i128 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|elapsed| i128::try_from(elapsed.as_millis()).unwrap_or(i128::MAX))
.unwrap_or(0)
}
#[cfg(test)]
mod tests {
use super::*;
const POINTER_BUILD: &str = "2026-11-10.20261119T0142Z";
const RAINFALL_LINES: &str = "# CHIRPS series\n\
final /products/CHIRPS/v3.0/pentads/global/cogs/chirps-v3.0.2026.10.6.cog\n\
prelim /products/CHIRPS/v3.0/prelim/pentads/global/tifs/chirps-v3.0.2026.11.1.tif\n\
prelim /products/CHIRPS/v3.0/prelim/pentads/global/tifs/chirps-v3.0.2026.11.2.tif\n\
prelim /products/CHIRPS/v3.0/prelim/pentads/global/tifs/chirps-v3.0.2026.11.3.tif";
const NDVI_LINES: &str = "final CLMS/x/2026/10/20/cog/c_gls_NDVI300-NDVI_202610200000_GLOBE_OLCI_V3.0.1.tiff ndvi300-v3.2026.10.2.tif 1280000000\n\
final CLMS/x/2026/11/01/cog/c_gls_NDVI300-NDVI_202611010000_GLOBE_OLCI_V3.0.1.tiff ndvi300-v3.2026.11.1.tif 1280000000";
fn pointer() -> Pointer {
Pointer {
build_id: POINTER_BUILD.to_owned(),
period_end: "2026-11-10".to_owned(),
status: Some("prelim".to_owned()),
boundary_release: Some("2026-10-21.0".to_owned()),
boundary_tiles_revision: Some(2),
}
}
struct Fake {
calls: Vec<String>,
lines: Vec<String>,
alerts: Vec<String>,
list: String,
pointer: Option<Pointer>,
dry_run: bool,
fail_at: Option<&'static str>,
rollback_fails: bool,
publish_writes_first: bool,
read_back_error: bool,
build: String,
live: Option<Pointer>,
src: PathBuf,
now: i64,
period: PeriodKind,
}
impl Fake {
fn new(src: &Path) -> Self {
Self {
calls: Vec::new(),
lines: Vec::new(),
alerts: Vec::new(),
list: RAINFALL_LINES.to_owned(),
pointer: Some(pointer()),
dry_run: false,
fail_at: None,
rollback_fails: false,
publish_writes_first: false,
read_back_error: false,
build: "2026-11-15.20261119T0141Z".to_owned(),
live: Some(pointer()),
src: src.to_path_buf(),
now: 1_763_000_000,
period: PeriodKind::Pentad,
}
}
fn gate(&mut self, name: &'static str) -> Result<()> {
self.calls.push(name.to_owned());
if self.fail_at == Some(name) {
bail!("{name} broke");
}
Ok(())
}
}
impl Flow for Fake {
fn label(&self) -> &str {
"rainfall"
}
fn dataset(&self) -> &str {
"rainfall"
}
fn country(&self) -> &str {
"in"
}
fn period(&self) -> PeriodKind {
self.period
}
fn dry_run(&self) -> bool {
self.dry_run
}
fn src(&self) -> &Path {
&self.src
}
fn lists(&mut self) -> Result<()> {
self.calls.push("lists".to_owned());
Ok(())
}
fn list_text(&mut self) -> Result<String> {
Ok(self.list.clone())
}
fn pointer(&mut self) -> Result<Option<Pointer>> {
Ok(self.pointer.clone())
}
fn published_series(&mut self) -> Result<Option<Vec<SeriesRef>>> {
Ok(None)
}
fn download(&mut self) -> Result<()> {
self.gate("download")
}
fn sources(&mut self, _files: &[PathBuf]) -> Result<()> {
self.gate("sources")
}
fn build(&mut self) -> Result<String> {
self.gate("build")?;
Ok(self.build.clone())
}
fn verify(&mut self, _id: &str) -> Result<()> {
self.gate("verify")
}
fn accuracy(&mut self, _id: &str) -> Result<()> {
self.gate("accuracy")
}
fn bounds(&mut self, _id: &str) -> Result<()> {
self.gate("bounds")
}
fn boundaries(&mut self, _id: &str) -> Result<()> {
self.gate("boundaries")
}
fn stage(&mut self, _id: &str) -> Result<()> {
self.gate("stage")
}
fn upload_plan(&mut self, _id: &str) -> Result<u64> {
self.gate("upload-plan")?;
Ok(401)
}
fn upload(&mut self, _id: &str) -> Result<u64> {
self.gate("upload")?;
Ok(2_023_003)
}
fn remote(&mut self, _id: &str) -> Result<()> {
self.gate("remote")
}
fn publish(&mut self, _id: &str) -> Result<()> {
self.calls.push("publish".to_owned());
if self.fail_at == Some("publish") {
if self.publish_writes_first {
self.live = Some(Pointer {
build_id: self.build.clone(),
period_end: "2026-11-15".to_owned(),
..Pointer::default()
});
}
bail!("publish broke");
}
self.live = Some(Pointer {
build_id: self.build.clone(),
period_end: "2026-11-15".to_owned(),
..Pointer::default()
});
Ok(())
}
fn read_back(&mut self) -> Result<Option<Pointer>> {
if self.read_back_error {
bail!("connection reset");
}
Ok(self.live.clone())
}
fn live(&mut self, _id: &str) -> Result<()> {
self.gate("live")
}
fn rollback(&mut self, id: &str) -> Result<()> {
self.calls.push(format!("rollback {id}"));
if self.rollback_fails {
bail!("publish refused");
}
Ok(())
}
fn log(&mut self, line: &str) {
self.lines.push(line.to_owned());
}
fn notify(&mut self, text: &str) {
self.alerts.push(text.to_owned());
}
fn now(&self) -> i64 {
self.now
}
}
fn source_dir() -> tempfile::TempDir {
let dir = tempfile::tempdir().expect("a temp dir");
for (status, name) in [
("prelim", "chirps-v3.0.2026.11.3.tif"),
("final", "chirps-v3.0.2026.11.1.cog"),
] {
let dir = dir.path().join(status);
std::fs::create_dir_all(&dir).expect("mkdir");
std::fs::write(dir.join(name), "raster").expect("write");
}
dir
}
#[test]
fn candidates_parse_both_list_layouts_and_skip_comments() {
let rain = candidates(RAINFALL_LINES, PeriodKind::Pentad).expect("rainfall list");
assert_eq!(rain.len(), 4);
assert_eq!(rain[3].key, "2026.11.3");
assert_eq!(rain[3].period_end, "2026-11-15");
assert_eq!(rain[3].status, Status::Prelim);
assert_eq!(rain[0].status, Status::Final);
let ndvi = candidates(NDVI_LINES, PeriodKind::Dekad).expect("ndvi list");
assert_eq!(ndvi.len(), 2);
assert_eq!(ndvi[1].key, "2026.11.1");
assert_eq!(ndvi[1].period_end, "2026-11-10");
assert_eq!(ndvi[1].name, "ndvi300-v3.2026.11.1.tif");
}
#[test]
fn a_pentad_in_a_dekad_list_is_an_error() {
let error = candidates("final /x/chirps-v3.0.2026.11.6.cog", PeriodKind::Dekad)
.expect_err("pentad 6");
assert!(error.to_string().contains("pentad 6"), "{error}");
}
#[test]
fn nothing_new_when_the_newest_source_is_not_later_than_the_pointer() {
let list = candidates(
"final /x/chirps-v3.0.2026.11.1.cog\nfinal /x/chirps-v3.0.2026.11.2.cog",
PeriodKind::Pentad,
)
.expect("list");
let held = Pointer {
status: Some("final".to_owned()),
..pointer()
};
let decision = decide(&list, Some(&held), None);
assert_eq!(decision.kind(), "nothing-new");
let Decision::NothingNew { reason, .. } = decision else {
panic!("expected nothing-new");
};
assert!(reason.contains("2026-11-10"), "{reason}");
}
#[test]
fn a_later_period_is_new_and_the_newest_wins() {
let list = candidates(
"final /x/chirps-v3.0.2026.10.6.cog\nprelim /x/chirps-v3.0.2026.11.3.tif",
PeriodKind::Pentad,
)
.expect("list");
let decision = decide(&list, Some(&pointer()), None);
assert_eq!(decision.kind(), "new");
assert_eq!(
decision.candidate().map(|c| c.period_end.as_str()),
Some("2026-11-15")
);
}
#[test]
fn the_final_of_the_published_prelim_period_is_an_upgrade() {
let list =
candidates("final /x/chirps-v3.0.2026.11.2.cog", PeriodKind::Pentad).expect("list");
let decision = decide(&list, Some(&pointer()), None);
assert_eq!(decision.kind(), "upgrade");
assert_eq!(decision.candidate().map(|c| c.status), Some(Status::Final));
}
#[test]
fn a_prelim_in_the_published_series_upgrades_when_its_final_is_out() {
let list = candidates(
"final /x/chirps-v3.0.2026.11.1.cog\nprelim /x/chirps-v3.0.2026.11.2.tif",
PeriodKind::Pentad,
)
.expect("list");
let held = Pointer {
status: Some("final".to_owned()),
..pointer()
};
let series = vec![
SeriesRef {
period_end: "2026-11-05".to_owned(),
status: Some("prelim".to_owned()),
},
SeriesRef {
period_end: "2026-11-10".to_owned(),
status: Some("prelim".to_owned()),
},
];
let decision = decide(&list, Some(&held), Some(&series));
assert_eq!(decision.kind(), "upgrade");
assert_eq!(
decision.candidate().map(|c| c.period_end.as_str()),
Some("2026-11-05")
);
}
#[test]
fn no_pointer_means_new_and_an_empty_list_is_nothing_new() {
let list =
candidates("prelim /x/chirps-v3.0.2026.11.3.tif", PeriodKind::Pentad).expect("list");
assert_eq!(decide(&list, None, None).kind(), "new");
let decision = decide(&[], Some(&pointer()), None);
assert_eq!(decision.kind(), "nothing-new");
let Decision::NothingNew { candidate, .. } = decision else {
panic!("expected nothing-new");
};
assert!(candidate.is_none());
}
#[test]
fn a_lock_parses_its_fields_and_a_dead_pid_or_an_old_start_is_stale() {
let text = lock_text(&LockInfo {
pid: 4242,
host: "mac".to_owned(),
started: "2026-11-19T01:00:00.000Z".to_owned(),
command: "refresh".to_owned(),
});
let info = parse_lock(&text).expect("a holder");
assert_eq!(info.pid, 4242);
assert_eq!(info.host, "mac");
let start = parse_iso_secs("2026-11-19T01:00:00.000Z").expect("start");
let now = parse_iso_secs("2026-11-19T02:00:00.000Z").expect("now");
assert!(!lock_is_stale(
Some(&info),
"mac",
start,
now,
LOCK_STALE_SECS,
|_| true
));
assert!(lock_is_stale(
Some(&info),
"mac",
start,
now,
LOCK_STALE_SECS,
|_| false
));
assert!(!lock_is_stale(
Some(&info),
"box",
start,
now,
LOCK_STALE_SECS,
|_| false
));
assert!(lock_is_stale(
Some(&info),
"box",
start,
start + LOCK_STALE_SECS + 1,
LOCK_STALE_SECS,
|_| true
));
assert!(parse_lock("no fields").is_none());
}
#[test]
fn a_live_lock_is_refused_and_a_stale_one_is_moved_aside() {
let dir = tempfile::tempdir().expect("a temp dir");
let lock = dir.path().join("refresh.lock");
let now = parse_iso_secs("2026-11-19T02:00:00Z").expect("now");
std::fs::create_dir_all(&lock).expect("mkdir");
std::fs::write(
lock.join("lock"),
lock_text(&LockInfo {
pid: i64::from(std::process::id()),
host: hostname(),
started: format_utc_millis(i128::from(now - 60) * 1000),
command: "refresh".to_owned(),
}),
)
.expect("write");
let mut lines = Vec::new();
{
let mut log = |line: &str| lines.push(line.to_owned());
let error = Lock::acquire(&lock, now, "refresh", &mut log).expect_err("a live lock");
assert!(format!("{error}").contains("exit 2"), "{error}");
}
assert_eq!(lines.len(), 1, "{lines:?}");
assert!(lines[0].contains("another refresh holds"), "{lines:?}");
assert!(lock.exists());
std::fs::write(
lock.join("lock"),
lock_text(&LockInfo {
pid: 999_999,
host: hostname(),
started: format_utc_millis(i128::from(now - 60) * 1000),
command: "refresh".to_owned(),
}),
)
.expect("write");
let held = {
let mut log = |line: &str| lines.push(line.to_owned());
Lock::acquire(&lock, now, "refresh", &mut log).expect("a stale lock")
};
assert_eq!(lines.len(), 2, "{lines:?}");
assert!(
lines[1].contains("moved the stale 999999 lock aside"),
"{lines:?}"
);
drop(held);
assert!(!lock.exists(), "the lock is released when dropped");
std::fs::create_dir_all(&lock).expect("mkdir");
std::fs::write(
lock.join("lock"),
lock_text(&LockInfo {
pid: i64::from(std::process::id()),
host: hostname(),
started: format_utc_millis(i128::from(now - LOCK_STALE_SECS - 60) * 1000),
command: "refresh".to_owned(),
}),
)
.expect("write");
let mut old_lines = Vec::new();
let held = {
let mut log_old = |line: &str| old_lines.push(line.to_owned());
Lock::acquire(&lock, now, "refresh", &mut log_old).expect("an old lock")
};
assert!(old_lines[0].contains("moved the stale"), "{old_lines:?}");
drop(held);
}
#[test]
fn history_is_one_json_line_with_a_rounded_duration() {
let entry = HistoryEntry {
at: "2026-11-19T02:30:00.000Z".to_owned(),
dataset: "rainfall".to_owned(),
country: "in".to_owned(),
action: "published".to_owned(),
build: Some("2026-11-15.20261119T0141Z".to_owned()),
period: Some("2026-11-15".to_owned()),
seconds: 12.34,
bytes: 2_023_003,
};
assert_eq!(
history_line(&entry),
"{\"at\":\"2026-11-19T02:30:00.000Z\",\"dataset\":\"rainfall\",\"country\":\"in\",\
\"action\":\"published\",\"build\":\"2026-11-15.20261119T0141Z\",\
\"period\":\"2026-11-15\",\"seconds\":12.3,\"bytes\":2023003}\n"
);
let failed = HistoryEntry {
action: "failed-at-plan".to_owned(),
build: None,
period: None,
..entry
};
assert!(history_line(&failed).contains("\"build\":null,\"period\":null"));
}
#[test]
fn logs_are_named_by_utc_time_and_the_60_newest_stay() {
let millis = 1_795_052_460_000_i128;
assert_eq!(log_name(millis), "refresh-20261119T014100Z.log");
let mut names: Vec<String> = (0..62)
.map(|index| format!("refresh-20261119T{:04}Z.log", 100 + index))
.collect();
names.push("history.jsonl".to_owned());
names.push("notes.txt".to_owned());
let prune = logs_to_prune(&names, 60);
assert_eq!(prune.len(), 2);
assert_eq!(prune[0], "refresh-20261119T0100Z.log");
assert_eq!(prune[1], "refresh-20261119T0101Z.log");
}
#[test]
fn nothing_new_lists_the_sources_and_nothing_else() {
let dir = source_dir();
let mut fake = Fake::new(dir.path());
fake.list = "final /x/chirps-v3.0.2026.11.2.cog".to_owned();
fake.pointer = Some(Pointer {
status: Some("final".to_owned()),
..pointer()
});
let entry = run_dataset(&mut fake);
assert_eq!(entry.action, "nothing-new");
assert_eq!(entry.build.as_deref(), Some(POINTER_BUILD));
assert_eq!(fake.calls, vec!["lists"]);
}
#[test]
fn a_dry_run_reports_the_period_it_would_publish() {
let dir = source_dir();
let mut fake = Fake::new(dir.path());
fake.dry_run = true;
let entry = run_dataset(&mut fake);
assert_eq!(entry.action, "dry-run");
assert_eq!(entry.period.as_deref(), Some("2026-11-15"));
assert_eq!(fake.calls, vec!["lists"]);
assert!(
fake.lines
.iter()
.any(|line| line.contains("would publish 2026-11-15 (prelim)")),
"{:?}",
fake.lines
);
}
#[test]
fn one_failing_pair_does_not_stop_the_next() {
let first_dir = source_dir();
let second_dir = source_dir();
let mut first = Fake::new(first_dir.path());
first.fail_at = Some("sources");
let mut second = Fake::new(second_dir.path());
second.list = "final /x/chirps-v3.0.2026.11.2.cog".to_owned();
second.pointer = Some(Pointer {
status: Some("final".to_owned()),
..pointer()
});
let mut written: Vec<HistoryEntry> = Vec::new();
let mut write = |entry: &HistoryEntry| {
written.push(entry.clone());
Ok(())
};
let (entries, failed) =
run_all(vec![Box::new(first), Box::new(second)], &mut write).expect("history");
assert_eq!(
entries
.iter()
.map(|e| e.action.as_str())
.collect::<Vec<_>>(),
vec!["failed-at-sources", "nothing-new"]
);
assert_eq!(written.len(), 2);
assert!(failed);
}
#[test]
fn a_plan_failure_names_the_gate_in_its_history_line() {
let dir = source_dir();
let mut fake = Fake::new(dir.path());
fake.list = "not a list line".to_owned();
let entry = run_dataset(&mut fake);
assert_eq!(entry.action, "failed-at-plan");
assert_eq!(fake.alerts.len(), 1);
assert!(
fake.alerts[0].contains("failed at plan"),
"{:?}",
fake.alerts
);
assert_eq!(entry.build, None);
}
#[test]
fn a_pair_names_its_dataset_and_country() {
assert_eq!(pair_label("ndvi", "in", true), "ndvi");
assert_eq!(pair_label("ndvi", "us", false), "ndvi/us");
}
#[test]
fn a_published_pair_runs_every_gate_in_the_script_order() {
let dir = source_dir();
let mut fake = Fake::new(dir.path());
let entry = run_dataset(&mut fake);
assert_eq!(entry.action, "published");
assert_eq!(entry.build.as_deref(), Some("2026-11-15.20261119T0141Z"));
assert_eq!(entry.period.as_deref(), Some("2026-11-15"));
assert_eq!(entry.bytes, 2_023_003);
assert_eq!(
fake.calls,
vec![
"lists",
"download",
"sources",
"build",
"verify",
"accuracy",
"bounds",
"boundaries",
"stage",
"upload-plan",
"upload",
"remote",
"publish",
"live",
]
);
}
#[test]
fn every_gate_before_the_live_check_stops_the_pair() {
for gate in [
"sources",
"build",
"verify",
"accuracy",
"bounds",
"boundaries",
"stage",
"upload-plan",
"upload",
"remote",
"publish",
] {
let dir = source_dir();
let mut fake = Fake::new(dir.path());
fake.fail_at = Some(gate);
let entry = run_dataset(&mut fake);
assert_eq!(entry.action, format!("failed-at-{gate}"), "{gate}");
assert!(
!fake.calls.iter().any(|call| call == "live"),
"{gate} reached live"
);
assert_eq!(fake.alerts.len(), 1, "{gate}");
assert!(
fake.alerts[0].contains(&format!("failed at {gate}")),
"{gate}: {:?}",
fake.alerts
);
}
}
#[test]
fn a_publish_that_wrote_the_pointer_before_throwing_rolls_back() {
let dir = source_dir();
let mut fake = Fake::new(dir.path());
fake.fail_at = Some("publish");
fake.publish_writes_first = true;
let entry = run_dataset(&mut fake);
assert_eq!(entry.action, "rolled-back");
assert_eq!(entry.build.as_deref(), Some(POINTER_BUILD));
assert!(
fake.calls.contains(&format!("rollback {POINTER_BUILD}")),
"{:?}",
fake.calls
);
assert!(!fake.calls.iter().any(|call| call == "live"));
}
#[test]
fn a_publish_that_threw_before_writing_leaves_the_pointer_alone() {
let dir = source_dir();
let mut fake = Fake::new(dir.path());
fake.fail_at = Some("publish");
let entry = run_dataset(&mut fake);
assert_eq!(entry.action, "failed-at-publish");
assert!(
!fake.calls.iter().any(|call| call.starts_with("rollback")),
"{:?}",
fake.calls
);
}
#[test]
fn a_failed_live_check_rolls_back_to_the_previous_build() {
let dir = source_dir();
let mut fake = Fake::new(dir.path());
fake.fail_at = Some("live");
let entry = run_dataset(&mut fake);
assert_eq!(entry.action, "rolled-back");
assert_eq!(entry.build.as_deref(), Some(POINTER_BUILD));
assert!(
fake.calls.contains(&format!("rollback {POINTER_BUILD}")),
"{:?}",
fake.calls
);
assert!(
fake.alerts
.iter()
.any(|alert| alert.contains("rolled back to")),
"{:?}",
fake.alerts
);
}
#[test]
fn a_failed_rollback_is_a_failure_line_and_an_alert() {
let dir = source_dir();
let mut fake = Fake::new(dir.path());
fake.fail_at = Some("live");
fake.rollback_fails = true;
let entry = run_dataset(&mut fake);
assert_eq!(entry.action, "failed-at-live");
assert!(
fake.alerts
.iter()
.any(|alert| alert.contains("rollback failed")),
"{:?}",
fake.alerts
);
}
#[test]
fn an_unreadable_pointer_after_a_failed_publish_asks_for_the_manual_command() {
let dir = source_dir();
let mut fake = Fake::new(dir.path());
fake.fail_at = Some("publish");
fake.read_back_error = true;
let entry = run_dataset(&mut fake);
assert_eq!(entry.action, "failed-at-publish");
assert!(
!fake.calls.iter().any(|call| call.starts_with("rollback")),
"{:?}",
fake.calls
);
assert!(
fake.alerts.iter().any(|alert| alert.contains("--rollback")),
"{:?}",
fake.alerts
);
}
}
#[cfg(test)]
mod gate_tests {
use super::*;
use crate::layout::sha256_hex;
use crate::s3::fake::FakeS3;
fn staged(root: &Path) -> (Settings, String) {
staged_with(root, &[])
}
fn staged_with(root: &Path, extra: &[(&str, &[u8])]) -> (Settings, String) {
let id = "2026-11-20.20261120T0000Z";
let s = Settings {
dataset: "rainfall".to_owned(),
cc: "in".to_owned(),
data_root: root.join("data"),
repo: root.join("repo"),
key_root: "datasets/".to_owned(),
boundary_release: "2026-10-21.0".to_owned(),
boundary_tiles_revision: 2,
baseline: "1991-2020".to_owned(),
config_path: root.join("repo/packages/dataset-builder/data/datasets/rainfall.json"),
country_config_path: root
.join("repo/packages/dataset-builder/data/datasets/countries/in.json"),
published_csv: root
.join("repo/packages/dataset-builder/data/datasets/in/published.csv"),
stage_root: root.join("data/datasets/stage"),
};
let dir = s.stage_root.join(id);
let base = format!("datasets/rainfall/in/{id}");
fs::create_dir_all(dir.join(&base)).expect("mkdir");
fs::create_dir_all(dir.join("datasets/rainfall/in")).expect("mkdir");
fs::write(
dir.join(&base).join("index.json"),
b"{\"attribution\":\"x\"}",
)
.expect("write");
fs::write(
dir.join(&base).join("numbers.csv"),
b"id,attribution\na,x\n",
)
.expect("write");
fs::write(
dir.join("datasets/rainfall/in/current.json"),
format!(r#"{{"build_id":"{id}","period_end":"2026-11-18"}}"#),
)
.expect("write");
for (key, bytes) in extra {
let path = dir.join(key);
fs::create_dir_all(path.parent().expect("parent")).expect("mkdir");
fs::write(&path, bytes).expect("write");
}
let entries: Vec<String> = [
format!("{base}/index.json"),
format!("{base}/numbers.csv"),
"datasets/rainfall/in/current.json".to_owned(),
]
.into_iter()
.chain(extra.iter().map(|(key, _)| (*key).to_owned()))
.collect::<Vec<_>>()
.iter()
.map(|key| {
let path = dir.join(key);
format!(
r#"{{"key":"{key}","bytes":{},"sha256":"{}"}}"#,
fs::metadata(&path).expect("metadata").len(),
sha256_hex(&path).expect("digest")
)
})
.collect();
fs::write(
dir.join("stage.json"),
format!(
r#"{{"build_id":"{id}","files":[{}],"staged_at":"2026-11-21T00:00:00Z"}}"#,
entries.join(",")
),
)
.expect("write");
(s, id.to_owned())
}
#[test]
fn a_truncated_raster_fails_the_sources_gate() {
let dir = tempfile::tempdir().expect("a temp dir");
let file = dir.path().join("chirps-v3.0.2026.11.3.tif");
fs::write(&file, b"II*\0").expect("write");
let error = gate_sources("rainfall", &[file]).expect_err("a 4 byte raster");
assert!(error.to_string().contains("source file(s) fail"), "{error}");
}
#[test]
fn a_source_file_that_is_not_there_fails_the_sources_gate() {
let error = gate_sources("rainfall", &[PathBuf::from("/nonexistent/x.tif")])
.expect_err("a missing file");
assert!(
error.to_string().contains("fail the sanity checks"),
"{error}"
);
}
#[test]
fn boundary_gate_names_a_first_publish_a_change_and_a_match() {
let current = Pointer {
boundary_release: Some("2026-10-21.0".to_owned()),
boundary_tiles_revision: Some(2),
..Pointer::default()
};
let (kind, detail) = boundary_gate(¤t, None);
assert_eq!(kind, "same");
assert_eq!(detail, "first publish");
let (kind, detail) = boundary_gate(¤t, Some(¤t));
assert_eq!(kind, "same");
assert_eq!(detail, "2026-10-21.0 r2");
let was = Pointer {
boundary_release: Some("2026-10-21.0".to_owned()),
boundary_tiles_revision: Some(1),
..Pointer::default()
};
let (kind, detail) = boundary_gate(¤t, Some(&was));
assert_eq!(kind, "changed");
assert_eq!(
detail,
"2026-10-21.0 r1 -> 2026-10-21.0 r2: the repo's boundary constants changed"
);
}
const BOUNDARIES: [(&str, &[u8]); 3] = [
(
"datasets/boundaries/in/2026-10-21.0-r2/LICENSE.txt",
b"CC BY 4.0\n",
),
(
"datasets/boundaries/in/2026-10-21.0-r2/areas.parquet",
b"PAR1",
),
(
"datasets/boundaries/in/2026-10-21.0-r2/areas.pmtiles",
b"PMTiles",
),
];
#[test]
fn the_upload_plan_passes_with_the_shared_boundaries_already_in_the_bucket() {
let dir = tempfile::tempdir().expect("a temp dir");
let (s, id) = staged_with(dir.path(), &BOUNDARIES);
let fake = FakeS3::start();
let client = fake.client();
for (key, bytes) in BOUNDARIES {
client.put_overwrite(key, bytes).expect("seed the bucket");
}
let keys = gate_upload_plan(&s, &id, &client).expect("the plan passes");
assert_eq!(keys, 5);
}
#[test]
fn the_upload_plan_passes_with_new_boundaries_of_this_release() {
let dir = tempfile::tempdir().expect("a temp dir");
let (s, id) = staged_with(dir.path(), &BOUNDARIES);
let fake = FakeS3::start();
let keys = gate_upload_plan(&s, &id, &fake.client()).expect("the plan passes");
assert_eq!(keys, 5);
}
#[test]
fn a_key_outside_the_build_and_its_own_boundaries_is_foreign() {
let dir = tempfile::tempdir().expect("a temp dir");
let (s, id) = staged(dir.path());
assert_eq!(id, "2026-11-20.20261120T0000Z");
let own = [
"datasets/rainfall/in/2026-11-20.20261120T0000Z/index.json",
"datasets/boundaries/in/2026-10-21.0-r2/LICENSE.txt",
];
assert_eq!(foreign_key(&s, &id, own), None);
for other in [
"datasets/rainfall/in/2026-11-15.20261119T0141Z/index.json",
"datasets/boundaries/in/2026-10-21.0/LICENSE.txt",
"datasets/boundaries/us/2026-10-21.0-r2/LICENSE.txt",
"datasets/rainfall/in/current.json",
] {
assert_eq!(
foreign_key(&s, &id, [own[0], other, own[1]]),
Some(other),
"{other}"
);
}
}
#[test]
fn an_upload_plan_whose_object_differs_in_the_bucket_is_refused() {
let dir = tempfile::tempdir().expect("a temp dir");
let (s, id) = staged(dir.path());
let fake = FakeS3::start();
let client = fake.client();
let key = format!("datasets/rainfall/in/{id}/index.json");
client
.put_overwrite(&key, b"{\"attribution\":\"other\"}")
.expect("seed the bucket");
let error = gate_upload_plan(&s, &id, &client).expect_err("a conflict");
assert!(error.to_string().contains("never overwritten"), "{error}");
}
#[test]
fn the_live_probe_needs_both_the_api_and_the_page_to_name_the_build() {
let build = "2026-11-15.20261119T0141Z";
let silent = |_: &str| -> Result<(u16, String)> { Ok((200, "nothing here".to_owned())) };
let no_sleep = |_: u64| {};
let error = probe_live(
&silent,
Some("https://api.example/current.json"),
Some("https://example/data/in/rainfall"),
build,
now_millis(),
&no_sleep,
)
.expect_err("a site that never names the build");
assert!(
error.to_string().contains("the site does not name"),
"{error}"
);
let half = |url: &str| -> Result<(u16, String)> {
if url.contains("api.") {
Ok((200, format!("body {build}")))
} else {
Ok((200, "stale page".to_owned()))
}
};
assert!(
probe_live(
&half,
Some("https://api.example/current.json"),
Some("https://example/data/in/rainfall"),
build,
now_millis(),
&no_sleep,
)
.is_err()
);
let both = |_: &str| -> Result<(u16, String)> { Ok((200, format!("body {build}"))) };
probe_live(
&both,
Some("https://api.example/current.json"),
Some("https://example/data/in/rainfall"),
build,
now_millis() + 1000,
&no_sleep,
)
.expect("both name the build");
}
#[test]
fn a_url_that_is_not_configured_is_not_probed() {
let build = "2026-11-15.20261119T0141Z";
let no_sleep = |_: u64| {};
let asked = std::cell::RefCell::new(Vec::<String>::new());
let get = |url: &str| -> Result<(u16, String)> {
asked.borrow_mut().push(url.to_owned());
Ok((200, format!("body {build}")))
};
probe_live(
&get,
None,
Some("https://example/data/in/rainfall"),
build,
now_millis() + 1000,
&no_sleep,
)
.expect("the page names the build");
assert_eq!(
asked.borrow().as_slice(),
["https://example/data/in/rainfall".to_owned()]
);
asked.borrow_mut().clear();
probe_live(&get, None, None, build, now_millis() + 1000, &no_sleep).expect("nothing");
assert!(asked.borrow().is_empty());
let stale = |_: &str| -> Result<(u16, String)> { Ok((200, "stale".to_owned())) };
assert!(
probe_live(
&stale,
None,
Some("https://example/data/in/rainfall"),
build,
now_millis(),
&no_sleep,
)
.is_err()
);
}
fn deployment_of(json: &str) -> Deployment {
Deployment::resolve(None, Some(json), &|_: &str| None).expect("a made-up config")
}
#[test]
fn a_dry_run_needs_no_bucket_and_a_real_run_names_what_is_missing() {
let empty = deployment_of("{}");
assert_eq!(preflight(&empty, true), None);
let refusal = preflight(&empty, false).expect("a real run needs the store");
assert!(
refusal.contains("storage.endpoint is not set; see geolith.example.json"),
"{refusal}"
);
let full =
deployment_of(r#"{"storage":{"endpoint":"https://s3.example.test","bucket":"b"}}"#);
assert_eq!(preflight(&full, false), None);
}
#[test]
fn a_key_file_that_is_readable_by_others_stops_the_run() {
let dir = tempfile::tempdir().expect("a temp dir");
let path = dir.path().join("site.env");
fs::write(&path, "DATASETS_API_KEY=abc\n").expect("write");
let json = format!(
r#"{{"publish":{{"credentials_file":"{}"}}}}"#,
path.display()
);
let deployment = deployment_of(&json);
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt as _;
fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).expect("chmod");
let refusal = preflight(&deployment, true).expect("mode 644 is refused");
assert!(refusal.contains("not 600"), "{refusal}");
fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).expect("chmod");
}
assert_eq!(preflight(&deployment, true), None);
}
#[test]
fn the_local_pointer_is_the_newest_stage_that_holds_one() {
let dir = tempfile::tempdir().expect("a temp dir");
let (s, id) = staged(dir.path());
let pointer = read_local_pointer(&s)
.expect("readable")
.expect("a pointer");
assert_eq!(pointer.build_id, id);
assert_eq!(pointer.period_end, "2026-11-18");
let newer = s.stage_root.join("2026-12-01.20261201T0000Z");
fs::create_dir_all(&newer).expect("mkdir");
fs::write(newer.join("stage.json"), "{}").expect("write");
let pointer = read_local_pointer(&s)
.expect("readable")
.expect("a pointer");
assert_eq!(pointer.build_id, id);
let empty = Settings::for_test("rainfall", "in", "/nonexistent/data");
assert!(read_local_pointer(&empty).expect("readable").is_none());
}
#[test]
fn a_key_the_bucket_does_not_hold_fails_the_remote_gate() {
let dir = tempfile::tempdir().expect("a temp dir");
let (s, id) = staged(dir.path());
let fake = FakeS3::start();
let error = remote::check_remote(&s, &id, &fake.client()).expect_err("an empty bucket");
assert!(
error.to_string().contains("keys differ in the bucket"),
"{error}"
);
}
#[test]
fn the_bytes_an_upload_wrote_come_from_its_marker() {
let dir = tempfile::tempdir().expect("a temp dir");
let (s, id) = staged(dir.path());
fs::write(
s.stage_root.join(&id).join("uploaded.json"),
b"{\"build_id\":\"x\",\"bytes\":2023003}",
)
.expect("write");
assert_eq!(uploaded_bytes(&s, &id).expect("marker"), 2_023_003);
}
}