use super::{ActionCallError, Caller};
pub const RESOURCE_READS_UNAVAILABLE: &str = "this provider reads no records outside their apps";
pub const RESOURCE_READ_REFUSED: &str = "not allowed to read this record";
pub const RESOURCE_WRITE_REFUSED: &str = "not allowed to change this record";
pub const RESOURCE_READS_FOR_AGENTS: &str = "only a person, an app acting for its person, or an agent \
acting for the person who admitted it, reads records outside their app; a session a person's \
device handed to an agent reads nothing here";
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct ResourceAddress {
pub workspace: String,
pub app: String,
pub record: String,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct ListedResource {
pub address: ResourceAddress,
pub kind: Option<String>,
}
impl ListedResource {
#[must_use]
pub fn document(address: ResourceAddress) -> Self {
Self {
address,
kind: None,
}
}
#[must_use]
pub fn read_listing(workspace: &str, app: &str, listing: &serde_json::Value) -> Vec<Self> {
let text = |record: &serde_json::Value, key: &str| {
record
.get(key)
.and_then(serde_json::Value::as_str)
.map(str::to_owned)
};
listing
.get("records")
.and_then(serde_json::Value::as_array)
.into_iter()
.flatten()
.map(|record| Self {
address: ResourceAddress {
workspace: workspace.to_owned(),
app: text(record, "app").unwrap_or_else(|| app.to_owned()),
record: text(record, "record").unwrap_or_default(),
},
kind: text(record, "kind"),
})
.collect()
}
}
pub const DEVICE_SETTINGS: &str = "settings";
#[must_use]
pub fn device_record_space(device: &[u8; 32]) -> String {
format!("devices/{}", hex::encode(device))
}
pub const DEVICE_SETTINGS_REFUSED: &str = "Only this device's person, from any of their devices, and whoever they granted there, read \
its settings";
pub const DEVICE_JOBS: &str = "jobs";
#[must_use]
pub fn device_job_address(device: &[u8; 32], job: &str) -> ResourceAddress {
ResourceAddress {
workspace: device_record_space(device),
app: DEVICE_JOBS.to_owned(),
record: job.to_owned(),
}
}
#[must_use]
pub fn device_job_path(device: &[u8; 32], job: &str) -> String {
format!("devices/{}/jobs/{job}", hex::encode(device))
}
#[must_use]
pub fn parse_job_path(path: &str) -> Option<([u8; 32], String)> {
let (device, job) = path.strip_prefix("devices/")?.split_once("/jobs/")?;
if job.is_empty() || job.contains('/') || device.contains('/') {
return None;
}
let mut key = [0; 32];
hex::decode_to_slice(device, &mut key).ok()?;
Some((key, job.to_owned()))
}
#[must_use]
pub fn parse_device_record_space(space: &str) -> Option<[u8; 32]> {
let hex = space.strip_prefix("devices/")?;
if hex.len() != 64 || hex.contains('/') {
return None;
}
let mut key = [0; 32];
hex::decode_to_slice(hex, &mut key).ok()?;
Some(key)
}
#[must_use]
pub fn device_record_address(device: &[u8; 32], record: &str) -> ResourceAddress {
ResourceAddress {
workspace: device_record_space(device),
app: DEVICE_SETTINGS.to_owned(),
record: record.to_owned(),
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ResourceCopy {
Document(Vec<u8>),
Read(serde_json::Value),
Reading {
value: serde_json::Value,
revision: Option<String>,
},
Absent,
}
impl ResourceCopy {
#[must_use]
pub const fn reading(value: serde_json::Value, revision: Option<String>) -> Self {
Self::Reading { value, revision }
}
}
pub type Decided = Result<(), ActionCallError>;
pub type ReadsAnswer<'a, T> =
std::pin::Pin<Box<dyn std::future::Future<Output = Result<T, ActionCallError>> + Send + 'a>>;
pub type ReadingAnswer =
std::pin::Pin<Box<dyn std::future::Future<Output = super::RemoteActionMessage> + Send>>;
pub fn reads_answer<'a, T>(
answer: impl std::future::Future<Output = Result<T, ActionCallError>> + Send + 'a,
) -> ReadsAnswer<'a, T> {
Box::pin(answer)
}
fn unavailable<'a, T: Send + 'a>() -> ReadsAnswer<'a, T> {
Box::pin(std::future::ready(Err(ActionCallError::Unavailable {
reason: RESOURCE_READS_UNAVAILABLE.into(),
})))
}
pub trait ResourceReads: Send + Sync {
fn read<'a>(
&'a self,
caller: &'a Caller,
address: &'a ResourceAddress,
) -> ReadsAnswer<'a, ResourceCopy> {
let _ = (caller, address);
unavailable()
}
fn may_read<'a>(
&'a self,
caller: &'a Caller,
address: &'a ResourceAddress,
) -> ReadsAnswer<'a, ()> {
Box::pin(async move { self.read(caller, address).await.map(|_| ()) })
}
fn may_write<'a>(
&'a self,
caller: &'a Caller,
address: &'a ResourceAddress,
) -> ReadsAnswer<'a, ()> {
Box::pin(async move { self.read(caller, address).await.map(|_| ()) })
}
fn answer_read(
self: std::sync::Arc<Self>,
caller: &Caller,
correlation: u64,
read: super::ResourceReadRequest,
) -> ReadingAnswer
where
Self: 'static;
fn watch<'a>(
&'a self,
caller: &'a Caller,
address: &'a ResourceAddress,
wake: &'a ResourceWake,
) -> ReadsAnswer<'a, ()> {
let _ = (caller, address, wake);
unavailable()
}
fn list<'a>(
&'a self,
caller: &'a Caller,
workspace: &'a str,
app: &'a str,
) -> ReadsAnswer<'a, Vec<ListedResource>> {
let _ = (caller, workspace, app);
unavailable()
}
fn store_read<'a>(
&'a self,
caller: &'a Caller,
address: &'a ResourceAddress,
read: serde_json::Value,
) -> ReadsAnswer<'a, serde_json::Value> {
let _ = (caller, address, read);
unavailable()
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct HeldCopies(pub std::collections::HashMap<String, Vec<u8>>);
impl HeldCopies {
fn held(&self, address: &ResourceAddress) -> ResourceCopy {
self.0
.get(&address.record)
.map_or(ResourceCopy::Absent, |bytes| {
ResourceCopy::Document(bytes.clone())
})
}
}
impl ResourceReads for HeldCopies {
fn read<'a>(
&'a self,
_: &'a Caller,
address: &'a ResourceAddress,
) -> ReadsAnswer<'a, ResourceCopy> {
Box::pin(std::future::ready(Ok(self.held(address))))
}
fn watch<'a>(
&'a self,
_: &'a Caller,
_: &'a ResourceAddress,
_: &'a ResourceWake,
) -> ReadsAnswer<'a, ()> {
Box::pin(std::future::ready(Ok(())))
}
fn answer_read(
self: std::sync::Arc<Self>,
_: &Caller,
correlation: u64,
_: super::ResourceReadRequest,
) -> ReadingAnswer
where
Self: 'static,
{
Box::pin(std::future::ready(
super::RemoteActionMessage::ResourceReading {
correlation,
result: Err(ActionCallError::Unavailable {
reason: "these copies answer no read asked over the API".into(),
}),
},
))
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ResourceAsk {
pub address: ResourceAddress,
pub joined: bool,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ResourceReadings {
pub revision: String,
pub records: Vec<(String, Option<ResourceCopy>)>,
}
pub fn unanswered(correlation: u64) -> super::Pending<super::RemoteActionMessage> {
super::Pending::ready(super::RemoteActionMessage::ResourceReading {
correlation,
result: Err(ActionCallError::Unavailable {
reason: RESOURCE_READS_UNAVAILABLE.into(),
}),
})
}
impl ResourceReadings {
#[must_use]
pub fn documents(self) -> serde_json::Value {
let records: Vec<serde_json::Value> = self
.records
.into_iter()
.map(|(record, copy)| match copy {
None => serde_json::json!({"record": record, "arriving": true}),
Some(ResourceCopy::Absent) => serde_json::json!({"record": record, "absent": true}),
Some(ResourceCopy::Document(bytes)) => {
serde_json::json!({"record": record, "document": hex::encode(bytes)})
}
Some(ResourceCopy::Read(value) | ResourceCopy::Reading { value, .. }) => {
serde_json::json!({"record": record, "value": value})
}
})
.collect();
serde_json::json!({"revision": self.revision, "records": records})
}
pub fn readable(self) -> Result<serde_json::Value, String> {
let mut records = Vec::with_capacity(self.records.len());
for (record, copy) in self.records {
records.push(match copy {
None => serde_json::json!({"record": record, "arriving": true}),
Some(ResourceCopy::Absent) => serde_json::json!({"record": record, "absent": true}),
Some(copy) => serde_json::json!({"record": record, "value": copy.readable()?}),
});
}
Ok(serde_json::json!({"revision": self.revision, "records": records}))
}
}
impl ResourceCopy {
pub fn readable(&self) -> Result<serde_json::Value, String> {
match self {
Self::Absent => Ok(serde_json::Value::Null),
Self::Read(value) | Self::Reading { value, .. } => Ok(value.clone()),
Self::Document(bytes) => {
#[cfg(feature = "document-read")]
{
let doc =
automerge::Automerge::load(bytes).map_err(|error| error.to_string())?;
let mut value = tilo_automerge::json::read_document(&doc)
.map_err(|error| error.to_string())?;
name_variant_fields(&mut value);
Ok(value)
}
#[cfg(not(feature = "document-read"))]
{
let _ = bytes;
Err("this build reads no record as a document".to_owned())
}
}
}
}
}
#[cfg(feature = "document-read")]
fn name_variant_fields(value: &mut serde_json::Value) {
match value {
serde_json::Value::Array(items) => items.iter_mut().for_each(name_variant_fields),
serde_json::Value::Object(map) => {
map.values_mut().for_each(name_variant_fields);
let Some(variant) = map.get("$variant").and_then(serde_json::Value::as_str) else {
return;
};
let prefix = format!(
"$field/{}/",
variant.replace('%', "%25").replace('/', "%2F")
);
let stored: Vec<String> = map
.keys()
.filter(|key| key.starts_with(&prefix))
.cloned()
.collect();
for key in stored {
if let Some(field) = map.remove(&key) {
let name = key
.get(prefix.len()..)
.unwrap_or_default()
.replace("%2F", "/")
.replace("%25", "%");
map.insert(name, field);
}
}
}
_ => {}
}
}
#[derive(Clone)]
pub struct ResourceWake(std::sync::Arc<std::sync::Mutex<Option<super::Completer<()>>>>);
impl ResourceWake {
#[must_use]
pub fn new() -> (Self, super::Pending<()>) {
let (woken, waiting) = super::pending();
(
Self(std::sync::Arc::new(std::sync::Mutex::new(Some(woken)))),
waiting,
)
}
pub fn wake(&self) {
if let Some(woken) = self.0.lock().ok().and_then(|mut woken| woken.take()) {
woken.complete(());
}
}
#[must_use]
pub fn waiting(&self) -> bool {
self.0
.lock()
.is_ok_and(|woken| woken.as_ref().is_some_and(|woken| !woken.is_abandoned()))
}
}
pub async fn answered(
reads: std::sync::Arc<dyn ResourceReads>,
caller: &Caller,
read: super::ResourceReadRequest,
) -> Result<serde_json::Value, ActionCallError> {
match reads.answer_read(caller, 0, read).await {
super::RemoteActionMessage::ResourceReading { result, .. } => {
serde_json::from_str(&result?).map_err(|error| ActionCallError::Unavailable {
reason: format!("the reading does not read: {error}"),
})
}
_ => Err(ActionCallError::Unanswered),
}
}