use std::collections::{BTreeMap, BTreeSet};
use gitiverse_core::ids::{ActorId, RepoId};
use serde::{Deserialize, Serialize};
use crate::dag::{CobError, Dag, Lww, OpId, require_root};
pub const ISSUE_KIND: &str = "issue";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum IssueStatus {
Open,
Closed,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum IssueAction {
Open {
title: String,
body: String,
labels: Vec<String>,
},
Edit {
title: Option<String>,
body: Option<String>,
},
SetState(IssueStatus),
AddLabel(String),
RemoveLabel(String),
Comment {
body: String,
},
EditComment {
comment_id: OpId,
body: String,
},
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct IssueComment {
pub id: OpId,
pub author: ActorId,
pub body: String,
pub created_at: u64,
pub updated_at: u64,
pub lamport: u64,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct IssueState {
pub id: OpId,
pub repo_id: RepoId,
pub author: ActorId,
pub title: String,
pub body: String,
pub status: IssueStatus,
pub labels: BTreeSet<String>,
pub comments: Vec<IssueComment>,
pub created_at: u64,
pub updated_at: u64,
}
struct CommentAccum {
id: OpId,
author: ActorId,
body: Lww<String>,
created_at: u64,
updated_at: Lww<u64>,
lamport: u64,
}
struct IssueAccum {
id: OpId,
repo_id: RepoId,
author: ActorId,
title: Lww<String>,
body: Lww<String>,
status: Lww<IssueStatus>,
label_adds: BTreeMap<String, BTreeSet<OpId>>,
label_tombstones: BTreeMap<String, BTreeSet<OpId>>,
comments: BTreeMap<OpId, CommentAccum>,
created_at: u64,
updated_at: u64,
}
impl IssueState {
pub fn from_dag(dag: &Dag<IssueAction>) -> Result<Self, CobError> {
let accum: Option<IssueAccum> = dag.fold(None, |state, op_id, op, ancestors| {
match &op.payload {
IssueAction::Open {
title,
body,
labels,
} => {
if state.is_some() {
return Err(CobError::InvalidOp(
"duplicate issue Open operation".to_owned(),
));
}
if !op.parents.is_empty() {
return Err(CobError::InvalidOp(
"issue Open operation must have no parents".to_owned(),
));
}
let mut label_adds: BTreeMap<String, BTreeSet<OpId>> = BTreeMap::new();
for label in labels {
label_adds.entry(label.clone()).or_default().insert(op_id);
}
*state = Some(IssueAccum {
id: op_id,
repo_id: op.repo_id,
author: op.author,
title: Lww::new(op.lamport, op_id, title.clone()),
body: Lww::new(op.lamport, op_id, body.clone()),
status: Lww::new(op.lamport, op_id, IssueStatus::Open),
label_adds,
label_tombstones: BTreeMap::new(),
comments: BTreeMap::new(),
created_at: op.timestamp,
updated_at: op.timestamp,
});
Ok(())
}
IssueAction::Edit { title, body } => {
let acc = require_root(state, ISSUE_KIND, op_id)?;
if let Some(t) = title {
acc.title.update(op.lamport, op_id, t.clone());
}
if let Some(b) = body {
acc.body.update(op.lamport, op_id, b.clone());
}
acc.updated_at = acc.updated_at.max(op.timestamp);
Ok(())
}
IssueAction::SetState(next) => {
let acc = require_root(state, ISSUE_KIND, op_id)?;
acc.status.update(op.lamport, op_id, *next);
acc.updated_at = acc.updated_at.max(op.timestamp);
Ok(())
}
IssueAction::AddLabel(label) => {
let acc = require_root(state, ISSUE_KIND, op_id)?;
acc.label_adds
.entry(label.clone())
.or_default()
.insert(op_id);
acc.updated_at = acc.updated_at.max(op.timestamp);
Ok(())
}
IssueAction::RemoveLabel(label) => {
let acc = require_root(state, ISSUE_KIND, op_id)?;
if let Some(add_ids) = acc.label_adds.get(label) {
let observed: Vec<OpId> = add_ids
.iter()
.copied()
.filter(|add_id| ancestors.contains(add_id))
.collect();
if !observed.is_empty() {
acc.label_tombstones
.entry(label.clone())
.or_default()
.extend(observed);
}
}
acc.updated_at = acc.updated_at.max(op.timestamp);
Ok(())
}
IssueAction::Comment { body } => {
let acc = require_root(state, ISSUE_KIND, op_id)?;
acc.comments.insert(
op_id,
CommentAccum {
id: op_id,
author: op.author,
body: Lww::new(op.lamport, op_id, body.clone()),
created_at: op.timestamp,
updated_at: Lww::new(op.lamport, op_id, op.timestamp),
lamport: op.lamport,
},
);
acc.updated_at = acc.updated_at.max(op.timestamp);
Ok(())
}
IssueAction::EditComment { comment_id, body } => {
let acc = require_root(state, ISSUE_KIND, op_id)?;
let Some(comment) = acc.comments.get_mut(comment_id) else {
return Err(CobError::InvalidOp(format!(
"EditComment references unknown comment {comment_id}"
)));
};
if comment.author != op.author {
return Err(CobError::Unauthorised {
actor: op.author,
op_id,
reason: "only the comment author may edit their comment".to_owned(),
});
}
comment.body.update(op.lamport, op_id, body.clone());
comment.updated_at.update(op.lamport, op_id, op.timestamp);
acc.updated_at = acc.updated_at.max(op.timestamp);
Ok(())
}
}
})?;
let acc = accum.ok_or_else(|| CobError::InvalidOp("empty issue DAG".to_owned()))?;
let mut labels = BTreeSet::new();
for (label, add_ids) in acc.label_adds {
let tombstoned = acc.label_tombstones.get(&label);
let live = add_ids
.iter()
.any(|id| tombstoned.is_none_or(|t| !t.contains(id)));
if live {
labels.insert(label);
}
}
let mut comments: Vec<IssueComment> = acc
.comments
.into_values()
.map(|c| IssueComment {
id: c.id,
author: c.author,
body: c.body.value,
created_at: c.created_at,
updated_at: c.updated_at.value,
lamport: c.lamport,
})
.collect();
comments.sort_by_key(|c| (c.lamport, c.id));
Ok(IssueState {
id: acc.id,
repo_id: acc.repo_id,
author: acc.author,
title: acc.title.value,
body: acc.body.value,
status: acc.status.value,
labels,
comments,
created_at: acc.created_at,
updated_at: acc.updated_at,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::dag::DagOp;
use gitiverse_core::ids::RepoId;
use proptest::prelude::*;
use wire_mesh_core::adapters::NodeIdentity;
#[tokio::test]
async fn concurrent_add_wins_label_and_comment_edit_resolve_deterministically() {
let alice = NodeIdentity::generate_ed25519();
let bob = NodeIdentity::generate_es256();
let repo_id = RepoId::from_bytes([0x21; 32]);
let open = DagOp::sign_new(
repo_id,
ISSUE_KIND,
vec![],
1,
100,
IssueAction::Open {
title: "Initial bug".to_owned(),
body: "Needs fix".to_owned(),
labels: vec!["bug".to_owned()],
},
&alice,
)
.await
.unwrap();
let open_id = open.op_id().unwrap();
let bob_remove = DagOp::sign_new(
repo_id,
ISSUE_KIND,
vec![open_id],
2,
101,
IssueAction::RemoveLabel("bug".to_owned()),
&bob,
)
.await
.unwrap();
let alice_readd = DagOp::sign_new(
repo_id,
ISSUE_KIND,
vec![open_id],
2,
102,
IssueAction::AddLabel("bug".to_owned()),
&alice,
)
.await
.unwrap();
let comment = DagOp::sign_new(
repo_id,
ISSUE_KIND,
vec![open_id],
2,
103,
IssueAction::Comment {
body: "draft".to_owned(),
},
&alice,
)
.await
.unwrap();
let comment_id = comment.op_id().unwrap();
let edit_comment = DagOp::sign_new(
repo_id,
ISSUE_KIND,
vec![comment_id],
3,
104,
IssueAction::EditComment {
comment_id,
body: "final comment".to_owned(),
},
&alice,
)
.await
.unwrap();
let mut d1 = Dag::new();
for op in [
edit_comment.clone(),
bob_remove.clone(),
alice_readd.clone(),
comment.clone(),
open.clone(),
] {
d1.insert_verified(op, &alice, Some(&repo_id), Some(ISSUE_KIND))
.await
.unwrap();
}
let mut d2 = Dag::new();
for op in [open, comment, alice_readd, bob_remove, edit_comment] {
d2.insert_verified(op, &bob, Some(&repo_id), Some(ISSUE_KIND))
.await
.unwrap();
}
let s1 = IssueState::from_dag(&d1).unwrap();
let s2 = IssueState::from_dag(&d2).unwrap();
assert_eq!(s1, s2);
assert!(s1.labels.contains("bug"));
assert_eq!(s1.comments.len(), 1);
assert_eq!(s1.comments[0].body, "final comment");
}
proptest! {
#[test]
fn prop_issue_crdt_commutes_is_idempotent_and_converges(
perm in prop::collection::vec(0usize..100, 1..20),
dups in prop::collection::vec(0usize..12, 0..10),
) {
let rt = tokio::runtime::Runtime::new().unwrap();
rt.block_on(async {
let alice = NodeIdentity::from_ed25519_secret(&[1u8; 32]).unwrap();
let bob = NodeIdentity::from_ed25519_secret(&[2u8; 32]).unwrap();
let repo_id = RepoId::from_bytes([0x55; 32]);
let open = DagOp::sign_new(
repo_id,
ISSUE_KIND,
vec![],
1,
10,
IssueAction::Open {
title: "t0".to_owned(),
body: "b0".to_owned(),
labels: vec!["triage".to_owned()],
},
&alice,
).await.unwrap();
let id_open = open.op_id().unwrap();
let edit_a = DagOp::sign_new(
repo_id, ISSUE_KIND, vec![id_open], 2, 11,
IssueAction::Edit { title: Some("t-a".to_owned()), body: None }, &alice,
).await.unwrap();
let edit_b = DagOp::sign_new(
repo_id, ISSUE_KIND, vec![id_open], 2, 12,
IssueAction::Edit { title: Some("t-b".to_owned()), body: Some("b-b".to_owned()) }, &bob,
).await.unwrap();
let rm_triage = DagOp::sign_new(
repo_id, ISSUE_KIND, vec![id_open], 2, 13,
IssueAction::RemoveLabel("triage".to_owned()), &bob,
).await.unwrap();
let add_triage = DagOp::sign_new(
repo_id, ISSUE_KIND, vec![id_open], 2, 14,
IssueAction::AddLabel("triage".to_owned()), &alice,
).await.unwrap();
let add_perf = DagOp::sign_new(
repo_id, ISSUE_KIND, vec![edit_a.op_id().unwrap()], 3, 15,
IssueAction::AddLabel("perf".to_owned()), &alice,
).await.unwrap();
let close_op = DagOp::sign_new(
repo_id, ISSUE_KIND, vec![edit_b.op_id().unwrap()], 3, 16,
IssueAction::SetState(IssueStatus::Closed), &bob,
).await.unwrap();
let reopen_op = DagOp::sign_new(
repo_id, ISSUE_KIND, vec![close_op.op_id().unwrap()], 4, 17,
IssueAction::SetState(IssueStatus::Open), &alice,
).await.unwrap();
let comment_a = DagOp::sign_new(
repo_id, ISSUE_KIND, vec![id_open], 2, 18,
IssueAction::Comment { body: "first".to_owned() }, &alice,
).await.unwrap();
let comment_id = comment_a.op_id().unwrap();
let edit_comment = DagOp::sign_new(
repo_id, ISSUE_KIND, vec![comment_id], 3, 19,
IssueAction::EditComment { comment_id, body: "edited".to_owned() }, &alice,
).await.unwrap();
let all_ops = vec![
open, edit_a, edit_b, rm_triage, add_triage,
add_perf, close_op, reopen_op, comment_a, edit_comment,
];
let mut canonical_dag = Dag::new();
for op in &all_ops {
canonical_dag.insert_unchecked(op.clone()).unwrap();
}
let expected = IssueState::from_dag(&canonical_dag).unwrap();
let mut indices: Vec<usize> = (0..all_ops.len()).collect();
for (i, &swap_seed) in perm.iter().enumerate() {
let a = i % all_ops.len();
let b = swap_seed % all_ops.len();
indices.swap(a, b);
}
let mut peer_dag = Dag::new();
for idx in indices {
peer_dag.insert_unchecked(all_ops[idx].clone()).unwrap();
}
for dup in dups {
let op = &all_ops[dup % all_ops.len()];
peer_dag.insert_unchecked(op.clone()).unwrap();
}
let actual = IssueState::from_dag(&peer_dag).unwrap();
assert_eq!(actual, expected);
assert_eq!(peer_dag.len(), all_ops.len());
});
}
}
}