1use crate::{Result, coded, safe_name, storage};
13use serde::{Deserialize, Serialize};
14use serde_json::{Map, Value, json};
15use std::{
16 collections::BTreeSet,
17 fs,
18 io::{self, BufRead, Read},
19 path::Path,
20};
21
22pub const DECLARATIONS: &str = "artifacts.jsonl";
24const LOCK: &str = "artifacts.lock";
25pub const RESULTS: &str = "results";
27pub const FORMATS: [&str; 2] = ["records", "json"];
35pub const RESERVED: [&str; 22] = [
38 "artifacts.jsonl",
39 "artifacts.lock",
40 "cancel.lock",
41 "cancel.request",
42 "child_finished",
43 "containment.unknown",
44 "events.jsonl",
45 "inputs",
46 "job.json",
47 "job.lock",
48 "provenance.json",
49 "request.json",
50 "resolved.json",
51 "results.jsonl",
52 "retries.jsonl",
53 "run.json",
54 "stderr.log",
55 "stdout.log",
56 "submitted.json",
57 "worker",
58 "worker-process.json",
59 "worker.lock",
60];
61pub const MAX_DECLARATIONS: usize = 4096;
63pub const MAX_DESCRIPTION: usize = 200;
65pub const INLINE_CAP: usize = 1 << 20;
68pub const MAX_PAGE: usize = 10_000;
70
71#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
73#[serde(deny_unknown_fields)]
74pub struct Declaration {
75 pub name: String,
77 pub file: String,
79 pub format: String,
81 #[serde(default, skip_serializing_if = "Option::is_none")]
83 pub task_id: Option<usize>,
84 #[serde(default, skip_serializing_if = "String::is_empty")]
86 pub description: String,
87}
88
89impl Declaration {
90 pub fn records(name: impl Into<String>, file: impl Into<String>) -> Self {
92 Self {
93 name: name.into(),
94 file: file.into(),
95 format: "records".into(),
96 task_id: None,
97 description: String::new(),
98 }
99 }
100 pub fn json(name: impl Into<String>, file: impl Into<String>) -> Self {
102 Self {
103 format: "json".into(),
104 ..Self::records(name, file)
105 }
106 }
107 pub fn task(mut self, task_id: usize) -> Self {
109 self.task_id = Some(task_id);
110 self
111 }
112 pub fn describe(mut self, description: impl Into<String>) -> Self {
114 self.description = description.into();
115 self
116 }
117 pub fn check(&self) -> std::result::Result<(), String> {
119 let file = self.file.as_str();
120 if !safe_name(&self.name) || self.name == RESULTS {
121 return Err(format!("invalid or reserved artifact name {:?}", self.name));
122 }
123 if !safe_name(file)
124 || RESERVED.contains(&file)
125 || file.starts_with('.')
126 || file.ends_with(".lock")
127 || file.ends_with(".tmp")
128 {
129 return Err(format!(
130 "artifact {}: invalid or reserved file name {file:?}",
131 self.name
132 ));
133 }
134 if !FORMATS.contains(&self.format.as_str()) {
135 return Err(format!(
136 "artifact {}: unknown format {:?}",
137 self.name, self.format
138 ));
139 }
140 if self.description.len() > MAX_DESCRIPTION || self.description.contains(char::is_control) {
141 return Err(format!(
142 "artifact {}: description over {MAX_DESCRIPTION} bytes or with control characters",
143 self.name
144 ));
145 }
146 Ok(())
147 }
148}
149
150pub fn declare(dir: &Path, declaration: &Declaration) -> Result<()> {
157 declaration.check()?;
158 let _lock = storage::lock(&dir.join(LOCK))?;
159 let existing = declarations(dir)?;
160 if let Some(old) = existing.iter().find(|d| d.name == declaration.name) {
161 if old == declaration {
162 return Ok(());
163 }
164 return Err(format!(
165 "artifact {} is already declared differently",
166 declaration.name
167 )
168 .into());
169 }
170 if existing.iter().any(|d| d.file == declaration.file) {
171 return Err(format!("file {} is already declared", declaration.file).into());
172 }
173 if existing.len() >= MAX_DECLARATIONS {
174 return Err(format!("more than {MAX_DECLARATIONS} artifacts declared").into());
175 }
176 storage::append_checked(&dir.join(DECLARATIONS), 1, declaration)?;
177 Ok(())
178}
179
180pub fn declarations(dir: &Path) -> Result<Vec<Declaration>> {
184 let path = dir.join(DECLARATIONS);
185 if !path.exists() {
186 return Ok(vec![]);
187 }
188 let list: Vec<Declaration> =
189 storage::read_checked(&path, 1).map_err(|e| format!("{DECLARATIONS}: {e}"))?;
190 let (mut names, mut files) = (BTreeSet::new(), BTreeSet::new());
191 for d in &list {
192 d.check().map_err(|e| format!("{DECLARATIONS}: {e}"))?;
193 if !names.insert(&d.name) || !files.insert(&d.file) {
194 return Err(format!("{DECLARATIONS}: {} or its file declared twice", d.name).into());
195 }
196 }
197 if list.len() > MAX_DECLARATIONS {
198 return Err(format!("{DECLARATIONS}: more than {MAX_DECLARATIONS} artifacts").into());
199 }
200 Ok(list)
201}
202
203pub fn all(dir: &Path) -> Result<Vec<Declaration>> {
206 let mut list = vec![results()];
207 list.extend(declarations(dir)?);
208 Ok(list)
209}
210
211fn results() -> Declaration {
212 Declaration::records(RESULTS, "results.jsonl")
213 .describe("The result journal: one checked record per completed task")
214}
215
216pub fn all_or_results(dir: &Path) -> (Vec<Declaration>, Vec<String>) {
219 match all(dir) {
220 Ok(list) => (list, vec![]),
221 Err(e) => (vec![results()], vec![e.to_string()]),
222 }
223}
224
225fn entry(d: &Declaration) -> Map<String, Value> {
226 let mut e = Map::new();
227 e.insert("file".into(), json!(d.file));
228 e.insert("format".into(), json!(d.format));
229 if let Some(task) = d.task_id {
230 e.insert("task_id".into(), json!(task));
231 }
232 if !d.description.is_empty() {
233 e.insert("description".into(), json!(d.description));
234 }
235 e
236}
237
238pub fn progress(dir: &Path) -> (Value, Vec<String>) {
242 let (list, errors) = all_or_results(dir);
243 let mut index = Map::new();
244 for d in list {
245 if let Ok(meta) = fs::symlink_metadata(dir.join(&d.file))
246 && meta.is_file()
247 {
248 let mut e = entry(&d);
249 e.insert("bytes".into(), json!(meta.len()));
250 index.insert(d.name.clone(), Value::Object(e));
251 }
252 }
253 (Value::Object(index), errors)
254}
255
256pub fn sealed(dir: &Path) -> (Value, Value, Vec<String>) {
262 let (list, mut errors) = all_or_results(dir);
263 let (mut files, mut index) = (Map::new(), Map::new());
264 for d in list {
265 let path = dir.join(&d.file);
266 match fs::symlink_metadata(&path) {
267 Ok(meta) if meta.is_file() => {}
268 Err(e) if e.kind() == io::ErrorKind::NotFound => continue,
269 Ok(_) => {
270 errors.push(format!(
271 "artifact {}: {} is not a regular file",
272 d.name, d.file
273 ));
274 continue;
275 }
276 Err(e) => {
277 errors.push(format!("artifact {}: {e}", d.name));
278 continue;
279 }
280 }
281 let (bytes, sha256) = match digest_file(&path) {
282 Ok(digest) => digest,
283 Err(e) => {
284 errors.push(format!("artifact {}: {e}", d.name));
285 continue;
286 }
287 };
288 let mut e = entry(&d);
289 e.insert("bytes".into(), json!(bytes));
290 e.insert("sha256".into(), json!(sha256));
291 files.insert(d.name.clone(), json!(d.file));
292 index.insert(d.name, Value::Object(e));
293 }
294 (Value::Object(files), Value::Object(index), errors)
295}
296
297pub fn digest_file(path: &Path) -> Result<(u64, String)> {
299 use sha2::{Digest, Sha256};
300 let mut file = fs::File::open(path)?;
301 let mut hasher = Sha256::new();
302 let mut buffer = vec![0u8; 1 << 16];
303 let mut bytes = 0u64;
304 loop {
305 let n = file.read(&mut buffer)?;
306 if n == 0 {
307 break;
308 }
309 bytes += n as u64;
310 hasher.update(&buffer[..n]);
311 }
312 Ok((bytes, format!("{:x}", hasher.finalize())))
313}
314
315pub fn content(path: &Path, format: &str) -> Result<Value> {
319 let size = fs::metadata(path)?.len();
320 if size > INLINE_CAP as u64 {
321 return Err(coded(
322 "artifact_too_large",
323 format!(
324 "the artifact has {size} bytes, over the {INLINE_CAP}-byte inline cap; {}",
325 if format == "records" {
326 "read it in pages with offset and limit"
327 } else {
328 "read the file in the job directory"
329 }
330 ),
331 ));
332 }
333 let mut data = fs::read(path)?;
334 if format == "records" {
335 data.truncate(data.iter().rposition(|b| *b == b'\n').map_or(0, |i| i + 1));
336 }
337 let sha256 = storage::digest(&data);
338 let bytes = data.len();
339 let text = String::from_utf8(data).map_err(|_| "artifact is not UTF-8 text")?;
340 Ok(json!({"format":format,"bytes":bytes,"sha256":sha256,"content":text}))
341}
342
343pub fn page(path: &Path, offset: usize, limit: usize) -> Result<Value> {
355 if !(1..=MAX_PAGE).contains(&limit) {
356 return Err(coded(
357 "invalid_command",
358 format!("limit must lie in 1..={MAX_PAGE}"),
359 ));
360 }
361 let mut reader = io::BufReader::with_capacity(1 << 16, fs::File::open(path)?);
362 let mut line = Vec::new();
363 let (mut index, mut size, mut full) = (0usize, 0usize, false);
364 let mut records = Vec::new();
365 loop {
366 line.clear();
367 if reader.read_until(b'\n', &mut line)? == 0 || line.last() != Some(&b'\n') {
368 break;
369 }
370 if line.iter().all(u8::is_ascii_whitespace) {
371 continue;
372 }
373 if index >= offset && records.len() < limit && !full {
374 let envelope: storage::Envelope = serde_json::from_slice(&line)
375 .map_err(|e| format!("record {index} of the artifact is no checked record: {e}"))?;
376 if envelope.checksum != storage::digest(envelope.payload_json.as_bytes()) {
377 return Err(format!("record {index} of the artifact fails its checksum").into());
378 }
379 if size + envelope.payload_json.len() > INLINE_CAP {
380 if records.is_empty() {
381 return Err(coded(
382 "artifact_too_large",
383 format!(
384 "record {index} alone exceeds the {INLINE_CAP}-byte inline cap; read the file in the job directory"
385 ),
386 ));
387 }
388 full = true;
389 } else {
390 size += envelope.payload_json.len();
391 records.push(serde_json::from_str::<Value>(&envelope.payload_json)?);
392 }
393 }
394 index += 1;
395 }
396 let next = offset.min(index) + records.len();
397 Ok(
398 json!({"format":"records","offset":offset,"records":records,"next_offset":next,"available":index}),
399 )
400}