treasury-store 0.2.2

Treasury storage
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
use std::{
    error::Error,
    fs::File,
    io::{Read, Seek, SeekFrom},
    mem,
    path::{Path, PathBuf},
    time::{Duration, SystemTime},
};

use eyre::WrapErr;
use hashbrown::HashMap;
use treasury_id::AssetId;
use url::Url;

use crate::{scheme::Scheme, sha256::HashSha256};

const PREFIX_STARTING_LEN: usize = 8;
const EXTENSION: &'static str = "treasure";
const DOT_EXTENSION: &'static str = ".treasure";

#[derive(serde::Serialize, serde::Deserialize)]
pub struct AssetMeta {
    id: AssetId,
    sha256: HashSha256,

    #[serde(skip_serializing_if = "Option::is_none", default)]
    format: Option<String>,

    #[serde(skip_serializing_if = "prefix_is_default", default = "default_prefix")]
    prefix: usize,

    #[serde(skip_serializing_if = "suffix_is_zero", default)]
    suffix: u64,

    // Array of dependencies of this asset.
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    dependencies: Vec<AssetId>,

    // URLs to source files.
    // Relative paths are relative to treasury base.
    #[serde(skip_serializing_if = "HashMap::is_empty", default)]
    sources: HashMap<String, u64>,
}

fn prefix_is_default(prefix: &usize) -> bool {
    *prefix == PREFIX_STARTING_LEN
}

fn default_prefix() -> usize {
    PREFIX_STARTING_LEN
}

fn suffix_is_zero(suffix: &u64) -> bool {
    *suffix == 0
}

impl AssetMeta {
    /// Creates new asset metadata.
    /// Puts ouput to the artifacs directory.
    /// Called when new asset is imported.
    ///
    /// `output` contain temporary path to imported asset artifact.
    /// `artifacts` is path to artifact directory.
    pub fn new(
        id: AssetId,
        mut format: Option<String>,
        sources: Vec<(String, SystemTime)>,
        mut dependencies: Vec<AssetId>,
        output: &Path,
        artifacts: &Path,
    ) -> eyre::Result<Self> {
        let sha256 = HashSha256::file_hash(output).wrap_err_with(|| {
            format!(
                "Failed to calculate hash of the file '{}'",
                output.display()
            )
        })?;

        let hex = format!("{:x}", sha256);

        with_path_candidates(&hex, artifacts, move |prefix, suffix, path| {
            match path.metadata() {
                Err(_) => {
                    // Artifact file does not exists.
                    // This is the most common case.
                    std::fs::rename(output, &path).wrap_err_with(|| {
                        format!(
                            "Failed to rename output file '{}' to artifact file '{}'",
                            output.display(),
                            path.display()
                        )
                    })?;

                    Ok(Some(AssetMeta {
                        id,
                        format: format.take(),
                        sha256,
                        prefix,
                        suffix,
                        sources: sources
                            .iter()
                            .map(|(source, modified)| {
                                (
                                    source.clone(),
                                    modified
                                        .duration_since(SystemTime::UNIX_EPOCH)
                                        .unwrap()
                                        .as_nanos() as u64,
                                )
                            })
                            .collect(),
                        dependencies: mem::take(&mut dependencies),
                    }))
                }
                Ok(meta) if meta.is_file() => {
                    let eq = files_eq(output, &path).wrap_err_with(|| {
                        format!(
                            "Failed to compare artifact file '{}' and new asset output '{}'",
                            path.display(),
                            output.display(),
                        )
                    })?;

                    if eq {
                        tracing::warn!("Artifact for asset '{}' is already in storage", id);

                        if let Err(err) = std::fs::remove_file(output) {
                            tracing::error!(
                                "Failed to remove duplicate artifact file '{}'. {:#}",
                                err,
                                output.display()
                            );
                        }

                        Ok(Some(AssetMeta {
                            id,
                            format: format.take(),
                            sha256,
                            prefix,
                            suffix,
                            sources: sources
                                .iter()
                                .map(|(source, modified)| {
                                    (
                                        source.clone(),
                                        modified
                                            .duration_since(SystemTime::UNIX_EPOCH)
                                            .unwrap()
                                            .as_nanos()
                                            as u64,
                                    )
                                })
                                .collect(),
                            dependencies: mem::take(&mut dependencies),
                        }))
                    } else {
                        // Prefixes are the same.
                        // Try longer prefix.
                        tracing::debug!("Artifact path collision");
                        Ok(None)
                    }
                }
                Ok(_) => {
                    // Path is occupied by directory.
                    // This should never be caused by treasury itself.
                    tracing::warn!(
                        "Artifacts storage occupied by non-file entity '{}'",
                        path.display()
                    );
                    Ok(None)
                }
            }
        })
    }

