use std::collections::BTreeSet;
use automerge::transaction::Transactable;
use automerge::{ObjType, Prop, ROOT, ReadDoc, Value};
use crate::action::Refusal;
use crate::collection::{Id, VALUE};
use crate::model::{Doc, Model};
use crate::path::Segment;
use crate::shape::Shape;
pub const RESOURCE_UNIT: &str = tilo_actions::surface::RESOURCE_UNIT;
pub const UNIT_INDEX: &str = "_units";
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Writes {
pub item: Option<Id>,
pub fields: &'static [&'static str],
}
impl Writes {
#[must_use]
pub const fn record() -> Self {
Self {
item: None,
fields: &[],
}
}
fn allows(&self, unit: &[Segment]) -> bool {
if unit.is_empty() {
return true;
}
if unit.iter().any(
|segment| matches!(segment, Segment::Field(key) if self.fields.contains(&key.as_str())),
) {
return true;
}
unit.iter()
.any(|segment| matches!(segment, Segment::Item(id) if self.item.as_ref() == Some(id)))
}
}
#[derive(Clone, Debug, Default)]
pub(crate) struct Footprints {
fields: std::collections::BTreeSet<&'static str>,
items: std::collections::BTreeSet<Id>,
}
impl Footprints {
pub(crate) fn add(&mut self, writes: &Writes) {
self.fields.extend(writes.fields.iter().copied());
self.items.extend(writes.item.iter().cloned());
}
fn allows(&self, unit: &[Segment]) -> bool {
unit.is_empty()
|| unit.iter().any(|segment| match segment {
Segment::Field(key) => self.fields.contains(key.as_str()),
Segment::Item(id) => self.items.contains(id),
_ => false,
})
}
}
#[must_use]
pub fn has_units(shape: Shape) -> bool {
match shape {
Shape::Record(fields) => fields
.iter()
.any(|field| field.unit || has_units(field.shape)),
Shape::Collection(item) | Shape::Keyed(item) => has_units(*item),
Shape::Value | Shape::Map(_) => false,
}
}
fn unit_name(unit: &[Segment]) -> String {
if unit.is_empty() {
return RESOURCE_UNIT.to_owned();
}
unit.iter()
.map(|segment| match segment {
Segment::Field(key) | Segment::Key(key) => key.clone(),
Segment::Item(id) => id.as_str().to_owned(),
Segment::Cell { row, column } => format!("{row}:{column}"),
})
.collect::<Vec<_>>()
.join(".")
}
pub fn check<R: Model>(before: &R, after: &R, writes: &Writes) -> Result<(), Refusal> {
let mut edits: Vec<crate::Edit<()>> = Vec::new();
before.diff(after, &[], &mut edits);
check_edits(R::SHAPE, &edits, writes)
}
pub(crate) fn check_edits(
shape: Shape,
edits: &[crate::Edit<()>],
writes: &Writes,
) -> Result<(), Refusal> {
check_edits_within(shape, edits, &|unit| writes.allows(unit))
}
pub(crate) fn check_edits_of(
shape: Shape,
edits: &[crate::Edit<()>],
footprints: &Footprints,
) -> Result<(), Refusal> {
check_edits_within(shape, edits, &|unit| footprints.allows(unit))
}
fn check_edits_within(
shape: Shape,
edits: &[crate::Edit<()>],
allows: &dyn Fn(&[Segment]) -> bool,
) -> Result<(), Refusal> {
use crate::path::EditOp;
for edit in edits {
let mut path = edit.path().to_vec();
match edit.op() {
EditOp::InsertItem { id: Some(id), .. }
| EditOp::UpsertItem { id: Some(id), .. }
| EditOp::RemoveItem { id }
| EditOp::MoveTo { id, .. } => path.push(Segment::Item(id.clone())),
_ => {}
}
let unit = shape.unit_of(&path);
if !allows(&unit) && !is_outbox(shape, &unit) {
return Err(Refusal::new(format!(
"the action wrote `{}`, outside the units it declares; add \
`#[action(writes = field)]`",
unit_name(&unit)
)));
}
}
Ok(())
}
fn is_outbox(shape: Shape, unit: &[Segment]) -> bool {
let [Segment::Field(key)] = unit else {
return false;
};
shape.fields().iter().any(|field| {
field.key == key && tilo_actions::surface::FieldType::from_rust_text(field.ty).is_outbox()
})
}
#[must_use]
pub fn declared(shape: Shape, item: Option<&str>, fields: &[&str]) -> Vec<String> {
let mut units = vec![RESOURCE_UNIT.to_owned()];
let field_of = |key: &str| shape.fields().iter().find(|field| field.key == key);
if let Some(collection) = item.and_then(field_of)
&& collection.unit
&& matches!(collection.shape, Shape::Collection(_) | Shape::Keyed(_))
{
units.push(format!("{}.*", collection.key));
}
for key in fields {
let Some(field) = field_of(key) else { continue };
let unit = if matches!(field.shape, Shape::Collection(_) | Shape::Keyed(_)) {
format!("{}.*", field.key)
} else {
field.key.to_owned()
};
if !units.contains(&unit) {
units.push(unit);
}
}
units
}
#[must_use]
pub fn patterns(shape: Shape) -> Vec<String> {
fn walk(shape: Shape, prefix: &str, out: &mut Vec<String>) {
match shape {
Shape::Record(fields) => {
for field in fields {
let path = format!("{prefix}{}", field.key);
match field.shape {
Shape::Collection(item) | Shape::Keyed(item) if field.unit => {
out.push(format!("{path}/*"));
let value = if matches!(field.shape, Shape::Collection(_)) {
format!("{path}/*/{VALUE}/")
} else {
format!("{path}/*/")
};
walk(*item, &value, out);
}
_ if field.unit => {
out.push(path.clone());
walk(field.shape, &format!("{path}/"), out);
}
_ => walk(field.shape, &format!("{path}/"), out),
}
}
}
Shape::Collection(item) => walk(*item, &format!("{prefix}*/{VALUE}/"), out),
Shape::Keyed(item) => walk(*item, &format!("{prefix}*/"), out),
Shape::Value | Shape::Map(_) => {}
}
}
let mut out = Vec::new();
walk(shape, "", &mut out);
out
}
pub fn index(doc: &mut Doc, shape: Shape) -> Result<(), automerge::AutomergeError> {
if !has_units(shape) || doc.get(&ROOT, UNIT_INDEX)?.is_some() {
return Ok(());
}
let list = doc.put_object(&ROOT, UNIT_INDEX, ObjType::List)?;
for (at, pattern) in patterns(shape).into_iter().enumerate() {
doc.insert(&list, at, pattern)?;
}
Ok(())
}
fn indexed(doc: &Doc) -> Vec<Vec<String>> {
let Ok(Some((Value::Object(ObjType::List), list))) = doc.get(&ROOT, UNIT_INDEX) else {
return Vec::new();
};
(0..doc.length(&list))
.filter_map(|at| match doc.get(&list, at).ok()?? {
(Value::Scalar(scalar), _) => scalar.as_str().map(str::to_owned),
_ => None,
})
.map(|pattern| pattern.split('/').map(str::to_owned).collect())
.collect()
}
#[must_use]
pub fn units_of(doc: &Doc, patches: &[automerge::Patch]) -> BTreeSet<String> {
use automerge::PatchAction;
let patterns = indexed(doc);
let mut units = BTreeSet::new();
for patch in patches {
let mut keys: Vec<String> = patch
.path
.iter()
.map(|(_, prop)| match prop {
Prop::Map(key) => key.clone(),
Prop::Seq(index) => index.to_string(),
})
.collect();
match &patch.action {
PatchAction::PutMap { key, .. } | PatchAction::DeleteMap { key } => {
keys.push(key.clone());
}
PatchAction::Increment { prop, .. } | PatchAction::Conflict { prop } => {
keys.push(match prop {
Prop::Map(key) => key.clone(),
Prop::Seq(index) => index.to_string(),
});
}
_ => {}
}
let unit = patterns
.iter()
.filter(|pattern| {
pattern.len() <= keys.len()
&& pattern
.iter()
.zip(&keys)
.all(|(want, key)| want == "*" || want == key)
})
.max_by_key(|pattern| pattern.len())
.map_or_else(
|| RESOURCE_UNIT.to_owned(),
|pattern| keys.get(..pattern.len()).unwrap_or_default().join("/"),
);
units.insert(unit);
}
units
}