use automerge::transaction::{CommitOptions, Transactable};
use automerge::{ObjId, ROOT, ReadDoc, ScalarValue, Value};
use tilo_automerge::ApplyIncoming;
use tilo_sort::CompactSort as _;
use crate::model::{Doc, ModelError};
use crate::resource::Resource;
pub const VERSION_KEY: &str = "tilo:version";
fn version_of(value: &Value<'_>) -> Option<u32> {
let Value::Scalar(scalar) = value else {
return None;
};
match scalar.as_ref() {
ScalarValue::Uint(version) => Some(u32::try_from(*version).unwrap_or(u32::MAX)),
ScalarValue::Int(version) => Some(u32::try_from(*version).unwrap_or(u32::MAX)),
_ => None,
}
}
#[must_use]
pub fn stored_version(doc: &Doc) -> u32 {
doc.get(&ROOT, VERSION_KEY)
.ok()
.flatten()
.and_then(|(value, _)| version_of(&value))
.unwrap_or(1)
}
pub fn write_version(doc: &mut Doc, version: u32) -> Result<(), ModelError> {
write_version_at(doc, &ROOT, version)
}
pub fn write_version_at(doc: &mut Doc, at: &ObjId, version: u32) -> Result<(), ModelError> {
if version > 1 || doc.get(at, VERSION_KEY)?.is_some() {
doc.put(at, VERSION_KEY, ScalarValue::Uint(u64::from(version)))?;
}
Ok(())
}
pub fn step(
scope: crate::founding::Scope<'_>,
version: u32,
before: &Doc,
) -> Result<automerge::Change, automerge::AutomergeError> {
let crate::founding::Scope {
workspace,
kind,
id,
} = scope;
let mut doc = before.clone().with_actor(crate::genesis::actor(
id,
kind,
&format!("version {version} in {workspace}"),
));
doc.put(ROOT, VERSION_KEY, ScalarValue::Uint(u64::from(version)))?;
let context = tilo_actions::ActionContext {
change: tilo_actions::ChangeKind::Housekeeping,
..tilo_actions::ActionContext::for_resource(id, kind, kind).with_described(
tilo_actions::Described::new(tilo_actions::Did::history(
tilo_actions::HistoryOp::Migrate {
to: version,
rewrite: false,
},
0,
None,
)),
)
};
let mut options = CommitOptions::default().with_time(0);
if let Some(message) = context.change_message() {
options = options.with_message(message);
}
let hash = doc
.commit_with(options)
.ok_or(automerge::AutomergeError::Fail)?;
doc.get_change_by_hash(&hash)
.ok_or(automerge::AutomergeError::MissingHash(hash))
}
pub fn check_version<R: Resource>(doc: &Doc) -> Result<(), ModelError> {
let (stored, version) = (stored_version(doc), R::VERSION);
if stored < version {
return Err(ModelError::invalid(format!(
"stored at version {stored}; it is brought up to version {version} when it opens"
)));
}
Ok(())
}
#[must_use]
pub fn needs_migrate<R: Resource>(doc: &Doc) -> bool {
stored_version(doc) < R::VERSION
}
pub fn rewrite(
(scope, version): (crate::founding::Scope<'_>, u32),
from: u32,
migration: &dyn Fn(&mut Doc, u32) -> Result<(), ModelError>,
doc: &mut Doc,
) -> Result<bool, ModelError> {
let crate::founding::Scope {
workspace,
kind,
id,
} = scope;
let mut heads = doc.get_heads();
heads.compact_sort();
let mut on: Vec<String> = heads.iter().map(ToString::to_string).collect();
on.sort();
let actor = crate::genesis::actor(
id,
kind,
&format!(
"rewrite to version {version} on {} in {workspace}",
on.join(",")
),
);
let mut migrated = doc.fork_at(&heads)?.with_actor(actor);
if from < version {
migration(&mut migrated, from)?;
}
if stored_version(&migrated) < version {
migrated.put(ROOT, VERSION_KEY, ScalarValue::Uint(u64::from(version)))?;
}
if migrated.pending_ops() == 0 {
return Ok(false);
}
let context = tilo_actions::ActionContext {
change: tilo_actions::ChangeKind::Housekeeping,
..tilo_actions::ActionContext::for_resource(id, kind, kind).with_described(
tilo_actions::Described::new(tilo_actions::Did::history(
tilo_actions::HistoryOp::Migrate {
to: version,
rewrite: true,
},
0,
None,
)),
)
};
let mut options = CommitOptions::default().with_time(0);
if let Some(message) = context.change_message() {
options = options.with_message(message);
}
migrated.commit_with(options);
let changes = migrated.get_changes(&heads);
doc.apply_incoming(changes)?;
Ok(true)
}
pub fn copy_into(from: &Doc, to: &mut Doc) -> Result<(), ModelError> {
for key in from.keys(&ROOT).collect::<Vec<_>>() {
if key.starts_with("tilo:") && key != VERSION_KEY {
continue;
}
if let Some((value, obj)) = from.get(&ROOT, key.as_str())? {
copy_value(from, &value, &obj, to, &ROOT, Place::Key(&key))?;
}
}
Ok(())
}
enum Place<'a> {
Key(&'a str),
Insert(usize),
}
fn copy_value(
from: &Doc,
value: &Value<'_>,
obj: &ObjId,
to: &mut Doc,
into: &ObjId,
place: Place<'_>,
) -> Result<(), ModelError> {
use automerge::ObjType;
let Value::Object(kind) = value else {
let Value::Scalar(scalar) = value else {
return Ok(());
};
let scalar = scalar.as_ref().clone();
match place {
Place::Key(key) => to.put(into, key, scalar)?,
Place::Insert(index) => to.insert(into, index, scalar)?,
}
return Ok(());
};
let kind = match kind {
ObjType::Table => ObjType::Map,
other => *other,
};
let held = match place {
Place::Key(key) => match to.get(into, key)? {
Some((Value::Object(held), id)) if held == kind => Some(id),
_ => None,
},
Place::Insert(_) => None,
};
let target = match (held, place) {
(Some(id), _) => id,
(None, Place::Key(key)) => to.put_object(into, key, kind)?,
(None, Place::Insert(index)) => to.insert_object(into, index, kind)?,
};
match kind {
ObjType::Text => {
let text = from.text(obj)?;
let length = to.length(&target);
to.splice_text(
&target,
0,
isize::try_from(length).unwrap_or(isize::MAX),
&text,
)?;
}
ObjType::List => {
let start = to.length(&target);
for index in 0..from.length(obj) {
if let Some((item, item_obj)) = from.get(obj, index)? {
copy_value(
from,
&item,
&item_obj,
to,
&target,
Place::Insert(start.saturating_add(index)),
)?;
}
}
}
ObjType::Map | ObjType::Table => {
for key in from.keys(obj).collect::<Vec<_>>() {
if let Some((item, item_obj)) = from.get(obj, key.as_str())? {
copy_value(from, &item, &item_obj, to, &target, Place::Key(&key))?;
}
}
}
}
Ok(())
}
pub fn fixture(doc: &mut Doc, obj: &ObjId, shape: &serde_json::Value) -> Result<(), ModelError> {
let serde_json::Value::Object(fields) = shape else {
return Err(ModelError::shape("an object of fields"));
};
for (key, value) in fields {
fixture_value(doc, crate::Slot::Key(obj, key), value)?;
}
Ok(())
}
fn fixture_value(
doc: &mut Doc,
slot: crate::Slot<'_>,
value: &serde_json::Value,
) -> Result<(), ModelError> {
use automerge::ObjType;
use serde_json::Value as Json;
match value {
Json::Object(fields) if fields.len() == 1 && fields.contains_key("$text") => {
let Some(Json::String(text)) = fields.get("$text") else {
return Err(ModelError::shape("a text's string"));
};
let obj = slot.object(doc, ObjType::Text)?;
crate::TextEdit::ReplaceText { text: text.clone() }
.apply_under(doc, &obj)
.map_err(|error| ModelError::invalid(error.to_string()))
}
Json::Object(_) => {
let obj = slot.object(doc, ObjType::Map)?;
fixture(doc, &obj, value)
}
Json::Array(items) => {
let obj = slot.object(doc, ObjType::List)?;
for (index, item) in items.iter().enumerate() {
fixture_value(doc, crate::Slot::Insert(&obj, index), item)?;
}
Ok(())
}
Json::String(text) => slot.put_scalar(doc, ScalarValue::Str(text.as_str().into())),
Json::Bool(flag) => slot.put_scalar(doc, ScalarValue::Boolean(*flag)),
Json::Number(number) => slot.put_scalar(
doc,
match (number.as_i64(), number.as_u64(), number.as_f64()) {
(Some(int), _, _) => ScalarValue::Int(int),
(None, Some(uint), _) => ScalarValue::Uint(uint),
(None, None, Some(float)) => ScalarValue::F64(float),
(None, None, None) => return Err(ModelError::shape("a number")),
},
),
Json::Null => slot.put_scalar(doc, ScalarValue::Null),
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Unreadable {
pub reason: String,
pub stored: u32,
pub expected: u32,
}
impl std::fmt::Display for Unreadable {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.reason)
}
}
impl Unreadable {
#[must_use]
pub fn of<R: Resource>(doc: &Doc, error: &ModelError) -> Self {
Self {
reason: error.to_string(),
stored: stored_version(doc),
expected: R::VERSION,
}
}
}
pub fn read_checked<R: Resource>(doc: &Doc) -> Result<R::State, Unreadable> {
check_version::<R>(doc)
.and_then(|()| R::read(doc))
.map_err(|error| Unreadable::of::<R>(doc, &error))
}