use std::any::Any;
use std::future::Future;
use std::sync::Arc;
use crate::db::Value;
use crate::error::{Error, Result};
pub trait Access: Send + Sync + 'static {
fn describe(&self) -> String;
fn owns(&self, column: &str) -> Option<Value> {
let _ = column;
None
}
fn as_any(&self) -> &dyn Any;
fn reference(&self) -> Option<serde_json::Value> {
None
}
}
pub trait Rebuild: Access + Sized {
const KIND: &'static str;
fn rebuild(reference: serde_json::Value) -> impl Future<Output = Result<Self>> + Send;
}
pub trait AccessField: Sized {
fn reference(&self) -> serde_json::Value;
fn rebuild(reference: serde_json::Value) -> impl Future<Output = Result<Self>> + Send;
}
impl<M: crate::model::Model + Send> AccessField for M {
fn reference(&self) -> serde_json::Value {
match self.id_value() {
Value::Int(id) => serde_json::Value::from(id),
other => serde_json::Value::from(other.to_text()),
}
}
fn rebuild(reference: serde_json::Value) -> impl Future<Output = Result<Self>> + Send {
let id = match reference {
serde_json::Value::Number(n) => Value::Int(n.as_i64().unwrap_or_default()),
other => Value::Text(other.as_str().unwrap_or_default().to_owned()),
};
M::find(id)
}
}
type Rebuilding = std::pin::Pin<Box<dyn Future<Output = Result<Arc<dyn Access>>> + Send>>;
type Rebuilder = fn(serde_json::Value) -> Rebuilding;
static KINDS: std::sync::RwLock<std::collections::BTreeMap<&'static str, Rebuilder>> =
std::sync::RwLock::new(std::collections::BTreeMap::new());
pub fn register<A: Rebuild>() {
fn rebuild<A: Rebuild>(reference: serde_json::Value) -> Rebuilding {
Box::pin(async move { Ok(Arc::new(A::rebuild(reference).await?) as Arc<dyn Access>) })
}
KINDS
.write()
.unwrap_or_else(|e| e.into_inner())
.insert(A::KIND, rebuild::<A>);
}
pub(crate) async fn rebuild(reference: serde_json::Value) -> Result<Arc<dyn Access>> {
let kind = reference["kind"].as_str().unwrap_or_default().to_owned();
let rebuild = KINDS
.read()
.unwrap_or_else(|e| e.into_inner())
.get(kind.as_str())
.copied()
.ok_or_else(|| Error::internal(format!("no Access is registered as `{kind}`")))?;
rebuild(reference).await
}
#[derive(Clone)]
pub struct RequestAccess(pub Arc<dyn Access>);
impl std::ops::Deref for RequestAccess {
type Target = dyn Access;
fn deref(&self) -> &(dyn Access + 'static) {
&*self.0
}
}
impl Access for RequestAccess {
fn describe(&self) -> String {
self.0.describe()
}
fn owns(&self, column: &str) -> Option<Value> {
self.0.owns(column)
}
fn as_any(&self) -> &dyn Any {
self.0.as_any()
}
}
impl AsRef<RequestAccess> for RequestAccess {
fn as_ref(&self) -> &RequestAccess {
self
}
}
impl RequestAccess {
pub fn of<A: Access + Clone>(&self) -> Result<A> {
self.0
.as_any()
.downcast_ref::<A>()
.cloned()
.ok_or_else(Error::not_found)
}
}
#[derive(Debug, Clone, Copy)]
pub struct SystemAccess {
pub reason: &'static str,
}
impl Access for SystemAccess {
fn describe(&self) -> String {
format!("system ({})", self.reason)
}
fn as_any(&self) -> &dyn Any {
self
}
}
tokio::task_local! {
static CURRENT: Arc<dyn Access>;
}
pub(crate) fn may_change_shared() -> bool {
current().is_none_or(|access| access.as_any().is::<SystemAccess>())
}
pub fn current() -> Option<Arc<dyn Access>> {
CURRENT
.try_with(Arc::clone)
.ok()
.or_else(|| crate::current::get::<RequestAccess>().map(|access| access.0))
}
pub fn required() -> Result<RequestAccess> {
current()
.map(RequestAccess)
.ok_or_else(|| Error::new(http::StatusCode::UNAUTHORIZED, "no access"))
}
static STRICT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
pub fn strict(on: bool) {
STRICT.store(on, std::sync::atomic::Ordering::Relaxed);
}
pub(crate) fn check_unscoped(table: &str) -> Result<()> {
let Some(access) = current() else {
return Ok(());
};
if access.as_any().is::<SystemAccess>() {
return Ok(());
}
let message = format!(
"`{table}` read for {} without its access: read it through `Model.for(access)`, \
or inside `glacier::access::unscoped(\"why\", …)`",
access.describe()
);
if STRICT.load(std::sync::atomic::Ordering::Relaxed) {
return Err(Error::internal(message));
}
tracing::warn!(target: "glacier::access", "{message}");
Ok(())
}
pub async fn with_access<F: Future>(access: impl Access, fut: F) -> F::Output {
CURRENT.scope(Arc::new(access), fut).await
}
pub(crate) async fn with_shared<F: Future>(access: Arc<dyn Access>, fut: F) -> F::Output {
CURRENT.scope(access, fut).await
}
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)"));
}
}