use std::collections::BTreeMap;
use std::fs;
use std::io::Write as _;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::Duration;
use anyhow::{Context, Result, bail};
use serde_json::Value;
use crate::cli::{
CdseAction, CdseArgs, CdseListArgs, CdseLsArgs, CdseMergeArgs, CdseMissingArgs,
CdseSeriesRangeArgs, CdseWindowArgs,
};
use crate::exit::Exit;
use crate::layout::{Settings, today_utc, unix_seconds};
use crate::s3::sigv4::{Credentials, SignableRequest, amz_date, empty_payload_sha256, sign};
use crate::settings;
pub const DEFAULT_STAC: &str = "https://stac.dataspace.copernicus.eu/v1";
const COLLECTION: &str = "clms_ndvi_global_300m_10daily_v3_cog";
pub const NDVI_GRID: [f64; 6] = [
-180.001_488_095_238_1,
80.001_488_095_238_09,
0.002_976_190_476_204,
-0.002_976_190_476_189_8,
120_960.0,
47_040.0,
];
const DEKADS: [(&str, u8); 3] = [("01", 1), ("11", 2), ("21", 3)];
const FALLBACK_REACH: f64 = 2.0;
pub const S3_ROOT: &str = "CLMS/bio-geophysical/vegetation_indices/ndvi_global_300m_10daily_v3";
pub const DEFAULT_ENDPOINT: &str = "https://eodata.dataspace.copernicus.eu";
const REGION: &str = "default";
const CHUNK_BYTES: u64 = 128 * 1024 * 1024;
const CHUNK_ATTEMPTS: u32 = 5;
const LIST_ATTEMPTS: u32 = 10;
const RETRY_DELAY: u64 = 10;
const BLOCKSIZE: &str = "512";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ListLine {
pub key: String,
pub name: String,
pub bytes: u64,
}
impl ListLine {
#[must_use]
pub fn final_line(&self) -> String {
format!("final {} {} {}", self.key, self.name, self.bytes)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct Group {
name: String,
best: ListLine,
version: String,
replaced: Vec<(ListLine, String)>,
}
fn agent() -> Result<ureq::Agent> {
Ok(ureq::Agent::config_builder()
.timeout_global(Some(Duration::from_secs(1800)))
.http_status_as_error(false)
.build()
.into())
}
fn encode_component(text: &str) -> String {
use std::fmt::Write as _;
let mut out = String::with_capacity(text.len());
for byte in text.bytes() {
if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'~') {
out.push(char::from(byte));
} else {
let _ = write!(out, "%{byte:02X}");
}
}
out
}
#[must_use]
pub fn is_date(text: &str) -> bool {
let bytes = text.as_bytes();
bytes.len() == 10
&& bytes[4] == b'-'
&& bytes[7] == b'-'
&& bytes
.iter()
.enumerate()
.all(|(index, byte)| matches!(index, 4 | 7) || byte.is_ascii_digit())
}
#[must_use]
pub fn compare_versions(a: &str, b: &str) -> std::cmp::Ordering {
let parts = |text: &str| -> Vec<i64> {
let mut out = Vec::new();
let mut digits = String::new();
for byte in text.bytes() {
if byte.is_ascii_digit() {
digits.push(char::from(byte));
} else if !digits.is_empty() {
out.push(digits.parse::<i64>().unwrap_or(0));
digits.clear();
}
}
if !digits.is_empty() {
out.push(digits.parse::<i64>().unwrap_or(0));
}
out
};
let (pa, pb) = (parts(a), parts(b));
for index in 0..pa.len().max(pb.len()) {
let left = pa.get(index).copied().unwrap_or(0);
let right = pb.get(index).copied().unwrap_or(0);
match left.cmp(&right) {
std::cmp::Ordering::Equal => {}
other => return other,
}
}
std::cmp::Ordering::Equal
}
fn parts_of(date: &str) -> (i64, u8, u8) {
let year = date.get(..4).and_then(|v| v.parse().ok()).unwrap_or(0);
let month = date.get(5..7).and_then(|v| v.parse().ok()).unwrap_or(1);
let day = date.get(8..10).and_then(|v| v.parse().ok()).unwrap_or(1);
(year, month, day)
}
fn last_day(year: i64, month: u8) -> u8 {
match month {
1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
4 | 6 | 9 | 11 => 30,
_ if (year % 4 == 0 && year % 100 != 0) || year % 400 == 0 => 29,
_ => 28,
}
}
fn date_of(year: i64, month: i64, day: u8) -> String {
let (year, month) = if month < 1 {
let back = (1 - month) / 12 + 1;
(year - back, (month + 12 * back) as u8)
} else if month > 12 {
(year + (month - 1) / 12, ((month - 1) % 12 + 1) as u8)
} else {
(year, month as u8)
};
format!("{year:04}-{month:02}-{day:02}")
}
fn local_name(year: i64, month: u8, day: &str) -> Option<String> {
let dekad = DEKADS
.iter()
.find(|(start, _)| *start == day)
.map(|(_, index)| index)?;
Some(format!("ndvi300-v3.{year}.{month:02}.{dekad}.tif"))
}
fn get_json(agent: &ureq::Agent, url: &str) -> Result<Value> {
let mut response = agent
.get(url)
.header("accept", "application/geo+json")
.call()
.with_context(|| format!("GET {url}"))?;
let status = response.status().as_u16();
if !(200..300).contains(&status) {
bail!("GET {url}: HTTP {status}");
}
let bytes = response
.body_mut()
.with_config()
.limit(32 * 1024 * 1024)
.read_to_vec()
.with_context(|| format!("reading the body of {url}"))?;
serde_json::from_slice(&bytes).with_context(|| format!("parsing the body of {url}"))
}
fn features(agent: &ureq::Agent, url: &str) -> Result<Vec<Value>> {
let mut out = Vec::new();
let mut next = Some(url.to_owned());
while let Some(url) = next {
let page = get_json(agent, &url)?;
if let Some(list) = page.get("features").and_then(Value::as_array) {
out.extend(list.iter().cloned());
}
next = page
.get("links")
.and_then(Value::as_array)
.and_then(|links| {
links
.iter()
.find(|link| link.get("rel").and_then(Value::as_str) == Some("next"))
})
.and_then(|link| link.get("href").and_then(Value::as_str))
.map(str::to_owned);
}
Ok(out)
}
fn entry_of(item: &Value) -> Result<(ListLine, String)> {
let id = item.get("id").and_then(Value::as_str).unwrap_or("(no id)");
let properties = item.get("properties");
let start = properties
.and_then(|value| value.get("start_datetime"))
.and_then(Value::as_str);
let version = properties
.and_then(|value| value.get("processing:version"))
.and_then(Value::as_str)
.unwrap_or_default()
.to_owned();
let asset = item.get("assets").and_then(|value| value.get("ndvi"));
let href = asset
.and_then(|value| value.get("href"))
.and_then(Value::as_str);
let bytes = asset
.and_then(|value| value.get("file:size"))
.and_then(Value::as_u64);
let Some(start) = start else {
bail!("item {id}: start_datetime is not a dekad start");
};
let Some(name) = dekad_name(start) else {
bail!("item {id}: start_datetime {start} is not a dekad start");
};
let Some(href) = href.filter(|href| href.starts_with("s3://eodata/")) else {
bail!("item {id}: ndvi asset href is not s3://eodata/…");
};
let Some(bytes) = bytes.filter(|bytes| *bytes > 0) else {
bail!("item {id}: ndvi asset has no file:size");
};
Ok((
ListLine {
key: href.trim_start_matches("s3://eodata/").to_owned(),
name,
bytes,
},
version,
))
}
fn dekad_name(start: &str) -> Option<String> {
let date = start.get(..10)?;
if !is_date(date) || start.as_bytes().get(10) != Some(&b'T') {
return None;
}
let (year, month, day) = parts_of(date);
local_name(year, month, &format!("{day:02}"))
}
fn groups(features: &[Value]) -> Result<Vec<Group>> {
let mut by_name: BTreeMap<String, Vec<(ListLine, String)>> = BTreeMap::new();
for feature in features {
let (line, version) = entry_of(feature)?;
by_name
.entry(line.name.clone())
.or_default()
.push((line, version));
}
let mut out = Vec::with_capacity(by_name.len());
for (name, mut entries) in by_name {
entries.sort_by(|a, b| compare_versions(&b.1, &a.1));
let Some((best, version)) = entries.first().cloned() else {
continue;
};
out.push(Group {
name,
best,
version,
replaced: entries.into_iter().skip(1).collect(),
});
}
Ok(out)
}
pub fn list(from: &str, to: &str, stac: &str) -> Result<Vec<String>> {
if !is_date(from) || !is_date(to) {
bail!("list needs --from and --to as YYYY-MM-DD");
}
let stac = stac.trim_end_matches('/');
let url = format!(
"{stac}/collections/{COLLECTION}/items?datetime={}&limit=100",
encode_component(&format!("{from}T00:00:00Z/{to}T23:59:59Z"))
);
let agent = agent()?;
let mut lines = Vec::new();
for group in groups(&features(&agent, &url)?)? {
for (other, version) in &group.replaced {
lines.push(format!(
"# {}: {} ({version}) replaced by {}",
group.name, other.key, group.version
));
}
lines.push(group.best.final_line());
}
Ok(lines)
}
fn name_of_line(line: &str) -> Option<&str> {
let mut parts = line.split(' ');
let status = parts.next()?;
parts.next()?;
let name = parts.next()?;
let bytes = parts.next()?;
if status != "final" || parts.next().is_some() {
return None;
}
if !bytes.bytes().all(|byte| byte.is_ascii_digit()) || !is_ndvi_name(name) {
return None;
}
Some(name)
}
fn is_ndvi_name(name: &str) -> bool {
let Some(rest) = name.strip_prefix("ndvi300-v3.") else {
return false;
};
let Some(rest) = rest.strip_suffix(".tif") else {
return false;
};
let parts: Vec<&str> = rest.split('.').collect();
if parts.len() != 3 {
return false;
}
let [year, month, dekad] = [parts[0], parts[1], parts[2]];
year.len() == 4
&& year.bytes().all(|byte| byte.is_ascii_digit())
&& month.len() == 2
&& month.bytes().all(|byte| byte.is_ascii_digit())
&& matches!(dekad, "1" | "2" | "3")
}
#[must_use]
pub fn missing(list_text: &str, from: &str, to: &str, today: &str) -> Vec<String> {
let have: std::collections::BTreeSet<&str> =
list_text.split('\n').filter_map(name_of_line).collect();
let mut out = Vec::new();
let (year, month, _) = parts_of(from);
let (mut year, mut month) = (year, i64::from(month));
loop {
let month_start = date_of(year, month, 1);
if month_start.as_str() > to {
break;
}
for (day, _) in DEKADS {
let start = date_of(year, month, day.parse().unwrap_or(1));
if start.as_str() < from || start.as_str() > to || start.as_str() > today {
continue;
}
if local_name(year, u8::try_from(month).unwrap_or(1), day)
.is_some_and(|name| !have.contains(name.as_str()))
{
out.push(format!("{S3_ROOT}/{year}/{month:02}/{day}/"));
}
}
month += 1;
if month > 12 {
month = 1;
year += 1;
}
}
out
}
fn s3_ndvi(line: &str) -> Option<(String, String, String, u64)> {
let (key, bytes) = line.rsplit_once(' ')?;
let bytes = bytes.parse::<u64>().ok()?;
if !key.contains("_cog/") {
return None;
}
let file = key.rsplit('/').next()?;
let parts: Vec<&str> = file.split('_').collect();
if parts.len() != 7 || parts[0] != "c" || parts[1] != "gls" || parts[2] != "NDVI300-NDVI" {
return None;
}
if parts[4] != "GLOBE" || parts[5].is_empty() {
return None;
}
let stamp = parts[3];
if stamp.len() != 12 || !stamp.bytes().all(|byte| byte.is_ascii_digit()) {
return None;
}
let version = parts[6].strip_suffix(".tiff")?;
let digits = version.strip_prefix('V')?;
let numbers: Vec<&str> = digits.split('.').collect();
if numbers.is_empty()
|| !numbers
.iter()
.all(|part| !part.is_empty() && part.bytes().all(|byte| byte.is_ascii_digit()))
{
return None;
}
let (year, month, day) = (
stamp.get(0..4)?.parse::<i64>().ok()?,
stamp.get(4..6)?.parse::<u8>().ok()?,
stamp.get(6..8)?,
);
let name = local_name(year, month, day)?;
Some((key.to_owned(), name, version.to_owned(), bytes))
}
#[must_use]
pub fn merge(list_text: &str, s3_text: &str) -> String {
let lines: Vec<String> = list_text
.split('\n')
.filter(|line| !line.trim().is_empty())
.map(str::to_owned)
.collect();
let have: std::collections::BTreeSet<&str> =
lines.iter().filter_map(|l| name_of_line(l)).collect();
let mut best: BTreeMap<String, (String, u64, String)> = BTreeMap::new();
for line in s3_text.split('\n') {
let Some((key, name, version, bytes)) = s3_ndvi(line.trim()) else {
continue;
};
if have.contains(name.as_str()) {
continue;
}
match best.get(&name) {
Some((_, _, old)) if compare_versions(&version, old) != std::cmp::Ordering::Greater => {
}
_ => {
best.insert(name, (key, bytes, version));
}
}
}
let mut by_name: BTreeMap<String, Vec<String>> = BTreeMap::new();
for line in lines {
let name = name_of_line(&line).map(str::to_owned).or_else(|| {
let rest = line.strip_prefix("# ")?;
Some(rest.split_once(':')?.0.to_owned())
});
by_name
.entry(name.unwrap_or_default())
.or_default()
.push(line);
}
for (name, (key, bytes, _)) in best {
let entry = by_name.entry(name.clone()).or_default();
entry.push(format!(
"# {name}: from the S3 listing (not in the STAC yet)"
));
entry.push(format!("final {key} {name} {bytes}"));
}
by_name
.into_values()
.flat_map(|entries| entries.into_iter())
.collect::<Vec<_>>()
.join("\n")
}
#[derive(Debug, Clone, Copy)]
struct Bounds {
min_x: f64,
min_y: f64,
max_x: f64,
max_y: f64,
}
impl Bounds {
fn empty() -> Self {
Self {
min_x: f64::INFINITY,
min_y: f64::INFINITY,
max_x: f64::NEG_INFINITY,
max_y: f64::NEG_INFINITY,
}
}
fn widen(&mut self, geometry: Option<&Value>) {
let mut points = Vec::new();
if let Some(geometry) = geometry {
positions(
geometry.get("coordinates").unwrap_or(&Value::Null),
&mut points,
);
}
for (x, y) in points {
self.min_x = self.min_x.min(x);
self.max_x = self.max_x.max(x);
self.min_y = self.min_y.min(y);
self.max_y = self.max_y.max(y);
}
}
fn is_empty(&self) -> bool {
!self.min_x.is_finite()
}
}
fn positions(value: &Value, out: &mut Vec<(f64, f64)>) {
let Some(array) = value.as_array() else {
return;
};
if let Some(x) = array.first().and_then(Value::as_f64) {
if let Some(y) = array.get(1).and_then(Value::as_f64) {
out.push((x, y));
}
return;
}
for item in array {
positions(item, out);
}
}
pub fn window(
areas: &Path,
outline: Option<&Path>,
country: &str,
grid: [f64; 6],
block: u32,
) -> Result<(i64, i64, u32, u32)> {
let [ox, oy, px, py, width, height] = grid;
if grid.iter().any(|value| !value.is_finite()) || px <= 0.0 || py >= 0.0 {
bail!("--grid must be <x0>,<y0>,<px>,<py>,<width>,<height> with px > 0 > py");
}
if block == 0 {
bail!("--block must be a positive integer");
}
let country = country.to_uppercase();
if country == "IN" && outline.is_none() {
bail!("window for IN needs --outline <Survey of India GeoJSON>");
}
let mut bounds = Bounds::empty();
let areas_json = crate::layout::read_json(areas)?;
for feature in areas_json
.get("features")
.and_then(Value::as_array)
.into_iter()
.flatten()
{
let code = feature
.get("properties")
.and_then(|value| value.get("country"))
.and_then(Value::as_str)
.unwrap_or_default()
.to_uppercase();
if code != country {
continue;
}
bounds.widen(feature.get("geometry"));
}
if bounds.is_empty() {
bail!("{} has no area of country {country}", areas.display());
}
if let Some(outline) = outline {
let outline_json = crate::layout::read_json(outline)?;
for feature in outline_json
.get("features")
.and_then(Value::as_array)
.into_iter()
.flatten()
{
bounds.widen(feature.get("geometry"));
}
}
let block = f64::from(block);
let down = |value: f64| ((value / block).floor() * block).max(0.0);
let up = |value: f64| (value / block).ceil() * block;
let x0 = down(((bounds.min_x - ox) / px).floor() - FALLBACK_REACH);
let y0 = down(((bounds.max_y - oy) / py).floor() - FALLBACK_REACH);
let x1 = width.min(up(((bounds.max_x - ox) / px).ceil() + FALLBACK_REACH));
let y1 = height.min(up(((bounds.min_y - oy) / py).ceil() + FALLBACK_REACH));
if x1 <= x0 || y1 <= y0 {
bail!("the {country} areas lie outside the grid");
}
let (w, h) = (x1 - x0, y1 - y0);
Ok((x0 as i64, y0 as i64, w.round() as u32, h.round() as u32))
}
#[must_use]
pub fn series_range(today: &str) -> (String, String) {
let (year, month, day) = parts_of(today);
let dekad: u8 = if day <= 10 {
0
} else if day <= 20 {
1
} else {
2
};
let end = if dekad < 2 {
date_of(year, i64::from(month), dekad * 10 + 10)
} else {
date_of(year, i64::from(month), last_day(year, month))
};
let start = date_of(year, i64::from(month) - 4, dekad * 10 + 1);
(start, end)
}
#[must_use]
pub fn endpoint() -> String {
settings::current()
.sources
.cdse_endpoint
.clone()
.unwrap_or_else(|| DEFAULT_ENDPOINT.to_owned())
}
pub fn credentials() -> Result<Credentials> {
settings::current().cdse_credentials()?.context(
"set CDSE_S3_ACCESS_KEY and CDSE_S3_SECRET_KEY, or name a sources.cdse_credentials_file \
(CDSE account, S3 keys)",
)
}
struct Source {
agent: ureq::Agent,
endpoint: String,
host: String,
credentials: Credentials,
}
impl Source {
fn new(endpoint: &str, credentials: Credentials) -> Result<Self> {
let rest = endpoint
.split_once("://")
.map_or(endpoint, |(_, rest)| rest);
let host = rest.split('/').next().unwrap_or_default();
if host.is_empty() {
bail!("endpoint {endpoint} is not a URL");
}
Ok(Self {
agent: agent()?,
endpoint: endpoint.trim_end_matches('/').to_owned(),
host: host.to_owned(),
credentials,
})
}
fn get(
&self,
path: &str,
query: &[(String, String)],
range: Option<String>,
limit: u64,
) -> Result<(u16, Vec<u8>)> {
let mut url = format!("{}{path}", self.endpoint);
if !query.is_empty() {
url.push('?');
url.push_str(&crate::s3::sigv4::canonical_query(query));
}
let mut headers = Vec::new();
if let Some(range) = &range {
headers.push(("range".to_owned(), range.clone()));
}
let request = SignableRequest {
method: "GET",
host: &self.host,
path,
query: query.to_vec(),
headers,
payload_sha256: empty_payload_sha256(),
};
let signed = sign(
&request,
&self.credentials,
REGION,
&amz_date(unix_seconds()),
)?;
let mut http = self.agent.get(&url);
for (name, value) in &signed {
http = http.header(name, value);
}
if let Some(range) = range {
http = http.header("range", range);
}
let mut response = http.call().with_context(|| format!("GET {url}"))?;
let status = response.status().as_u16();
let body = response
.body_mut()
.with_config()
.limit(limit)
.read_to_vec()
.with_context(|| format!("reading the body of {url}"))?;
Ok((status, body))
}
}
fn s3_keys(source: &Source, prefixes: &[String]) -> Result<Vec<(String, u64)>> {
let mut out = Vec::new();
for prefix in prefixes {
let mut token: Option<String> = None;
loop {
let mut query = vec![
("list-type".to_owned(), "2".to_owned()),
("prefix".to_owned(), prefix.clone()),
];
if let Some(token) = &token {
query.push(("continuation-token".to_owned(), token.clone()));
}
let mut attempt = 0;
let text = loop {
attempt += 1;
match source.get("/eodata", &query, None, 8 * 1024 * 1024) {
Ok((status, body)) if (200..300).contains(&status) => {
break String::from_utf8_lossy(&body).into_owned();
}
Ok(_) | Err(_) if attempt >= LIST_ATTEMPTS => {
bail!("cannot list s3://eodata/{prefix}");
}
Ok(_) | Err(_) => std::thread::sleep(Duration::from_secs(RETRY_DELAY)),
}
};
for contents in between(&text, "<Contents>", "</Contents>") {
let Some(key) = tag(contents, "Key") else {
continue;
};
let Some(bytes) = tag(contents, "Size").and_then(|size| size.parse::<u64>().ok())
else {
continue;
};
out.push((unescape(key), bytes));
}
token = if text.contains("<IsTruncated>true</IsTruncated>") {
tag(&text, "NextContinuationToken").map(unescape)
} else {
None
};
if token.is_none() {
break;
}
}
}
Ok(out)
}
fn between<'a>(xml: &'a str, start: &str, end: &str) -> Vec<&'a str> {
let mut out = Vec::new();
let mut rest = xml;
while let Some((_, after)) = rest.split_once(start) {
let Some((inside, tail)) = after.split_once(end) else {
break;
};
out.push(inside);
rest = tail;
}
out
}
fn tag<'a>(xml: &'a str, name: &str) -> Option<&'a str> {
let open = format!("<{name}>");
let close = format!("</{name}>");
let (_, after) = xml.split_once(&open)?;
let (inside, _) = after.split_once(&close)?;
Some(inside)
}
fn unescape(text: &str) -> String {
text.replace("&", "&")
.replace("<", "<")
.replace(">", ">")
.replace(""", "\"")
.replace("'", "'")
.replace("'", "'")
}
fn file_size(path: &Path) -> u64 {
fs::metadata(path).map(|meta| meta.len()).unwrap_or(0)
}
fn part_of(dest: &Path) -> PathBuf {
PathBuf::from(format!("{}.part", dest.display()))
}
fn get_range(source: &Source, key: &str, start: u64, end: u64, attempts: u32) -> Result<Vec<u8>> {
let path = format!("/eodata/{key}");
let range = format!("bytes={start}-{end}");
let want = usize::try_from(end - start + 1).unwrap_or(usize::MAX);
let mut attempt = 0;
loop {
attempt += 1;
let last = attempt >= attempts;
match source.get(
&path,
&[],
Some(range.clone()),
u64::try_from(want + 1).unwrap_or(u64::MAX),
) {
Ok((status, bytes)) => {
let partial = if start == 0 {
(200..300).contains(&status)
} else {
status == 206
};
if partial && bytes.len() == want {
return Ok(bytes);
}
if last {
bail!(
"GET {path}: window {start}-{end} answered {status}, {} bytes",
bytes.len()
);
}
}
Err(error) => {
if last {
return Err(error).with_context(|| format!("GET {path}: window {start}-{end}"));
}
}
}
std::thread::sleep(Duration::from_secs(RETRY_DELAY));
}
}
#[must_use]
pub fn list_line(line: &str) -> Option<ListLine> {
let mut parts = line.split_whitespace();
let status = parts.next()?;
let key = parts.next()?;
let name = parts.next()?;
let bytes = parts.next()?;
if status != "final" || parts.next().is_some() || name.contains('/') || !is_ndvi_name(name) {
return None;
}
Some(ListLine {
key: key.to_owned(),
name: name.to_owned(),
bytes: bytes.parse().ok()?,
})
}
fn download_one(
source: &Source,
entry: &ListLine,
dest: &Path,
chunk: u64,
tries: u32,
out: &mut Vec<String>,
) -> Result<()> {
let name = dest
.file_name()
.map(|name| name.to_string_lossy().into_owned())
.unwrap_or_default();
if dest.is_file() && file_size(dest) == entry.bytes {
out.push(format!("SKIP {name}"));
return Ok(());
}
let part = part_of(dest);
if part.is_file() && file_size(&part) > entry.bytes {
fs::remove_file(&part).with_context(|| format!("removing {}", part.display()))?;
}
let mut start = file_size(&part);
if start > 0 {
out.push(format!("RESUME {name} from {start}"));
}
while start < entry.bytes {
let end = (start + chunk - 1).min(entry.bytes - 1);
let bytes = get_range(source, &entry.key, start, end, tries).with_context(|| {
format!("{name}: window {start}-{end} failed after {tries} attempts")
})?;
let mut file = fs::OpenOptions::new()
.create(true)
.append(true)
.open(&part)
.with_context(|| format!("opening {}", part.display()))?;
file.write_all(&bytes)
.with_context(|| format!("writing {}", part.display()))?;
drop(file);
start = end + 1;
}
if file_size(&part) != entry.bytes {
eprintln!(
"size mismatch for {}: got {}, expected {}",
entry.key,
file_size(&part),
entry.bytes
);
fs::remove_file(&part).with_context(|| format!("removing {}", part.display()))?;
bail!("{} is not {} bytes", entry.key, entry.bytes);
}
fs::rename(&part, dest).with_context(|| format!("renaming {}", part.display()))?;
out.push(format!("OK {name}"));
Ok(())
}
pub fn download_full(list: &Path, dest_dir: &Path) -> Result<()> {
let source = Source::new(&endpoint(), credentials()?)?;
download_full_with(&source, list, dest_dir, CHUNK_BYTES, CHUNK_ATTEMPTS)
}
fn download_full_with(
source: &Source,
list: &Path,
dest_dir: &Path,
chunk: u64,
tries: u32,
) -> Result<()> {
let text = fs::read_to_string(list).with_context(|| format!("reading {}", list.display()))?;
fs::create_dir_all(dest_dir).with_context(|| format!("creating {}", dest_dir.display()))?;
let mut failed: Vec<String> = Vec::new();
let mut out = Vec::new();
for line in text.lines() {
let line = line.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
let Some(entry) = list_line(line) else {
eprintln!("bad list line: {line}");
failed.push(line.to_owned());
continue;
};
let dest = dest_dir.join(&entry.name);
match download_one(source, &entry, &dest, chunk, tries, &mut out) {
Ok(()) => {}
Err(error) => {
eprintln!("{error:#}");
failed.push(entry.key.clone());
}
}
}
for line in &out {
println!("{line}");
}
if failed.is_empty() {
return Ok(());
}
for key in failed {
println!("FAILED {key}");
}
Err(Exit(1).into())
}
#[must_use]
pub fn gdal_available() -> bool {
Command::new("gdal_translate")
.arg("--version")
.output()
.is_ok_and(|output| output.status.success())
}
fn gdal_version(gdal: &Path) -> Option<String> {
let output = Command::new(gdal).arg("--version").output().ok()?;
if !output.status.success() {
return None;
}
let mut text = String::from_utf8_lossy(&output.stdout).into_owned();
text.push_str(&String::from_utf8_lossy(&output.stderr));
let first = text.trim().split(',').next()?.trim().to_owned();
(!first.is_empty()).then_some(first)
}
fn clip_env(command: &mut Command, source: &Source) {
for name in [
"AWS_SESSION_TOKEN",
"AWS_PROFILE",
"AWS_DEFAULT_REGION",
"AWS_CONFIG_FILE",
"AWS_SHARED_CREDENTIALS_FILE",
] {
command.env_remove(name);
}
let https = if source.endpoint.starts_with("http://") {
"NO"
} else {
"YES"
};
command
.env("AWS_REGION", REGION)
.env("AWS_ACCESS_KEY_ID", &source.credentials.key_id)
.env("AWS_SECRET_ACCESS_KEY", &source.credentials.secret)
.env("AWS_S3_ENDPOINT", &source.host)
.env("AWS_HTTPS", https)
.env("AWS_VIRTUAL_HOSTING", "FALSE")
.env("GDAL_HTTP_MULTIRANGE", "YES")
.env("GDAL_DISABLE_READDIR_ON_OPEN", "EMPTY_DIR")
.env("GDAL_HTTP_MAX_RETRY", LIST_ATTEMPTS.to_string())
.env("GDAL_HTTP_RETRY_DELAY", RETRY_DELAY.to_string());
}
fn src_of(dest: &Path) -> PathBuf {
PathBuf::from(format!("{}.src", dest.display()))
}
fn clip_record(key: &str, window: (i64, i64, u32, u32)) -> String {
let (x0, y0, w, h) = window;
format!("{key} {x0} {y0} {w} {h}")
}
pub(crate) fn write_atomic(path: &Path, text: &str) -> Result<()> {
let partial = PathBuf::from(format!("{}.partial", path.display()));
fs::write(&partial, text).with_context(|| format!("writing {}", partial.display()))?;
fs::rename(&partial, path).with_context(|| format!("renaming to {}", path.display()))
}
fn clip_one(
source: &Source,
gdal: &Path,
key: &str,
dest: &Path,
window: (i64, i64, u32, u32),
out: &mut Vec<String>,
) -> Result<bool> {
let name = dest
.file_name()
.map(|name| name.to_string_lossy().into_owned())
.unwrap_or_default();
let record = clip_record(key, window);
let src = src_of(dest);
if dest.is_file() && src.is_file() {
let have = fs::read_to_string(&src).unwrap_or_default();
if have.trim_end() == record {
out.push(format!("SKIP {name}"));
return Ok(true);
}
}
if dest.is_file() {
out.push(format!("RECLIP {name} (now {record})"));
}
let partial = PathBuf::from(format!("{}.partial", dest.display()));
let _ = fs::remove_file(&partial);
let (x0, y0, w, h) = window;
let mut command = Command::new(gdal);
clip_env(&mut command, source);
command
.arg("-q")
.args(["-srcwin", &x0.to_string(), &y0.to_string()])
.args([&w.to_string(), &h.to_string()])
.arg("-of")
.arg("COG")
.args(["-co", "COMPRESS=DEFLATE", "-co", "PREDICTOR=2"])
.args(["-co", &format!("BLOCKSIZE={BLOCKSIZE}")])
.arg(format!("/vsis3/eodata/{key}"))
.arg(&partial);
let status = command.status();
if status.is_ok_and(|status| status.success()) {
let _ = fs::remove_file(&src);
fs::rename(&partial, dest).with_context(|| format!("renaming {}", partial.display()))?;
write_atomic(&src, &format!("{record}\n"))?;
out.push(format!("OK {name}"));
return Ok(true);
}
let _ = fs::remove_file(&partial);
let _ = fs::remove_file(format!("{}.aux.xml", partial.display()));
Ok(false)
}
pub fn download_clip(list: &Path, dest_dir: &Path, window: (i64, i64, u32, u32)) -> Result<()> {
if !gdal_available() {
eprintln!("gdal_translate not found; the NDVI clip needs GDAL (brew install gdal)");
bail!(Exit(3));
}
let source = Source::new(&endpoint(), credentials()?)?;
download_clip_with(&source, Path::new("gdal_translate"), list, dest_dir, window)
}
fn download_clip_with(
source: &Source,
gdal: &Path,
list: &Path,
dest_dir: &Path,
window: (i64, i64, u32, u32),
) -> Result<()> {
let text = fs::read_to_string(list).with_context(|| format!("reading {}", list.display()))?;
fs::create_dir_all(dest_dir).with_context(|| format!("creating {}", dest_dir.display()))?;
let mut failed: Vec<String> = Vec::new();
let mut out = Vec::new();
for line in text.lines() {
let line = line.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
let Some(entry) = list_line(line) else {
eprintln!("bad list line: {line}");
failed.push(line.to_owned());
continue;
};
let dest = dest_dir.join(&entry.name);
match clip_one(source, gdal, &entry.key, &dest, window, &mut out) {
Ok(true) => {}
Ok(false) => {
eprintln!("{}: the clip failed", entry.name);
failed.push(entry.key.clone());
}
Err(error) => {
eprintln!("{error:#}");
failed.push(entry.key.clone());
}
}
}
for line in &out {
println!("{line}");
}
if failed.is_empty() {
return Ok(());
}
for key in failed {
println!("FAILED {key}");
}
Err(Exit(1).into())
}
pub struct Client {
source: Source,
}
impl Client {
pub fn open() -> Result<Self> {
Ok(Self {
source: Source::new(&endpoint(), credentials()?)?,
})
}
pub fn download_entry(&self, entry: &ListLine, dest_dir: &Path) -> Result<()> {
fs::create_dir_all(dest_dir).with_context(|| format!("creating {}", dest_dir.display()))?;
let dest = dest_dir.join(&entry.name);
let mut out = Vec::new();
download_one(
&self.source,
entry,
&dest,
CHUNK_BYTES,
CHUNK_ATTEMPTS,
&mut out,
)?;
for line in out {
println!("{line}");
}
Ok(())
}
pub fn clip_entry(
&self,
entry: &ListLine,
dest_dir: &Path,
window: (i64, i64, u32, u32),
) -> Result<()> {
fs::create_dir_all(dest_dir).with_context(|| format!("creating {}", dest_dir.display()))?;
let dest = dest_dir.join(&entry.name);
let mut out = Vec::new();
if clip_one(
&self.source,
Path::new("gdal_translate"),
&entry.key,
&dest,
window,
&mut out,
)? {
for line in out {
println!("{line}");
}
return Ok(());
}
eprintln!("{}: the clip failed", entry.name);
Err(Exit(1).into())
}
pub fn probe_entry(&self, entry: &ListLine, window: (i64, i64, u32, u32)) -> Result<()> {
probe_entry_with(&self.source, Path::new("gdal_translate"), entry, window)
}
}
pub fn probe(list: &Path, window: (i64, i64, u32, u32)) -> Result<()> {
probe_with(Path::new("gdal_translate"), list, window)
}
fn probe_with(gdal: &Path, list: &Path, window: (i64, i64, u32, u32)) -> Result<()> {
let text = fs::read_to_string(list).with_context(|| format!("reading {}", list.display()))?;
let Some(entry) = text
.lines()
.map(str::trim)
.find(|line| !line.is_empty() && !line.starts_with('#'))
.and_then(list_line)
else {
bail!("{} lists no file to probe", list.display());
};
let source = Source::new(&endpoint(), credentials()?)?;
probe_entry_with(&source, gdal, &entry, window)
}
fn probe_entry_with(
source: &Source,
gdal: &Path,
entry: &ListLine,
window: (i64, i64, u32, u32),
) -> Result<()> {
let Some(version) = gdal_version(gdal) else {
eprintln!(
"GDAL is broken: `gdal_translate --version` failed; fix GDAL (brew install gdal) and rerun"
);
bail!(Exit(3));
};
let dir = std::env::temp_dir().join(format!("geolith-probe-{}", unix_seconds()));
fs::create_dir_all(&dir).with_context(|| format!("creating {}", dir.display()))?;
let target = dir.join("probe.tif");
let (x0, y0, _, _) = window;
let mut command = Command::new(gdal);
clip_env(&mut command, source);
let status = command
.arg("-q")
.args(["-srcwin", &x0.to_string(), &y0.to_string(), "1", "1"])
.arg("-of")
.arg("GTiff")
.arg(format!("/vsis3/eodata/{}", entry.key))
.arg(&target)
.status();
let _ = fs::remove_dir_all(&dir);
if !status.is_ok_and(|status| status.success()) {
eprintln!(
"GDAL cannot read /vsis3/eodata/{} (one pixel); check GDAL and the CDSE keys, then rerun",
entry.key
);
bail!(Exit(3));
}
println!("PROBE OK {version}");
Ok(())
}
pub fn source_lists(s: &Settings, quiet: bool) -> Result<PathBuf> {
let lists = s
.data_root
.join("datasets")
.join(&s.dataset)
.join(&s.cc)
.join("lists");
fs::create_dir_all(&lists).with_context(|| format!("creating {}", lists.display()))?;
let current = settings::current();
let today = current
.run
.cdse_today
.clone()
.filter(|value| is_date(value))
.unwrap_or_else(today_utc);
let (from, to) = series_range(&today);
let stac = current.sources.cdse_stac.as_deref().unwrap_or(DEFAULT_STAC);
let text = list(&from, &to, stac)?.join("\n");
let path = lists.join("series.txt");
write_atomic(&path, &text)?;
let prefixes = missing(&text, &from, &to, &today);
if prefixes.is_empty() {
return Ok(lists);
}
let source = Source::new(&endpoint(), credentials()?)?;
let keys = s3_keys(&source, &prefixes)?;
if keys.is_empty() {
return Ok(lists);
}
let s3_text = keys
.iter()
.map(|(key, bytes)| format!("{key} {bytes}"))
.collect::<Vec<_>>()
.join("\n");
let merged = merge(&text, &s3_text);
write_atomic(&path, &merged)?;
if !quiet {
for line in merged.lines() {
if line.starts_with("# ") && line.contains("from the S3 listing") {
println!("{line}");
}
}
}
Ok(lists)
}
pub fn run(args: &CdseArgs) -> Result<()> {
match &args.action {
CdseAction::List(a) => list_verb(a),
CdseAction::Missing(a) => missing_verb(a),
CdseAction::Merge(a) => merge_verb(a),
CdseAction::Ls(a) => ls_verb(a),
CdseAction::SeriesRange(a) => series_range_verb(a),
CdseAction::Window(a) => window_verb(a),
}
}
fn list_verb(args: &CdseListArgs) -> Result<()> {
if !is_date(&args.from) || !is_date(&args.to) {
eprintln!("list needs --from and --to as YYYY-MM-DD");
bail!(Exit(2));
}
let text = list(
&args.from,
&args.to,
args.stac.as_deref().unwrap_or(DEFAULT_STAC),
)?
.join("\n");
if !text.is_empty() {
println!("{text}");
}
Ok(())
}
fn missing_verb(args: &CdseMissingArgs) -> Result<()> {
let today = args.today.clone().unwrap_or_else(today_utc);
if !is_date(&args.from) || !is_date(&args.to) || !is_date(&today) {
eprintln!("missing needs --from and --to (YYYY-MM-DD) [--today]");
bail!(Exit(2));
}
let text = fs::read_to_string(&args.list)
.with_context(|| format!("reading {}", args.list.display()))?;
let found = missing(&text, &args.from, &args.to, &today);
if !found.is_empty() {
println!("{}", found.join("\n"));
}
Ok(())
}
fn merge_verb(args: &CdseMergeArgs) -> Result<()> {
let list_text = fs::read_to_string(&args.list)
.with_context(|| format!("reading {}", args.list.display()))?;
let s3_text =
fs::read_to_string(&args.s3).with_context(|| format!("reading {}", args.s3.display()))?;
let text = merge(&list_text, &s3_text);
if !text.is_empty() {
println!("{text}");
}
Ok(())
}
fn ls_verb(args: &CdseLsArgs) -> Result<()> {
let text = fs::read_to_string(&args.prefixes)
.with_context(|| format!("reading {}", args.prefixes.display()))?;
let prefixes: Vec<String> = text
.lines()
.map(str::trim)
.filter(|line| !line.is_empty() && !line.starts_with('#'))
.map(str::to_owned)
.collect();
if prefixes.is_empty() {
return Ok(());
}
let source = Source::new(&endpoint(), credentials()?)?;
for (key, bytes) in s3_keys(&source, &prefixes)? {
println!("{key} {bytes}");
}
Ok(())
}
fn series_range_verb(args: &CdseSeriesRangeArgs) -> Result<()> {
let today = args.today.clone().unwrap_or_else(today_utc);
if !is_date(&today) {
eprintln!("--today must be YYYY-MM-DD");
bail!(Exit(2));
}
let (from, to) = series_range(&today);
println!("{from} {to}");
Ok(())
}
fn window_verb(args: &CdseWindowArgs) -> Result<()> {
let grid = match &args.grid {
Some(text) => {
let values: Vec<f64> = text
.split(',')
.filter_map(|value| value.trim().parse::<f64>().ok())
.collect();
if values.len() != 6 {
eprintln!("--grid must be <x0>,<y0>,<px>,<py>,<width>,<height>");
bail!(Exit(2));
}
[
values[0], values[1], values[2], values[3], values[4], values[5],
]
}
None => NDVI_GRID,
};
let (x0, y0, w, h) = window(
&args.areas,
args.outline.as_deref(),
&args.country,
grid,
args.block,
)?;
println!("{x0} {y0} {w} {h}");
Ok(())
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
use crate::settings::read_env_file;
use std::io::{BufRead as _, BufReader};
use std::net::{TcpListener, TcpStream};
use std::os::unix::fs::PermissionsExt as _;
use std::sync::{Arc, Mutex};
fn item(day: &str, version: &str, size: u64) -> Value {
let compact = day.replace('-', "");
let (year, month, date) = (
day.get(0..4).expect("year"),
day.get(5..7).expect("month"),
day.get(8..10).expect("day"),
);
let name = format!("c_gls_NDVI300_{compact}0000_GLOBE_OLCI_{version}");
serde_json::json!({
"id": format!("{name}_cog"),
"properties": {
"start_datetime": format!("{day}T00:00:00Z"),
"processing:version": version,
},
"assets": {
"ndvi": {
"href": format!("s3://eodata/{S3_ROOT}/{year}/{month}/{date}/{name}_cog/c_gls_NDVI300-NDVI_{compact}0000_GLOBE_OLCI_{version}.tiff"),
"file:size": size,
},
},
})
}
fn key_of(item: &Value) -> String {
item["assets"]["ndvi"]["href"]
.as_str()
.expect("href")
.trim_start_matches("s3://eodata/")
.to_owned()
}
fn stac_server(pages: Vec<Vec<Value>>) -> (String, Arc<Mutex<Vec<String>>>) {
let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
let address = listener.local_addr().expect("address").to_string();
let origin = address.clone();
let seen: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));
let shared = Arc::clone(&seen);
std::thread::spawn(move || {
for stream in listener.incoming() {
let Ok(stream) = stream else { continue };
let pages = pages.clone();
let address = address.clone();
let shared = Arc::clone(&shared);
std::thread::spawn(move || {
let _ = serve_stac(stream, &pages, &address, &shared);
});
}
});
(format!("http://{origin}/v1"), seen)
}
fn serve_stac(
mut stream: TcpStream,
pages: &[Vec<Value>],
address: &str,
seen: &Arc<Mutex<Vec<String>>>,
) -> std::io::Result<()> {
let mut reader = BufReader::new(stream.try_clone()?);
let mut line = String::new();
reader.read_line(&mut line)?;
let target = line
.split_whitespace()
.nth(1)
.unwrap_or_default()
.to_owned();
loop {
let mut header = String::new();
reader.read_line(&mut header)?;
if header.trim().is_empty() {
break;
}
}
seen.lock().expect("seen").push(target.clone());
let page: usize = target
.split("page=")
.nth(1)
.and_then(|rest| rest.split('&').next())
.and_then(|value| value.parse().ok())
.unwrap_or(0);
let features = pages.get(page).cloned().unwrap_or_default();
let links = if page + 1 < pages.len() {
format!(
r#"[{{"rel":"next","href":"http://{address}/v1/collections/{COLLECTION}/items?page={}"}}]"#,
page + 1
)
} else {
"[]".to_owned()
};
let body = format!(
r#"{{"type":"FeatureCollection","features":{},"links":{links}}}"#,
serde_json::to_string(&features).expect("features")
);
let head = format!(
"HTTP/1.1 200 OK\r\nContent-Type: application/geo+json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
body.len()
);
stream.write_all(head.as_bytes())?;
stream.write_all(body.as_bytes())?;
stream.flush()
}
#[derive(Debug, Clone)]
pub(crate) struct Record {
pub(crate) target: String,
pub(crate) range: Option<String>,
authorization: String,
}
pub(crate) struct Store {
source: Source,
pub(crate) log: Arc<Mutex<Vec<Record>>>,
}
impl Store {
pub(crate) fn client(&self) -> Client {
Client {
source: Source::new(&self.source.endpoint, self.source.credentials.clone())
.expect("a fake store is a URL"),
}
}
}
pub(crate) fn store(objects: Vec<(String, Vec<u8>)>, listings: Vec<(String, String)>) -> Store {
let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
let address = listener.local_addr().expect("address").to_string();
let log: Arc<Mutex<Vec<Record>>> = Arc::new(Mutex::new(Vec::new()));
let objects: Arc<BTreeMap<String, Vec<u8>>> = Arc::new(objects.into_iter().collect());
let listings: Arc<BTreeMap<String, String>> = Arc::new(listings.into_iter().collect());
let shared = Arc::clone(&log);
std::thread::spawn(move || {
for stream in listener.incoming() {
let Ok(stream) = stream else { continue };
let objects = Arc::clone(&objects);
let listings = Arc::clone(&listings);
let shared = Arc::clone(&shared);
std::thread::spawn(move || {
let _ = serve_store(stream, &objects, &listings, &shared);
});
}
});
let source = Source::new(
&format!("http://{address}"),
Credentials {
key_id: "AKIACDSETESTKEY".to_owned(),
secret: "SEKRET-cdse-never-printed".to_owned(),
},
)
.expect("a fake store is a URL");
Store { source, log }
}
fn serve_store(
mut stream: TcpStream,
objects: &BTreeMap<String, Vec<u8>>,
listings: &BTreeMap<String, String>,
log: &Arc<Mutex<Vec<Record>>>,
) -> std::io::Result<()> {
let mut reader = BufReader::new(stream.try_clone()?);
let mut line = String::new();
reader.read_line(&mut line)?;
let target = line
.split_whitespace()
.nth(1)
.unwrap_or_default()
.to_owned();
let (mut range, mut authorization) = (None, String::new());
loop {
let mut header = String::new();
reader.read_line(&mut header)?;
if header.trim().is_empty() {
break;
}
let lower = header.to_ascii_lowercase();
if let Some(value) = lower.strip_prefix("range:") {
range = Some(value.trim().to_owned());
}
if lower.starts_with("authorization:") {
authorization = header
.split_once(':')
.map(|(_, value)| value.trim().to_owned())
.unwrap_or_default();
}
}
log.lock().expect("log").push(Record {
target: target.clone(),
range: range.clone(),
authorization,
});
let (status, body): (&str, Vec<u8>) = if target.starts_with("/eodata?") {
let prefix = target
.split("prefix=")
.nth(1)
.and_then(|rest| rest.split('&').next())
.map(|value| value.replace("%2F", "/").replace("%2f", "/"))
.unwrap_or_default();
let body = listings.get(&prefix).cloned().unwrap_or_default();
("200 OK", body.into_bytes())
} else if let Some(key) = target.strip_prefix("/eodata/") {
let bytes = objects.get(key).cloned().unwrap_or_default();
match range.as_deref().map(parse_range) {
Some(Some((start, end))) => {
let start = start.min(bytes.len());
let end = (end + 1).min(bytes.len());
("206 Partial Content", bytes[start..end].to_vec())
}
_ => ("200 OK", bytes),
}
} else {
("404 Not Found", Vec::new())
};
let head = format!(
"HTTP/1.1 {status}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
body.len()
);
stream.write_all(head.as_bytes())?;
stream.write_all(&body)?;
stream.flush()
}
fn parse_range(text: &str) -> Option<(usize, usize)> {
let rest = text.trim().strip_prefix("bytes=")?;
let (start, end) = rest.split_once('-')?;
Some((start.parse().ok()?, end.parse().ok()?))
}
#[test]
fn a_stac_page_names_the_dekads_in_name_order() {
let (a, b, c) = (
item("2026-09-01", "V3.0.1", 1_250_000_001),
item("2026-09-11", "V3.0.1", 1_250_000_002),
item("2026-09-21", "V3.0.1", 1_250_000_003),
);
let (origin, seen) = stac_server(vec![vec![c.clone(), a.clone()], vec![b.clone()]]);
let lines = list("2026-09-01", "2026-09-30", &origin).expect("list");
assert_eq!(
lines,
[
format!("final {} ndvi300-v3.2026.09.1.tif 1250000001", key_of(&a)),
format!("final {} ndvi300-v3.2026.09.2.tif 1250000002", key_of(&b)),
format!("final {} ndvi300-v3.2026.09.3.tif 1250000003", key_of(&c)),
]
);
let seen = seen.lock().expect("seen");
assert!(
seen[0].starts_with(&format!(
"/v1/collections/{COLLECTION}/items?datetime=2026-09-01T00%3A00%3A00Z%2F2026-09-30T23%3A59%3A59Z&limit=100"
)),
"{}",
seen[0]
);
assert!(seen.iter().any(|target| target.contains("page=1")));
}
#[test]
fn a_reprocessed_dekad_keeps_the_larger_version() {
let old = item("2025-12-21", "V3.0.1", 100);
let newer = item("2025-12-21", "V3.0.10", 200);
let (origin, _) = stac_server(vec![vec![newer.clone(), old.clone()]]);
let lines = list("2025-12-21", "2025-12-31", &origin).expect("list");
assert_eq!(
lines,
[
format!(
"# ndvi300-v3.2025.12.3.tif: {} (V3.0.1) replaced by V3.0.10",
key_of(&old)
),
format!("final {} ndvi300-v3.2025.12.3.tif 200", key_of(&newer)),
]
);
}
#[test]
fn an_item_that_is_not_a_dekad_start_is_named() {
let mut bad = item("2026-09-05", "V3.0.1", 7);
bad["id"] = Value::String("c_gls_NDVI300_20260905".to_owned());
let (origin, _) = stac_server(vec![vec![bad]]);
let error = list("2026-09-01", "2026-09-30", &origin).expect_err("a failure");
assert!(
error.to_string().contains("c_gls_NDVI300_20260905"),
"{error}"
);
}
#[test]
fn missing_lists_only_the_dekads_the_catalogue_lacks() {
let list_text = [
ListLine {
key: "a".to_owned(),
name: "ndvi300-v3.2026.10.1.tif".to_owned(),
bytes: 9,
}
.final_line(),
ListLine {
key: "b".to_owned(),
name: "ndvi300-v3.2026.10.2.tif".to_owned(),
bytes: 9,
}
.final_line(),
]
.join("\n");
assert_eq!(
missing(&list_text, "2026-10-01", "2026-11-20", "2026-11-18"),
[
format!("{S3_ROOT}/2026/10/21/"),
format!("{S3_ROOT}/2026/11/01/"),
format!("{S3_ROOT}/2026/11/11/"),
]
);
assert!(missing(&list_text, "2026-10-01", "2026-10-20", "2026-11-18").is_empty());
assert!(missing(&list_text, "2026-10-01", "2026-11-20", "2026-10-11").is_empty());
}
#[test]
fn merge_fills_only_the_missing_dekads_and_keeps_the_newest_version() {
let listed = ListLine {
key: format!(
"{S3_ROOT}/2026/10/11/x_cog/c_gls_NDVI300-NDVI_202610110000_GLOBE_OLCI_V3.0.1.tiff"
),
name: "ndvi300-v3.2026.10.2.tif".to_owned(),
bytes: 9,
};
let dir = |day: &str, version: &str| {
let compact = day.replace('-', "");
let year = &day[0..4];
let month = &day[5..7];
let date = &day[8..10];
format!(
"{S3_ROOT}/{year}/{month}/{date}/c_gls_NDVI300_{compact}0000_GLOBE_OLCI_{version}"
)
};
let s3 = [
format!(
"{}_cog/c_gls_NDVI300-NDVI_202610210000_GLOBE_OLCI_V3.0.1.tiff 1151405426",
dir("2026-10-21", "V3.0.1")
),
format!(
"{}_cog/c_gls_NDVI300-NOBS_202610210000_GLOBE_OLCI_V3.0.1.tiff 250690453",
dir("2026-10-21", "V3.0.1")
),
format!(
"{}_nc/c_gls_NDVI300_202610210000_GLOBE_OLCI_V3.0.1.nc 2583893193",
dir("2026-10-21", "V3.0.1")
),
format!(
"{}_cog/c_gls_NDVI300-NDVI_202611010000_GLOBE_OLCI_V3.0.1.tiff 1078825184",
dir("2026-11-01", "V3.0.1")
),
format!(
"{}_cog/c_gls_NDVI300-NDVI_202611010000_GLOBE_OLCI_V3.0.2.tiff 1078825185",
dir("2026-11-01", "V3.0.2")
),
format!(
"{}_cog/c_gls_NDVI300-NDVI_202610110000_GLOBE_OLCI_V3.0.9.tiff 5",
dir("2026-10-11", "V3.0.9")
),
]
.join("\n");
let merged = merge(&listed.final_line(), &s3);
let finals: Vec<&str> = merged
.lines()
.filter(|line| line.starts_with("final "))
.collect();
assert_eq!(
finals,
[
listed.final_line(),
format!(
"final {}_cog/c_gls_NDVI300-NDVI_202610210000_GLOBE_OLCI_V3.0.1.tiff ndvi300-v3.2026.10.3.tif 1151405426",
dir("2026-10-21", "V3.0.1")
),
format!(
"final {}_cog/c_gls_NDVI300-NDVI_202611010000_GLOBE_OLCI_V3.0.2.tiff ndvi300-v3.2026.11.1.tif 1078825185",
dir("2026-11-01", "V3.0.2")
),
]
);
assert!(
merged
.contains("# ndvi300-v3.2026.10.3.tif: from the S3 listing (not in the STAC yet)"),
"{merged}"
);
assert_eq!(merge(&listed.final_line(), ""), listed.final_line());
}
#[test]
fn the_series_is_the_current_dekad_and_the_twelve_before_it() {
assert_eq!(
series_range("2026-11-18"),
("2026-07-11".to_owned(), "2026-11-20".to_owned())
);
assert_eq!(
series_range("2026-01-31"),
("2025-09-21".to_owned(), "2026-01-31".to_owned())
);
assert_eq!(
series_range("2026-11-22"),
("2026-07-21".to_owned(), "2026-11-30".to_owned())
);
}
fn square(x0: f64, y0: f64, x1: f64, y1: f64) -> Value {
serde_json::json!({
"type": "Polygon",
"coordinates": [[[x0, y0], [x1, y0], [x1, y1], [x0, y1], [x0, y0]]],
})
}
fn window_files(dir: &Path, areas: Value, outline: Value) -> (PathBuf, PathBuf) {
let areas_path = dir.join("areas.geojson");
let outline_path = dir.join("outline.geojson");
fs::write(
&areas_path,
serde_json::json!({"type": "FeatureCollection", "features": areas}).to_string(),
)
.expect("areas");
fs::write(
&outline_path,
serde_json::json!({"type": "FeatureCollection", "features": [{"type": "Feature", "properties": {}, "geometry": outline}]})
.to_string(),
)
.expect("outline");
(areas_path, outline_path)
}
#[test]
fn the_window_is_the_country_bbox_snapped_out_to_the_block_grid() {
let dir = tempfile::tempdir().expect("a temp dir");
let areas = serde_json::json!([
{"type": "Feature", "properties": {"country": "IN"}, "geometry": square(74.1, 28.1, 76.0, 29.9)},
{"type": "Feature", "properties": {"country": "IN"}, "geometry": {
"type": "MultiPolygon",
"coordinates": [square(75.0, 29.0, 77.9, 29.5)["coordinates"].clone()],
}},
{"type": "Feature", "properties": {"country": "NP"}, "geometry": square(80.0, 21.0, 85.0, 35.0)},
]);
let (areas_path, outline_path) =
window_files(dir.path(), areas, square(75.0, 29.0, 76.0, 29.5));
let grid = [70.0, 36.0, 0.25, -0.25, 64.0, 64.0];
assert_eq!(
window(&areas_path, Some(&outline_path), "IN", grid, 16).expect("window"),
(0, 16, 48, 32)
);
let (areas_path, outline_path) = window_files(
dir.path(),
serde_json::json!([
{"type": "Feature", "properties": {"country": "IN"}, "geometry": square(74.1, 28.1, 76.0, 29.9)},
]),
square(75.0, 29.0, 79.0, 34.5),
);
assert_eq!(
window(&areas_path, Some(&outline_path), "IN", grid, 16).expect("window"),
(0, 0, 48, 48)
);
}
#[test]
fn an_india_window_needs_the_survey_of_india_outline() {
let dir = tempfile::tempdir().expect("a temp dir");
let (areas_path, _) = window_files(
dir.path(),
serde_json::json!([
{"type": "Feature", "properties": {"country": "IN"}, "geometry": square(74.1, 28.1, 76.0, 29.9)},
]),
square(75.0, 29.0, 76.0, 29.5),
);
let error = window(&areas_path, None, "IN", NDVI_GRID, 512).expect_err("a refusal");
assert!(
error
.to_string()
.contains("window for IN needs --outline <Survey of India GeoJSON>"),
"{error}"
);
}
fn one_line(dir: &Path, key: &str, name: &str, bytes: u64) -> PathBuf {
let path = dir.join("series.txt");
fs::write(
&path,
ListLine {
key: key.to_owned(),
name: name.to_owned(),
bytes,
}
.final_line(),
)
.expect("write");
path
}
pub(crate) fn object(size: usize) -> Vec<u8> {
(0..size)
.map(|index| u8::try_from(index % 251).unwrap_or_default())
.collect()
}
#[test]
fn a_whole_file_is_fetched_in_closed_windows() {
let bytes = object(300);
let store = store(vec![("k/ndvi.tiff".to_owned(), bytes.clone())], Vec::new());
let dir = tempfile::tempdir().expect("a temp dir");
let list = one_line(dir.path(), "k/ndvi.tiff", "ndvi300-v3.2026.10.1.tif", 300);
let dest = dir.path().join("final");
download_full_with(&store.source, &list, &dest, 128, 2).expect("download");
assert_eq!(
fs::read(dest.join("ndvi300-v3.2026.10.1.tif")).expect("read"),
bytes
);
let log = store.log.lock().expect("log");
let ranges: Vec<Option<String>> = log.iter().map(|record| record.range.clone()).collect();
assert_eq!(
ranges,
[
Some("bytes=0-127".to_owned()),
Some("bytes=128-255".to_owned()),
Some("bytes=256-299".to_owned()),
]
);
}
#[test]
fn a_resumed_part_asks_for_the_rest_only() {
let bytes = object(200);
let store = store(vec![("k/ndvi.tiff".to_owned(), bytes.clone())], Vec::new());
let dir = tempfile::tempdir().expect("a temp dir");
let list = one_line(dir.path(), "k/ndvi.tiff", "ndvi300-v3.2026.10.1.tif", 200);
let dest = dir.path().join("final/ndvi300-v3.2026.10.1.tif");
fs::create_dir_all(dest.parent().expect("parent")).expect("mkdir");
fs::write(part_of(&dest), &bytes[..100]).expect("write");
download_full_with(&store.source, &list, dest.parent().expect("parent"), 128, 2)
.expect("download");
assert_eq!(fs::read(&dest).expect("read"), bytes);
let log = store.log.lock().expect("log");
assert_eq!(log[0].range.as_deref(), Some("bytes=100-199"));
}
#[test]
fn a_part_longer_than_the_listing_is_discarded() {
let bytes = object(120);
let store = store(vec![("k/ndvi.tiff".to_owned(), bytes.clone())], Vec::new());
let dir = tempfile::tempdir().expect("a temp dir");
let list = one_line(dir.path(), "k/ndvi.tiff", "ndvi300-v3.2026.10.1.tif", 120);
let dest = dir.path().join("final/ndvi300-v3.2026.10.1.tif");
fs::create_dir_all(dest.parent().expect("parent")).expect("mkdir");
fs::write(part_of(&dest), vec![9_u8; 400]).expect("write");
download_full_with(&store.source, &list, dest.parent().expect("parent"), 128, 2)
.expect("download");
assert_eq!(fs::read(&dest).expect("read"), bytes);
let log = store.log.lock().expect("log");
assert_eq!(log[0].range.as_deref(), Some("bytes=0-119"));
}
#[test]
fn the_secret_never_reaches_a_line_or_a_header_value() {
let bytes = object(64);
let store = store(vec![("k/ndvi.tiff".to_owned(), bytes)], Vec::new());
let dir = tempfile::tempdir().expect("a temp dir");
let list = one_line(dir.path(), "k/ndvi.tiff", "ndvi300-v3.2026.10.1.tif", 64);
download_full_with(&store.source, &list, &dir.path().join("final"), 128, 1)
.expect("download");
let entries = fs::read_dir(dir.path().join("final")).expect("the dir");
for entry in entries {
let entry = entry.expect("an entry");
let text = String::from_utf8_lossy(&fs::read(entry.path()).expect("read")).into_owned();
assert!(!text.contains("SEKRET-cdse-never-printed"));
}
let log = store.log.lock().expect("log");
for record in log.iter() {
assert!(
!record.authorization.contains("SEKRET-cdse-never-printed"),
"{}",
record.target
);
assert!(record.authorization.contains("AKIACDSETESTKEY"));
}
let credentials = Credentials {
key_id: "id".to_owned(),
secret: "SEKRET-cdse-never-printed".to_owned(),
};
assert!(!format!("{credentials:?}").contains("SEKRET-cdse-never-printed"));
}
#[test]
fn a_credentials_file_wider_than_six_hundred_is_refused() {
let dir = tempfile::tempdir().expect("a temp dir");
let path = dir.path().join("cdse.env");
fs::write(
&path,
"export CDSE_S3_ACCESS_KEY = \"AKIAEXAMPLE\"\nCDSE_S3_SECRET_KEY='s3cret'\n",
)
.expect("write");
fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).expect("chmod");
let values = read_env_file(&path).expect("a 600 file is read");
assert_eq!(
values.get("CDSE_S3_ACCESS_KEY").map(String::as_str),
Some("AKIAEXAMPLE")
);
assert_eq!(
values.get("CDSE_S3_SECRET_KEY").map(String::as_str),
Some("s3cret")
);
fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).expect("chmod");
let error = read_env_file(&path).expect_err("a 644 file is refused");
assert!(error.to_string().contains("chmod 600"), "{error}");
}
#[test]
fn merge_lists_the_prefix_when_the_store_holds_the_dekad() {
let store = store(
Vec::new(),
vec![(
format!("{S3_ROOT}/2026/10/21/"),
format!(
"<ListBucketResult><IsTruncated>false</IsTruncated><Contents><Key>{S3_ROOT}/2026/10/21/x_cog/c_gls_NDVI300-NDVI_202610210000_GLOBE_OLCI_V3.0.1.tiff</Key><Size>42</Size></Contents></ListBucketResult>"
),
)],
);
let keys = s3_keys(&store.source, &[format!("{S3_ROOT}/2026/10/21/")]).expect("listing");
assert_eq!(
keys,
[(
format!(
"{S3_ROOT}/2026/10/21/x_cog/c_gls_NDVI300-NDVI_202610210000_GLOBE_OLCI_V3.0.1.tiff"
),
42
)]
);
}
fn fake_gdal(dir: &Path) -> PathBuf {
let path = dir.join("gdal_translate");
fs::write(
&path,
"#!/bin/sh\n\
d=$(dirname \"$0\")\n\
printf '%s\\n' \"$@\" >\"$d/argv.txt\"\n\
printf '%s\\n' \"$AWS_SECRET_ACCESS_KEY\" \"$AWS_S3_ENDPOINT\" >\"$d/env.txt\"\n\
for a in \"$@\"; do last=$a; done\n\
printf 'COG' >\"$last\"\n\
exit 0\n",
)
.expect("script");
fs::set_permissions(&path, fs::Permissions::from_mode(0o755)).expect("chmod");
path
}
#[test]
fn a_clip_hands_the_window_on_argv_and_the_keys_in_the_environment() {
let dir = tempfile::tempdir().expect("a temp dir");
let gdal = fake_gdal(dir.path());
let source = Source::new(
"https://eodata.example",
Credentials {
key_id: "AKIACDSETESTKEY".to_owned(),
secret: "SEKRET-cdse-never-printed".to_owned(),
},
)
.expect("a URL");
let dest = dir.path().join("final/ndvi300-v3.2026.10.1.tif");
fs::create_dir_all(dest.parent().expect("parent")).expect("mkdir");
let mut out = Vec::new();
let ok = clip_one(
&source,
&gdal,
"k/ndvi.tiff",
&dest,
(10, 20, 512, 512),
&mut out,
)
.expect("clip");
assert!(ok);
assert_eq!(out, ["OK ndvi300-v3.2026.10.1.tif"]);
let argv = fs::read_to_string(dir.path().join("argv.txt")).expect("argv");
assert!(argv.contains("-srcwin\n10\n20\n512\n512\n"), "{argv}");
assert!(argv.contains("/vsis3/eodata/k/ndvi.tiff"), "{argv}");
assert!(!argv.contains("SEKRET-cdse-never-printed"), "{argv}");
let env = fs::read_to_string(dir.path().join("env.txt")).expect("env");
assert!(env.contains("SEKRET-cdse-never-printed"), "{env}");
assert!(env.contains("eodata.example"), "{env}");
let sidecar = fs::read_to_string(src_of(&dest)).expect("the record");
assert_eq!(sidecar.trim_end(), "k/ndvi.tiff 10 20 512 512");
assert!(!sidecar.contains("SEKRET"));
let mut again = Vec::new();
assert!(
clip_one(
&source,
&gdal,
"k/ndvi.tiff",
&dest,
(10, 20, 512, 512),
&mut again
)
.expect("clip")
);
assert_eq!(again, ["SKIP ndvi300-v3.2026.10.1.tif"]);
}
#[test]
fn an_absent_gdal_is_a_refusal_naming_the_tool() {
let dir = tempfile::tempdir().expect("a temp dir");
let list = one_line(dir.path(), "k/ndvi.tiff", "ndvi300-v3.2026.10.1.tif", 8);
let text = fs::read_to_string(&list).expect("read the list");
let entry = text
.lines()
.map(str::trim)
.find(|line| !line.is_empty() && !line.starts_with('#'))
.and_then(list_line)
.expect("a list line");
let source = Source::new(
"https://eodata.example",
Credentials {
key_id: "AKIACDSETESTKEY".to_owned(),
secret: "SEKRET-cdse-never-printed".to_owned(),
},
)
.expect("a URL");
let error = probe_entry_with(
&source,
Path::new("/nonexistent/gdal_translate"),
&entry,
(0, 0, 512, 512),
)
.expect_err("a refusal");
assert_eq!(error.downcast_ref::<Exit>().copied(), Some(Exit(3)));
assert!(error.to_string().contains("exit 3"), "{error}");
}
#[test]
fn a_bad_list_line_is_named_and_fails() {
let store = store(Vec::new(), Vec::new());
let dir = tempfile::tempdir().expect("a temp dir");
let list = dir.path().join("series.txt");
fs::write(&list, "midday k/ndvi.tiff x.tif 8\n").expect("write");
let error = download_full_with(&store.source, &list, &dir.path().join("final"), 128, 1)
.expect_err("a failure");
assert_eq!(error.downcast_ref::<Exit>().copied(), Some(Exit(1)));
assert!(store.log.lock().expect("log").is_empty());
}
}