    pub fn id(&self) -> AssetId {
        self.id
    }

    pub fn format(&self) -> Option<&str> {
        self.format.as_deref()
    }

    pub fn needs_reimport(&self, base: &Url) -> bool {
        for (url, modified) in &self.sources {
            let url = match base.join(url) {
                Err(err) => {
                    tracing::error!(
                        "Failed to figure out source URL from base: {} and source: {}. {:#}. Asset can be outdated",
                        base,
                        url,
                        err,
                    );
                    continue;
                }
                Ok(url) => url,
            };

            let source_modified = SystemTime::UNIX_EPOCH + Duration::from_nanos(*modified);

            match url.scheme().parse() {
                Ok(Scheme::File) => {
                    let path = match url.to_file_path() {
                        Err(()) => {
                            tracing::error!("Invalid file URL");
                            continue;
                        }
                        Ok(path) => path,
                    };

                    let modified = match path.metadata().and_then(|meta| meta.modified()) {
                        Err(err) => {
                            tracing::error!(
                                "Failed to check how new the source file is. {:#}",
                                err
                            );
                            continue;
                        }
                        Ok(modified) => modified,
                    };

                    if modified < source_modified {
                        tracing::warn!("Source file is older than when asset was imported. Could be clock change. Reimort just in case");
                        return true;
                    }

                    if modified > source_modified {
                        tracing::debug!("Source file was updated");
                        return true;
                    }
                }
                Ok(Scheme::Data) => continue,
                Err(_) => tracing::error!("Unsupported scheme: '{}'", url.scheme()),
            }
        }

        false
    }

    /// Returns path to the artifact.
    pub fn artifact_path(&self, artifacts: &Path) -> PathBuf {
        let hex = format!("{:x}", self.sha256);
        let prefix = &hex[..self.prefix];

        match self.suffix {
            0 => artifacts.join(prefix),
            suffix => artifacts.join(format!("{}:{}", prefix, suffix)),
        }
    }
}

#[derive(Debug, thiserror::Error)]
#[error("Error: '{}' while trying to canonicalize path '{}'", error, path.display())]
struct CanonError {
    #[source]
    error: std::io::Error,
    path: PathBuf,
}

#[derive(Debug, thiserror::Error)]
#[error("Failed to convert path '{}' to URL", path.display())]
struct UrlFromPathError {
    path: PathBuf,
}

#[derive(Debug, thiserror::Error)]
#[error("Error: '{}' with file: '{}'", error, path.display())]
struct FileError<E: Error> {
    #[source]
    error: E,
    path: PathBuf,
}

/// Data attached to single asset source.
/// It may include several assets.
/// If attached to external source outside treasury directory
/// then it is stored together with artifacts by URL hash.
#[derive(serde::Serialize, serde::Deserialize)]
pub struct SourceMeta {
    url: Url,
    assets: HashMap<String, AssetMeta>,
}

impl SourceMeta {
    /// Finds and returns meta for the source URL.
    /// Creates new file if needed.
    pub fn new(source: &Url, base: &Path, external: &Path) -> eyre::Result<SourceMeta> {
        let (meta_path, is_external) = get_meta_path(source, base, external)?;

        if is_external {
            SourceMeta::new_external(&meta_path, source)
        } else {
            SourceMeta::new_local(&meta_path)
        }
    }

