Skip to main content

artifactize_core/remote/
push.rs

1use std::{collections::BTreeSet, io::Write, path::Path};
2
3use serde::Serialize;
4
5use super::session::{has_scope, record};
6use crate::{auth::remote, store::history};
7
8/// Bound retained local execution payloads per push batch while paging the whole key history.
9const PAGE_ENTRIES: usize = 100;
10
11#[derive(Debug, Default, Serialize)]
12#[serde(rename_all = "camelCase")]
13pub struct Push {
14    pub dry_run: bool,
15    /// Sent and created, or with `--dry-run` not yet in the store.
16    pub pushed: usize,
17    pub existing: usize,
18    /// Kept local: Human sign-offs without the human scope, or records over their limit.
19    pub skipped: usize,
20}
21
22/// Send the latest local GREEN/RED record of each key, never a mirror; records the store
23/// already holds are no-ops. Unlike verify, this explicit command fails on any remote failure.
24pub async fn push(
25    state: Option<&Path>,
26    repo: Option<&Path>,
27    dry_run: bool,
28) -> Result<Push, String> {
29    push_with_clock(state, repo, dry_run, crate::types::Timestamp::now).await
30}
31
32/// Push results and use the supplied clock when recording a completed publication.
33pub async fn push_with_clock(
34    state: Option<&Path>,
35    repo: Option<&Path>,
36    dry_run: bool,
37    clock: impl FnOnce() -> crate::types::Timestamp,
38) -> Result<Push, String> {
39    let remote = remote::remote(state, repo)?.ok_or(
40        "No remote review store is configured; run `artifactize remote login URL` or set ARTIFACTIZE_REMOTE.",
41    )?;
42    let principal = remote.whoami().await.map_err(String::from)?;
43    if !has_scope(&principal, &crate::auth::remote::Scope::Publish) {
44        return Err(format!(
45            "Remote token {} lacks the publish scope.",
46            principal.principal
47        ));
48    }
49    let state = crate::store::state_dir(state)?;
50    let mut report = Push {
51        dry_run,
52        ..Push::default()
53    };
54    let mut after = None;
55    loop {
56        let page = history::local(&state, after.take(), PAGE_ENTRIES).await?;
57        let Some((last_key, _)) = page.last() else {
58            break;
59        };
60        after = Some(last_key.clone());
61        let mut records = Vec::new();
62        for (_, execution) in &page {
63            match record(execution, &principal, remote.share) {
64                Ok(record) => records.push(record),
65                Err(reason) => {
66                    report.skipped += 1;
67                    let _ = writeln!(
68                        std::io::stderr().lock(),
69                        "Skipped {} ({}): {reason}.",
70                        execution.key.as_deref().unwrap_or_default(),
71                        execution.provenance.eval_id
72                    );
73                }
74            }
75        }
76        // With the read scope, a record that is already the store's latest is not sent again.
77        let existing: BTreeSet<_> = if has_scope(&principal, &crate::auth::remote::Scope::Read) {
78            let keys: Vec<_> = records.iter().map(|record| record.key.clone()).collect();
79            remote
80                .lookup(&keys)
81                .await
82                .map_err(String::from)?
83                .into_iter()
84                .filter_map(Result::ok)
85                .map(|entry| (entry.key, entry.execution_id))
86                .collect()
87        } else {
88            BTreeSet::new()
89        };
90        for record in records {
91            // The store keeps each execution once; a resent record answers `created: false`.
92            let created = !existing.contains(&(record.key.clone(), record.execution_id.clone()))
93                && (dry_run || remote.publish(&record).await.map_err(String::from)?);
94            if created {
95                report.pushed += 1;
96            } else {
97                report.existing += 1;
98            }
99        }
100    }
101    if !dry_run && report.pushed > 0 {
102        super::pushed::record_at(&state, report.pushed, clock())?;
103    }
104    Ok(report)
105}