1use std::any::Any;
18use std::future::Future;
19use std::sync::Arc;
20
21use crate::db::Value;
22use crate::error::{Error, Result};
23
24pub trait Access: Send + Sync + 'static {
28 fn describe(&self) -> String;
30
31 fn owns(&self, column: &str) -> Option<Value> {
36 let _ = column;
37 None
38 }
39
40 fn as_any(&self) -> &dyn Any;
42
43 fn reference(&self) -> Option<serde_json::Value> {
47 None
48 }
49}
50
51pub trait Rebuild: Access + Sized {
56 const KIND: &'static str;
58
59 fn rebuild(reference: serde_json::Value) -> impl Future<Output = Result<Self>> + Send;
61}
62
63pub trait AccessField: Sized {
66 fn reference(&self) -> serde_json::Value;
67 fn rebuild(reference: serde_json::Value) -> impl Future<Output = Result<Self>> + Send;
68}
69
70impl<M: crate::model::Model + Send> AccessField for M {
71 fn reference(&self) -> serde_json::Value {
72 match self.id_value() {
73 Value::Int(id) => serde_json::Value::from(id),
74 other => serde_json::Value::from(other.to_text()),
75 }
76 }
77
78 fn rebuild(reference: serde_json::Value) -> impl Future<Output = Result<Self>> + Send {
79 let id = match reference {
80 serde_json::Value::Number(n) => Value::Int(n.as_i64().unwrap_or_default()),
81 other => Value::Text(other.as_str().unwrap_or_default().to_owned()),
82 };
83 M::find(id)
84 }
85}
86
87type Rebuilding = std::pin::Pin<Box<dyn Future<Output = Result<Arc<dyn Access>>> + Send>>;
89
90type Rebuilder = fn(serde_json::Value) -> Rebuilding;
91
92static KINDS: std::sync::RwLock<std::collections::BTreeMap<&'static str, Rebuilder>> =
93 std::sync::RwLock::new(std::collections::BTreeMap::new());
94
95pub fn register<A: Rebuild>() {
98 fn rebuild<A: Rebuild>(reference: serde_json::Value) -> Rebuilding {
99 Box::pin(async move { Ok(Arc::new(A::rebuild(reference).await?) as Arc<dyn Access>) })
100 }
101 KINDS
102 .write()
103 .unwrap_or_else(|e| e.into_inner())
104 .insert(A::KIND, rebuild::<A>);
105}
106
107pub(crate) async fn rebuild(reference: serde_json::Value) -> Result<Arc<dyn Access>> {
109 let kind = reference["kind"].as_str().unwrap_or_default().to_owned();
110 let rebuild = KINDS
111 .read()
112 .unwrap_or_else(|e| e.into_inner())
113 .get(kind.as_str())
114 .copied()
115 .ok_or_else(|| Error::internal(format!("no Access is registered as `{kind}`")))?;
116 rebuild(reference).await
117}
118
119#[derive(Clone)]
121pub struct RequestAccess(pub Arc<dyn Access>);
122
123impl std::ops::Deref for RequestAccess {
124 type Target = dyn Access;
125
126 fn deref(&self) -> &(dyn Access + 'static) {
127 &*self.0
128 }
129}
130
131impl Access for RequestAccess {
134 fn describe(&self) -> String {
135 self.0.describe()
136 }
137
138 fn owns(&self, column: &str) -> Option<Value> {
139 self.0.owns(column)
140 }
141
142 fn as_any(&self) -> &dyn Any {
143 self.0.as_any()
144 }
145}
146
147impl AsRef<RequestAccess> for RequestAccess {
148 fn as_ref(&self) -> &RequestAccess {
149 self
150 }
151}
152
153impl RequestAccess {
154 pub fn of<A: Access + Clone>(&self) -> Result<A> {
162 self.0
163 .as_any()
164 .downcast_ref::<A>()
165 .cloned()
166 .ok_or_else(Error::not_found)
167 }
168}
169
170#[derive(Debug, Clone, Copy)]
172pub struct SystemAccess {
173 pub reason: &'static str,
174}
175
176impl Access for SystemAccess {
177 fn describe(&self) -> String {
178 format!("system ({})", self.reason)
179 }
180
181 fn as_any(&self) -> &dyn Any {
182 self
183 }
184}
185
186tokio::task_local! {
187 static CURRENT: Arc<dyn Access>;
188}
189
190pub(crate) fn may_change_shared() -> bool {
194 current().is_none_or(|access| access.as_any().is::<SystemAccess>())
195}
196
197pub fn current() -> Option<Arc<dyn Access>> {
198 CURRENT
199 .try_with(Arc::clone)
200 .ok()
201 .or_else(|| crate::current::get::<RequestAccess>().map(|access| access.0))
202}
203
204pub fn required() -> Result<RequestAccess> {
211 current()
212 .map(RequestAccess)
213 .ok_or_else(|| Error::new(http::StatusCode::UNAUTHORIZED, "no access"))
214}
215
216static STRICT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
219
220pub fn strict(on: bool) {
224 STRICT.store(on, std::sync::atomic::Ordering::Relaxed);
225}
226
227pub(crate) fn check_unscoped(table: &str) -> Result<()> {
232 let Some(access) = current() else {
233 return Ok(());
234 };
235 if access.as_any().is::<SystemAccess>() {
236 return Ok(());
237 }
238 let message = format!(
239 "`{table}` read for {} without its access: read it through `Model.for(access)`, \
240 or inside `glacier::access::unscoped(\"why\", …)`",
241 access.describe()
242 );
243 if STRICT.load(std::sync::atomic::Ordering::Relaxed) {
244 return Err(Error::internal(message));
245 }
246 tracing::warn!(target: "glacier::access", "{message}");
247 Ok(())
248}
249
250pub async fn with_access<F: Future>(access: impl Access, fut: F) -> F::Output {
252 CURRENT.scope(Arc::new(access), fut).await
253}
254
255pub(crate) async fn with_shared<F: Future>(access: Arc<dyn Access>, fut: F) -> F::Output {
257 CURRENT.scope(access, fut).await
258}
259
260pub async fn unscoped<F: Future>(reason: &'static str, fut: F) -> F::Output {
264 with_access(SystemAccess { reason }, fut).await
265}
266
267#[cfg(test)]
268mod tests {
269 use super::*;
270
271 #[tokio::test]
272 async fn work_knows_who_it_is_for() {
273 assert!(current().is_none());
274 let seen = unscoped("pruning", async { current().map(|a| a.describe()) }).await;
275 assert_eq!(seen.as_deref(), Some("system (pruning)"));
276 }
277}