    pub fn url(&self) -> &Url {
        &self.url
    }

    pub fn is_local_meta_path(meta_path: &Path) -> bool {
        meta_path.extension().map_or(false, |e| e == EXTENSION)
    }

    pub fn new_local(meta_path: &Path) -> eyre::Result<SourceMeta> {
        SourceMeta::read_local(meta_path, true)
    }

    pub fn open_local(meta_path: &Path) -> eyre::Result<SourceMeta> {
        SourceMeta::read_local(meta_path, false)
    }

    fn read_local(meta_path: &Path, allow_missing: bool) -> eyre::Result<Self> {
        let source_path = meta_path.with_extension("");
        let url = Url::from_file_path(&source_path)
            .map_err(|()| UrlFromPathError { path: source_path })?;

        match std::fs::read(meta_path) {
            Err(err) if allow_missing && err.kind() == std::io::ErrorKind::NotFound => {
                Ok(SourceMeta {
                    url,
                    assets: HashMap::new(),
                })
            }
            Err(err) => Err(FileError {
                error: err,
                path: meta_path.to_owned(),
            })
            .wrap_err("Meta read failed"),
            Ok(data) => {
                let assets = toml::from_slice(&data)
                    .map_err(|err| FileError {
                        error: err,
                        path: meta_path.to_owned(),
                    })
                    .wrap_err("Meta read failed")?;
                Ok(SourceMeta { url, assets })
            }
        }
    }

    pub fn new_external(meta_path: &Path, source: &Url) -> eyre::Result<SourceMeta> {
        match std::fs::read(meta_path) {
            Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(SourceMeta {
                url: source.clone(),
                assets: HashMap::new(),
            }),
            Err(err) => Err(FileError {
                error: err,
                path: meta_path.to_owned(),
            })
            .wrap_err("Meta read failed"),
            Ok(data) => {
                let assets = toml::from_slice(&data)
                    .map_err(|err| FileError {
                        error: err,
                        path: meta_path.to_owned(),
                    })
                    .wrap_err("Meta read failed")?;
                Ok(SourceMeta {
                    url: source.clone(),
                    assets,
                })
            }
        }
    }

    pub fn open_external(meta_path: &Path) -> eyre::Result<SourceMeta> {
        match std::fs::read(meta_path) {
            Err(err) => Err(FileError {
                error: err,
                path: meta_path.to_owned(),
            })
            .wrap_err("Meta read failed"),
            Ok(data) => {
                let meta = toml::from_slice(&data)
                    .map_err(|err| FileError {
                        error: err,
                        path: meta_path.to_owned(),
                    })
                    .wrap_err("Meta read failed")?;
                Ok(meta)
            }
        }
    }

    pub fn get_asset(&self, target: &str) -> Option<&AssetMeta> {
        self.assets.get(target)
    }

    pub fn assets(&self) -> impl Iterator<Item = (&str, &AssetMeta)> + '_ {
        self.assets.iter().map(|(target, meta)| (&**target, meta))
    }

    pub fn add_asset(
        &mut self,
        target: String,
        asset: AssetMeta,
        base: &Path,
        external: &Path,
    ) -> eyre::Result<()> {
        self.assets.insert(target, asset);

        let (meta_path, is_external) = get_meta_path(&self.url, base, external)?;
        if is_external {
            self.write_with_url_to(&meta_path)?;
        } else {
            self.write_to(&meta_path)?;
        }
        Ok(())
    }

    fn write_to(&self, path: &Path) -> eyre::Result<()> {
        let data = toml::to_string_pretty(&self.assets)
            .map_err(|err| FileError {
                error: err,
                path: path.to_owned(),
            })
            .wrap_err("Meta write failed")?;
        std::fs::write(path, data.as_bytes())
            .map_err(|err| FileError {
                error: err,
                path: path.to_owned(),
            })
            .wrap_err("Meta write failed")?;
        Ok(())
    }

    fn write_with_url_to(&self, path: &Path) -> eyre::Result<()> {
        let data = toml::to_string_pretty(self)
            .map_err(|err| FileError {
                error: err,
                path: path.to_owned(),
            })
            .wrap_err("Meta write failed")?;
        std::fs::write(path, data.as_bytes())
            .map_err(|err| FileError {
                error: err,
                path: path.to_owned(),
            })
            .wrap_err("Meta write failed")?;
        Ok(())
    }
}

