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
//! Who a piece of work acts for: a signed-in user, an organisation, or
//! the system itself. Glacier's name for what Phoenix calls a scope.
//!
//! This is the seam 0.4's accounts build on: requests will set the access
//! from the signed-in user, and queries will be limited to what it may
//! see. For now it records who work is done for, and work that runs for
//! nobody in particular (webhooks, pruning, recurring jobs) says so
//! explicitly, with a reason:
//!
//! ```ignore
//! glacier::access::unscoped("nightly digest", async {
//! // …
//! })
//! .await
//! ```
use std::future::Future;
use std::sync::Arc;
/// Who work is done for.
pub trait Access: Send + Sync + 'static {
/// For logs and traces: `user:12`, `org:3`, `system (webhooks)`.
fn describe(&self) -> String;
}
/// Work done for nobody in particular, with why.
#[derive(Debug, Clone, Copy)]
pub struct SystemAccess {
pub reason: &'static str,
}
impl Access for SystemAccess {
fn describe(&self) -> String {
format!("system ({})", self.reason)
}
}
tokio::task_local! {
static CURRENT: Arc<dyn Access>;
}
/// The access the current work runs with, if any.
pub fn current() -> Option<Arc<dyn Access>> {
CURRENT.try_with(Arc::clone).ok()
}
/// Runs `fut` for `access`.
pub async fn with_access<F: Future>(access: impl Access, fut: F) -> F::Output {
CURRENT.scope(Arc::new(access), fut).await
}
/// Runs `fut` for the system, saying why: what webhooks, pruning and
/// recurring jobs run as. In 0.4 it's the explicit way past the limits a
/// user's access puts on queries.
pub async fn unscoped<F: Future>(reason: &'static str, fut: F) -> F::Output {
with_access(SystemAccess { reason }, fut).await
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn work_knows_who_it_is_for() {
assert!(current().is_none());
let seen = unscoped("pruning", async { current().map(|a| a.describe()) }).await;
assert_eq!(seen.as_deref(), Some("system (pruning)"));
}
}