Skip to main content

artifactize_core/remote/
session.rs

1use std::{
2    collections::{BTreeSet, HashMap},
3    io::Write,
4    path::Path,
5    sync::{
6        Arc, Mutex,
7        atomic::{AtomicBool, Ordering},
8    },
9    time::{Duration, Instant},
10};
11
12use tokio::sync::OnceCell;
13
14use super::Record;
15use crate::{
16    auth::remote::{self, Failure, Principal, Remote, Share},
17    store::{Execution, Receipts, Request},
18};
19
20/// A key is looked up again at most once per second, however often verify polls,
21/// so concurrent waiters cannot flood the optional remote store with duplicate lookups.
22pub(crate) const REFRESH: Duration = Duration::from_secs(1);
23
24/// One process's use of the remote review store.
25///
26/// Outages (network errors, timeouts, 5xx) fail open: one warning, then the process
27/// continues without the remote. Every other failure is an error.
28pub struct Session {
29    remote: Remote,
30    principal: OnceCell<Option<Principal>>,
31    offline: AtomicBool,
32    looked_up: Mutex<HashMap<crate::types::ReuseKey, Instant>>,
33}
34
35fn warn(message: &str) {
36    let _ = writeln!(std::io::stderr().lock(), "{message}");
37}
38
39impl Session {
40    /// Resolve the configuration offline; `None` when no remote is configured.
41    pub fn open(state: Option<&Path>, repo: Option<&Path>) -> Result<Option<Arc<Self>>, String> {
42        Ok(remote::remote(state, repo)?.map(|remote| {
43            Arc::new(Self {
44                remote,
45                principal: OnceCell::new(),
46                offline: AtomicBool::new(false),
47                looked_up: Mutex::default(),
48            })
49        }))
50    }
51
52    fn failed<T: Default>(&self, failure: Failure) -> Result<T, String> {
53        if !matches!(
54            failure,
55            crate::auth::remote::Failure::Transport(_)
56                | crate::auth::remote::Failure::ServerOutage(_)
57        ) {
58            return Err(failure.into());
59        }
60        if !self.offline.swap(true, Ordering::SeqCst) {
61            warn(&format!(
62                "{}; continuing without the remote review store.",
63                failure.message().trim_end_matches('.')
64            ));
65        }
66        Ok(T::default())
67    }
68
69    /// The token's principal and scopes, asked once; `None` while the remote is unavailable.
70    async fn principal(&self) -> Result<Option<&Principal>, String> {
71        if self.offline.load(Ordering::SeqCst) {
72            return Ok(None);
73        }
74        let principal = self
75            .principal
76            .get_or_try_init(|| async {
77                match self.remote.whoami().await {
78                    Ok(principal) => Ok(Some(principal)),
79                    Err(failure) => self.failed(failure),
80                }
81            })
82            .await?;
83        Ok(principal.as_ref())
84    }
85
86    /// Read-only: the latest remote record of each key as a self-contained execution, not yet
87    /// stored.
88    pub async fn lookup(&self, keys: &[crate::types::ReuseKey]) -> Result<Vec<Execution>, String> {
89        if keys.is_empty() {
90            return Ok(Vec::new());
91        }
92        let Some(principal) = self.principal().await? else {
93            return Ok(Vec::new());
94        };
95        if !has_scope(principal, &crate::auth::remote::Scope::Read) {
96            return Ok(Vec::new());
97        }
98        let entries = match self.remote.lookup(keys).await {
99            Ok(entries) => entries,
100            Err(failure) => return self.failed(failure),
101        };
102        let requested: BTreeSet<_> = keys.iter().map(crate::types::ReuseKey::as_str).collect();
103        let mut executions = Vec::new();
104        for entry in entries {
105            // A record that does not validate is skipped; reviewing locally is always correct.
106            let mirrored = entry.and_then(|record| {
107                if !requested.contains(record.key.as_str()) {
108                    return Err("the store returned an unrequested key".into());
109                }
110                record.mirror(self.remote.url().as_str())
111            });
112            match mirrored {
113                Ok(execution) => executions.push(execution),
114                Err(error) => warn(&format!(
115                    "Ignoring an invalid remote review record: {error}"
116                )),
117            }
118        }
119        Ok(executions)
120    }
121
122    /// Look up the store's latest record of each key and mirror it into the local history when
123    /// it completed after the key's latest local record, so the normal reuse path takes the
124    /// newer of the two. Each key is looked up at most once per second.
125    pub async fn refresh(
126        &self,
127        receipts: &Receipts,
128        keys: Vec<crate::types::ReuseKey>,
129    ) -> Result<(), String> {
130        let now = Instant::now();
131        let keys: Vec<_> = {
132            let mut looked_up = self.looked_up.lock().expect("lookup times");
133            keys.into_iter()
134                .filter(|key| {
135                    let due = looked_up
136                        .get(key)
137                        .is_none_or(|at| now.duration_since(*at) >= REFRESH);
138                    if due {
139                        looked_up.insert(key.clone(), now);
140                    }
141                    due
142                })
143                .collect()
144        };
145        if keys.is_empty() || self.offline.load(Ordering::SeqCst) {
146            return Ok(());
147        }
148        for execution in self.lookup(&keys).await? {
149            receipts.mirror_execution(&execution).await?;
150        }
151        Ok(())
152    }
153
154    /// Publish a request's result when its own settle just appended it to the local history:
155    /// a GREEN/RED with a key, forced or not, never a mirror or an error.
156    pub async fn publish_request(
157        &self,
158        receipts: &Receipts,
159        request: &Request,
160    ) -> Result<(), String> {
161        let (Some(_), Some(execution_id)) = (&request.key, &request.execution_id) else {
162            return Ok(());
163        };
164        match receipts.published_execution(execution_id).await? {
165            Some(execution) => self.publish(&execution).await,
166            None => Ok(()),
167        }
168    }
169
170    /// Publish a result whose local settle published its cache entry. Nothing is sent while
171    /// the remote is unavailable or without the publish scope; Human results need `human`.
172    async fn publish(&self, execution: &Execution) -> Result<(), String> {
173        let Some(principal) = self.principal().await? else {
174            return Ok(());
175        };
176        if !has_scope(principal, &crate::auth::remote::Scope::Publish) {
177            return Ok(());
178        }
179        let record = match record(execution, principal, self.remote.share) {
180            Ok(record) => record,
181            Err(reason) => {
182                warn(&format!("This result stays local: {reason}."));
183                return Ok(());
184            }
185        };
186        match self.remote.publish(&record).await {
187            Ok(_) => Ok(()),
188            Err(failure) => self.failed(failure),
189        }
190    }
191}
192
193pub(super) fn has_scope(principal: &Principal, scope: &crate::auth::remote::Scope) -> bool {
194    principal.scopes.contains(scope)
195}
196
197/// The record a publishing token may send for a local result, or why it stays local.
198pub(super) fn record(
199    execution: &Execution,
200    principal: &Principal,
201    share: Share,
202) -> Result<Record, String> {
203    if execution.profile.kind() == crate::config::ProfileKind::Human
204        && !has_scope(principal, &crate::auth::remote::Scope::Human)
205    {
206        return Err(format!(
207            "remote token {} lacks the human scope",
208            principal.principal
209        ));
210    }
211    Record::new(execution, share == Share::Full)
212}