fn files_eq(lhs: &Path, rhs: &Path) -> std::io::Result<bool> {
    let mut lhs = File::open(lhs)?;
    let mut rhs = File::open(rhs)?;

    let lhs_size = lhs.seek(SeekFrom::End(0))?;
    let rhs_size = rhs.seek(SeekFrom::End(0))?;

    if lhs_size != rhs_size {
        return Ok(false);
    }

    lhs.seek(SeekFrom::Start(0))?;
    rhs.seek(SeekFrom::Start(0))?;

    let mut buffer_lhs = [0; 16536];
    let mut buffer_rhs = [0; 16536];

    loop {
        let read = lhs.read(&mut buffer_lhs)?;
        if read == 0 {
            return Ok(true);
        }
        rhs.read_exact(&mut buffer_rhs[..read])?;

        if buffer_lhs[..read] != buffer_rhs[..read] {
            return Ok(false);
        }
    }
}

/// Finds and returns meta for the source URL.
/// Creates new file if needed.
fn get_meta_path(source: &Url, base: &Path, external: &Path) -> eyre::Result<(PathBuf, bool)> {
    if source.scheme() == "file" {
        match source.to_file_path() {
            Ok(path) => {
                let path =
                    dunce::canonicalize(&path).map_err(|err| CanonError { error: err, path })?;

                if path.starts_with(base) {
                    // Files inside `base` directory has meta attached to them as sibling file with `.treasure` extension added.

                    let mut filename = path.file_name().unwrap_or("".as_ref()).to_owned();
                    filename.push(DOT_EXTENSION);

                    let path = path.with_file_name(filename);
                    return Ok((path, false));
                }
            }
            Err(()) => {}
        }
    }

    std::fs::create_dir_all(external).wrap_err_with(|| {
        format!(
            "Failed to create external directory '{}'",
            external.display()
        )
    })?;

    let hash = HashSha256::new(source.as_str());
    let hex = format!("{:x}", hash);

    with_path_candidates(&hex, external, |_prefix, _suffix, path| {
        match path.metadata() {
            Err(_) => {
                // Not exists. Let's try to occupy.
                Ok(Some((path, true)))
            }
            Ok(md) => {
                if md.is_file() {
                    match SourceMeta::open_external(&path) {
                        Err(_) => {
                            tracing::error!(
                                "Failed to open existing source metadata at '{}'",
                                path.display()
                            );
                        }
                        Ok(meta) => {
                            if meta.url == *source {
                                return Ok(Some((path, true)));
                            }
                        }
                    }
                }
                Ok(None)
            }
        }
    })
}

fn with_path_candidates<T, E>(
    hex: &str,
    base: &Path,
    mut f: impl FnMut(usize, u64, PathBuf) -> Result<Option<T>, E>,
) -> Result<T, E> {
    use std::fmt::Write;

    for len in PREFIX_STARTING_LEN..=hex.len() {
        let path = base.join(&hex[..len]);

        match f(len, 0, path) {
            Ok(None) => {}
            Ok(Some(ok)) => return Ok(ok),
            Err(err) => return Err(err),
        }
    }

    // Rarely needed.
    let mut name = hex.to_owned();

    for suffix in 0u64.. {
        name.truncate(hex.len());
        write!(name, ":{}", suffix).unwrap();

        let path = base.join(&name);

        match f(hex.len(), suffix, path) {
            Ok(None) => {}
            Ok(Some(ok)) => return Ok(ok),
            Err(err) => return Err(err),
        }
    }

    unreachable!()
}