use std::sync::Mutex;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use uuid::timestamp::{Timestamp, context::ContextV7};
pub type Doc = automerge::AutoCommit;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum ExecutionLocus {
#[default]
ClientLocal,
ServerPreferred,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum OperationKind {
#[default]
Document,
Effect,
View,
}
impl OperationKind {
pub const fn as_str(self) -> &'static str {
match self {
Self::Document => "document",
Self::Effect => "effect",
Self::View => "view",
}
}
#[must_use]
pub fn reports_a_change(self, need: crate::ActionKind) -> bool {
matches!(self, Self::Document | Self::View) || need == crate::ActionKind::Read
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ActionId(pub Uuid);
static MINTED: Mutex<ContextV7> = Mutex::new(ContextV7::new());
impl ActionId {
pub fn new() -> Self {
let now_ms = tilo_clock::unix_now_ms();
let seconds = now_ms / 1_000;
let nanos = u32::try_from(now_ms % 1_000).map_or(0, |rest| rest.saturating_mul(1_000_000));
Self(Uuid::new_v7(Timestamp::from_unix(&MINTED, seconds, nanos)))
}
pub fn actor_bytes(&self) -> [u8; 16] {
*self.0.as_bytes()
}
}
impl Default for ActionId {
fn default() -> Self {
Self::new()
}
}
#[derive(Debug, thiserror::Error)]
pub enum ActionError {
#[error("automerge error: {0}")]
Automerge(#[from] automerge::AutomergeError),
#[error("no decoder registered for action type `{0}`")]
UnknownType(String),
#[error("failed to decode action `{type_id}`: {source}")]
Decode {
type_id: String,
source: serde_json::Error,
},
#[error("failed to encode action: {0}")]
Encode(serde_json::Error),
#[error("{0}")]
Refused(String),
#[error("{message}")]
Unavailable { code: String, message: String },
#[error("{0}")]
Declined(Declined),
}
pub const MAX_TEXT_BYTES: usize = 8 * 1024 * 1024;
pub const RECALL_SUMMARY_BYTES: usize = 4 * 1024;
pub mod codes {
pub const NOTE_ALREADY_IMPORTED: &str = "note_already_imported";
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Declined {
Changed,
TooLong,
}
impl Declined {
#[must_use]
pub fn words(self) -> (String, Vec<(String, String)>) {
match self {
Self::Changed => ("rich-text-changed-while-typing".to_owned(), Vec::new()),
Self::TooLong => (
"rich-text-too-long".to_owned(),
vec![(
"limit".to_owned(),
format!("{} MB", MAX_TEXT_BYTES / (1024 * 1024)),
)],
),
}
}
}
impl std::fmt::Display for Declined {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
Self::Changed => "the text changed since it was read",
Self::TooLong => "the text is longer than one text may hold",
})
}
}
pub type ActionStep = (Box<dyn Action>, Vec<u8>);
pub trait Action: std::fmt::Debug {
fn apply(&self, doc: &mut Doc) -> Result<(), ActionError>;
fn locus(&self) -> ExecutionLocus {
ExecutionLocus::ClientLocal
}
fn risk(&self) -> crate::contract::RiskLevel {
crate::contract::RiskLevel::Low
}
fn inverse_before(&self, doc: &Doc) -> Option<Self>
where
Self: Sized,
{
let _ = doc;
None
}
fn inverse_encoded(&self, doc: &Doc) -> Option<EncodedAction> {
let _ = doc;
None
}
fn change_kind(&self) -> crate::context::ChangeKind {
crate::context::ChangeKind::Content
}
fn action_kind(&self) -> crate::ActionKind {
crate::ActionKind::Undoable
}
fn incoming_message(&self) -> bool {
false
}
fn readers(&self) -> Option<Vec<crate::MemberId>> {
None
}
fn irreversible(&self) -> bool {
false
}
fn compensates(&self) -> bool {
false
}
fn describe(&self, doc: &Doc) -> Option<crate::Described> {
let _ = doc;
None
}
fn made(&self, doc: &Doc) -> Option<crate::entry::ActionItem> {
let _ = doc;
None
}
fn steps(&self, doc: &Doc) -> Option<Vec<ActionStep>> {
let _ = doc;
None
}
}
#[must_use]
pub fn undo_takes_back(
kind: crate::ActionKind,
change: crate::ChangeKind,
irreversible: bool,
) -> bool {
kind == crate::ActionKind::Undoable && change.is_step() && !irreversible
}
#[must_use]
pub fn asks_first(
risk: crate::RiskLevel,
kind: crate::ActionKind,
change: crate::ChangeKind,
irreversible: bool,
) -> bool {
risk.requires_confirmation_when(undo_takes_back(kind, change, irreversible))
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct EncodedAction {
pub type_id: String,
#[serde(with = "payload_text")]
pub payload: Vec<u8>,
}
mod payload_text {
use serde::de::Visitor;
use serde::ser::Error as _;
use serde::{Deserializer, Serializer};
pub(super) fn serialize<S: Serializer>(payload: &[u8], into: S) -> Result<S::Ok, S::Error> {
if into.is_human_readable() {
into.serialize_str(std::str::from_utf8(payload).map_err(S::Error::custom)?)
} else {
into.serialize_bytes(payload)
}
}
pub(super) fn deserialize<'de, D: Deserializer<'de>>(from: D) -> Result<Vec<u8>, D::Error> {
struct Payload;
impl Visitor<'_> for Payload {
type Value = Vec<u8>;
fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str("an action's payload, as text or bytes")
}
fn visit_str<E: serde::de::Error>(self, text: &str) -> Result<Vec<u8>, E> {
Ok(text.as_bytes().to_vec())
}
fn visit_string<E: serde::de::Error>(self, text: String) -> Result<Vec<u8>, E> {
Ok(text.into_bytes())
}
fn visit_bytes<E: serde::de::Error>(self, bytes: &[u8]) -> Result<Vec<u8>, E> {
Ok(bytes.to_vec())
}
fn visit_byte_buf<E: serde::de::Error>(self, bytes: Vec<u8>) -> Result<Vec<u8>, E> {
Ok(bytes)
}
}
if from.is_human_readable() {
from.deserialize_string(Payload)
} else {
from.deserialize_byte_buf(Payload)
}
}
}
impl EncodedAction {
pub fn encode<A>(type_id: impl Into<String>, action: &A) -> Result<Self, ActionError>
where
A: Action + Serialize,
{
Self::encoded(type_id.into(), serde_json::to_vec(action))
}
#[inline(never)]
fn encoded(
type_id: String,
payload: Result<Vec<u8>, serde_json::Error>,
) -> Result<Self, ActionError> {
Ok(Self::written(
type_id,
payload.map_err(ActionError::Encode)?,
))
}
#[must_use]
pub fn written(type_id: String, payload: Vec<u8>) -> Self {
let payload = if crate::group_form::is_group(&type_id) {
crate::group_form::compact(&payload).unwrap_or(payload)
} else {
payload
};
Self { type_id, payload }
}
pub fn encode_operation<T>(type_id: impl Into<String>, payload: &T) -> Result<Self, ActionError>
where
T: Serialize,
{
Ok(Self {
type_id: type_id.into(),
payload: serde_json::to_vec(payload).map_err(ActionError::Encode)?,
})
}
}
#[cfg(test)]
mod action_id_tests {
use super::ActionId;
use tilo_clock::time::{Duration, UNIX_EPOCH};
#[test]
fn an_id_is_minted_at_the_time_the_process_holds() {
let at = UNIX_EPOCH + Duration::from_millis(1_700_000_000_123);
let (first, second) =
tilo_clock::testing::with_wall(at, || (ActionId::new(), ActionId::new()));
for id in [first, second] {
let (seconds, nanos) = id.0.get_timestamp().expect("a version 7 id").to_unix();
assert_eq!(
seconds * 1_000 + u64::from(nanos) / 1_000_000,
1_700_000_000_123,
"the id carries the time the process holds"
);
}
assert!(first.0 < second.0, "an id sorts after the one before it");
}
}
#[cfg(test)]
mod operation_kind_tests {
use super::OperationKind;
use crate::ActionKind;
#[test]
fn only_a_change_or_a_read_is_reported() {
for (kind, need, reported) in [
(OperationKind::Document, ActionKind::Undoable, true),
(OperationKind::Document, ActionKind::Read, true),
(OperationKind::View, ActionKind::Read, true),
(OperationKind::View, ActionKind::Outside, true),
(OperationKind::Effect, ActionKind::Outside, false),
(OperationKind::Effect, ActionKind::Undoable, false),
(OperationKind::Effect, ActionKind::Read, true),
] {
assert_eq!(kind.reports_a_change(need), reported, "{kind:?}/{need:?}");
}
}
#[test]
fn operation_kind_accepts_only_the_canonical_spelling() {
for (kind, canonical, lower) in [
(OperationKind::Document, "Document", "document"),
(OperationKind::Effect, "Effect", "effect"),
(OperationKind::View, "View", "view"),
] {
assert_eq!(serde_json::to_value(kind).unwrap(), canonical);
assert_eq!(
serde_json::from_value::<OperationKind>(serde_json::json!(canonical)).unwrap(),
kind
);
assert!(serde_json::from_value::<OperationKind>(serde_json::json!(lower)).is_err());
}
assert!(serde_json::from_value::<OperationKind>(serde_json::json!("EFFECT")).is_err());
}
}