1use std::collections::{BTreeMap, BTreeSet};
2
3use gitiverse_core::ids::{ActorId, RepoId};
4use serde::{Deserialize, Serialize};
5
6use crate::dag::{CobError, Dag, Lww, OpId, require_root};
7
8pub const ISSUE_KIND: &str = "issue";
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
12pub enum IssueStatus {
13 Open,
14 Closed,
15}
16
17#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
19pub enum IssueAction {
20 Open {
21 title: String,
22 body: String,
23 labels: Vec<String>,
24 },
25 Edit {
26 title: Option<String>,
27 body: Option<String>,
28 },
29 SetState(IssueStatus),
30 AddLabel(String),
31 RemoveLabel(String),
32 Comment {
33 body: String,
34 },
35 EditComment {
36 comment_id: OpId,
37 body: String,
38 },
39}
40
41#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
43pub struct IssueComment {
44 pub id: OpId,
45 pub author: ActorId,
46 pub body: String,
47 pub created_at: u64,
48 pub updated_at: u64,
49 pub lamport: u64,
50}
51
52#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
54pub struct IssueState {
55 pub id: OpId,
56 pub repo_id: RepoId,
57 pub author: ActorId,
58 pub title: String,
59 pub body: String,
60 pub status: IssueStatus,
61 pub labels: BTreeSet<String>,
62 pub comments: Vec<IssueComment>,
63 pub created_at: u64,
64 pub updated_at: u64,
65}
66
67struct CommentAccum {
68 id: OpId,
69 author: ActorId,
70 body: Lww<String>,
71 created_at: u64,
72 updated_at: Lww<u64>,
73 lamport: u64,
74}
75
76struct IssueAccum {
77 id: OpId,
78 repo_id: RepoId,
79 author: ActorId,
80 title: Lww<String>,
81 body: Lww<String>,
82 status: Lww<IssueStatus>,
83 label_adds: BTreeMap<String, BTreeSet<OpId>>,
84 label_tombstones: BTreeMap<String, BTreeSet<OpId>>,
85 comments: BTreeMap<OpId, CommentAccum>,
86 created_at: u64,
87 updated_at: u64,
88}
89
90impl IssueState {
91 pub fn from_dag(dag: &Dag<IssueAction>) -> Result<Self, CobError> {
93 let accum: Option<IssueAccum> = dag.fold(None, |state, op_id, op, ancestors| {
94 match &op.payload {
95 IssueAction::Open {
96 title,
97 body,
98 labels,
99 } => {
100 if state.is_some() {
101 return Err(CobError::InvalidOp(
102 "duplicate issue Open operation".to_owned(),
103 ));
104 }
105 if !op.parents.is_empty() {
106 return Err(CobError::InvalidOp(
107 "issue Open operation must have no parents".to_owned(),
108 ));
109 }
110 let mut label_adds: BTreeMap<String, BTreeSet<OpId>> = BTreeMap::new();
111 for label in labels {
112 label_adds.entry(label.clone()).or_default().insert(op_id);
113 }
114 *state = Some(IssueAccum {
115 id: op_id,
116 repo_id: op.repo_id,
117 author: op.author,
118 title: Lww::new(op.lamport, op_id, title.clone()),
119 body: Lww::new(op.lamport, op_id, body.clone()),
120 status: Lww::new(op.lamport, op_id, IssueStatus::Open),
121 label_adds,
122 label_tombstones: BTreeMap::new(),
123 comments: BTreeMap::new(),
124 created_at: op.timestamp,
125 updated_at: op.timestamp,
126 });
127 Ok(())
128 }
129 IssueAction::Edit { title, body } => {
130 let acc = require_root(state, ISSUE_KIND, op_id)?;
131 if let Some(t) = title {
132 acc.title.update(op.lamport, op_id, t.clone());
133 }
134 if let Some(b) = body {
135 acc.body.update(op.lamport, op_id, b.clone());
136 }
137 acc.updated_at = acc.updated_at.max(op.timestamp);
138 Ok(())
139 }
140 IssueAction::SetState(next) => {
141 let acc = require_root(state, ISSUE_KIND, op_id)?;
142 acc.status.update(op.lamport, op_id, *next);
143 acc.updated_at = acc.updated_at.max(op.timestamp);
144 Ok(())
145 }
146 IssueAction::AddLabel(label) => {
147 let acc = require_root(state, ISSUE_KIND, op_id)?;
148 acc.label_adds
149 .entry(label.clone())
150 .or_default()
151 .insert(op_id);
152 acc.updated_at = acc.updated_at.max(op.timestamp);
153 Ok(())
154 }
155 IssueAction::RemoveLabel(label) => {
156 let acc = require_root(state, ISSUE_KIND, op_id)?;
157 if let Some(add_ids) = acc.label_adds.get(label) {
159 let observed: Vec<OpId> = add_ids
160 .iter()
161 .copied()
162 .filter(|add_id| ancestors.contains(add_id))
163 .collect();
164 if !observed.is_empty() {
165 acc.label_tombstones
166 .entry(label.clone())
167 .or_default()
168 .extend(observed);
169 }
170 }
171 acc.updated_at = acc.updated_at.max(op.timestamp);
172 Ok(())
173 }
174 IssueAction::Comment { body } => {
175 let acc = require_root(state, ISSUE_KIND, op_id)?;
176 acc.comments.insert(
177 op_id,
178 CommentAccum {
179 id: op_id,
180 author: op.author,
181 body: Lww::new(op.lamport, op_id, body.clone()),
182 created_at: op.timestamp,
183 updated_at: Lww::new(op.lamport, op_id, op.timestamp),
184 lamport: op.lamport,
185 },
186 );
187 acc.updated_at = acc.updated_at.max(op.timestamp);
188 Ok(())
189 }
190 IssueAction::EditComment { comment_id, body } => {
191 let acc = require_root(state, ISSUE_KIND, op_id)?;
192 let Some(comment) = acc.comments.get_mut(comment_id) else {
193 return Err(CobError::InvalidOp(format!(
194 "EditComment references unknown comment {comment_id}"
195 )));
196 };
197 if comment.author != op.author {
198 return Err(CobError::Unauthorised {
199 actor: op.author,
200 op_id,
201 reason: "only the comment author may edit their comment".to_owned(),
202 });
203 }
204 comment.body.update(op.lamport, op_id, body.clone());
205 comment.updated_at.update(op.lamport, op_id, op.timestamp);
206 acc.updated_at = acc.updated_at.max(op.timestamp);
207 Ok(())
208 }
209 }
210 })?;
211
212 let acc = accum.ok_or_else(|| CobError::InvalidOp("empty issue DAG".to_owned()))?;
213 let mut labels = BTreeSet::new();
214 for (label, add_ids) in acc.label_adds {
215 let tombstoned = acc.label_tombstones.get(&label);
216 let live = add_ids
217 .iter()
218 .any(|id| tombstoned.is_none_or(|t| !t.contains(id)));
219 if live {
220 labels.insert(label);
221 }
222 }
223
224 let mut comments: Vec<IssueComment> = acc
225 .comments
226 .into_values()
227 .map(|c| IssueComment {
228 id: c.id,
229 author: c.author,
230 body: c.body.value,
231 created_at: c.created_at,
232 updated_at: c.updated_at.value,
233 lamport: c.lamport,
234 })
235 .collect();
236 comments.sort_by_key(|c| (c.lamport, c.id));
237
238 Ok(IssueState {
239 id: acc.id,
240 repo_id: acc.repo_id,
241 author: acc.author,
242 title: acc.title.value,
243 body: acc.body.value,
244 status: acc.status.value,
245 labels,
246 comments,
247 created_at: acc.created_at,
248 updated_at: acc.updated_at,
249 })
250 }
251}
252
253#[cfg(test)]
254mod tests {
255 use super::*;
256 use crate::dag::DagOp;
257 use gitiverse_core::ids::RepoId;
258 use proptest::prelude::*;
259 use wire_mesh_core::adapters::NodeIdentity;
260
261 #[tokio::test]
262 async fn concurrent_add_wins_label_and_comment_edit_resolve_deterministically() {
263 let alice = NodeIdentity::generate_ed25519();
264 let bob = NodeIdentity::generate_es256();
265 let repo_id = RepoId::from_bytes([0x21; 32]);
266
267 let open = DagOp::sign_new(
268 repo_id,
269 ISSUE_KIND,
270 vec![],
271 1,
272 100,
273 IssueAction::Open {
274 title: "Initial bug".to_owned(),
275 body: "Needs fix".to_owned(),
276 labels: vec!["bug".to_owned()],
277 },
278 &alice,
279 )
280 .await
281 .unwrap();
282 let open_id = open.op_id().unwrap();
283
284 let bob_remove = DagOp::sign_new(
286 repo_id,
287 ISSUE_KIND,
288 vec![open_id],
289 2,
290 101,
291 IssueAction::RemoveLabel("bug".to_owned()),
292 &bob,
293 )
294 .await
295 .unwrap();
296 let alice_readd = DagOp::sign_new(
297 repo_id,
298 ISSUE_KIND,
299 vec![open_id],
300 2,
301 102,
302 IssueAction::AddLabel("bug".to_owned()),
303 &alice,
304 )
305 .await
306 .unwrap();
307
308 let comment = DagOp::sign_new(
309 repo_id,
310 ISSUE_KIND,
311 vec![open_id],
312 2,
313 103,
314 IssueAction::Comment {
315 body: "draft".to_owned(),
316 },
317 &alice,
318 )
319 .await
320 .unwrap();
321 let comment_id = comment.op_id().unwrap();
322 let edit_comment = DagOp::sign_new(
323 repo_id,
324 ISSUE_KIND,
325 vec![comment_id],
326 3,
327 104,
328 IssueAction::EditComment {
329 comment_id,
330 body: "final comment".to_owned(),
331 },
332 &alice,
333 )
334 .await
335 .unwrap();
336
337 let mut d1 = Dag::new();
338 for op in [
339 edit_comment.clone(),
340 bob_remove.clone(),
341 alice_readd.clone(),
342 comment.clone(),
343 open.clone(),
344 ] {
345 d1.insert_verified(op, &alice, Some(&repo_id), Some(ISSUE_KIND))
346 .await
347 .unwrap();
348 }
349 let mut d2 = Dag::new();
350 for op in [open, comment, alice_readd, bob_remove, edit_comment] {
351 d2.insert_verified(op, &bob, Some(&repo_id), Some(ISSUE_KIND))
352 .await
353 .unwrap();
354 }
355
356 let s1 = IssueState::from_dag(&d1).unwrap();
357 let s2 = IssueState::from_dag(&d2).unwrap();
358 assert_eq!(s1, s2);
359 assert!(s1.labels.contains("bug"));
360 assert_eq!(s1.comments.len(), 1);
361 assert_eq!(s1.comments[0].body, "final comment");
362 }
363
364 proptest! {
365 #[test]
366 fn prop_issue_crdt_commutes_is_idempotent_and_converges(
367 perm in prop::collection::vec(0usize..100, 1..20),
368 dups in prop::collection::vec(0usize..12, 0..10),
369 ) {
370 let rt = tokio::runtime::Runtime::new().unwrap();
371 rt.block_on(async {
372 let alice = NodeIdentity::from_ed25519_secret(&[1u8; 32]).unwrap();
373 let bob = NodeIdentity::from_ed25519_secret(&[2u8; 32]).unwrap();
374 let repo_id = RepoId::from_bytes([0x55; 32]);
375
376 let open = DagOp::sign_new(
377 repo_id,
378 ISSUE_KIND,
379 vec![],
380 1,
381 10,
382 IssueAction::Open {
383 title: "t0".to_owned(),
384 body: "b0".to_owned(),
385 labels: vec!["triage".to_owned()],
386 },
387 &alice,
388 ).await.unwrap();
389 let id_open = open.op_id().unwrap();
390
391 let edit_a = DagOp::sign_new(
392 repo_id, ISSUE_KIND, vec![id_open], 2, 11,
393 IssueAction::Edit { title: Some("t-a".to_owned()), body: None }, &alice,
394 ).await.unwrap();
395 let edit_b = DagOp::sign_new(
396 repo_id, ISSUE_KIND, vec![id_open], 2, 12,
397 IssueAction::Edit { title: Some("t-b".to_owned()), body: Some("b-b".to_owned()) }, &bob,
398 ).await.unwrap();
399 let rm_triage = DagOp::sign_new(
400 repo_id, ISSUE_KIND, vec![id_open], 2, 13,
401 IssueAction::RemoveLabel("triage".to_owned()), &bob,
402 ).await.unwrap();
403 let add_triage = DagOp::sign_new(
404 repo_id, ISSUE_KIND, vec![id_open], 2, 14,
405 IssueAction::AddLabel("triage".to_owned()), &alice,
406 ).await.unwrap();
407 let add_perf = DagOp::sign_new(
408 repo_id, ISSUE_KIND, vec![edit_a.op_id().unwrap()], 3, 15,
409 IssueAction::AddLabel("perf".to_owned()), &alice,
410 ).await.unwrap();
411 let close_op = DagOp::sign_new(
412 repo_id, ISSUE_KIND, vec![edit_b.op_id().unwrap()], 3, 16,
413 IssueAction::SetState(IssueStatus::Closed), &bob,
414 ).await.unwrap();
415 let reopen_op = DagOp::sign_new(
416 repo_id, ISSUE_KIND, vec![close_op.op_id().unwrap()], 4, 17,
417 IssueAction::SetState(IssueStatus::Open), &alice,
418 ).await.unwrap();
419 let comment_a = DagOp::sign_new(
420 repo_id, ISSUE_KIND, vec![id_open], 2, 18,
421 IssueAction::Comment { body: "first".to_owned() }, &alice,
422 ).await.unwrap();
423 let comment_id = comment_a.op_id().unwrap();
424 let edit_comment = DagOp::sign_new(
425 repo_id, ISSUE_KIND, vec![comment_id], 3, 19,
426 IssueAction::EditComment { comment_id, body: "edited".to_owned() }, &alice,
427 ).await.unwrap();
428
429 let all_ops = vec![
430 open, edit_a, edit_b, rm_triage, add_triage,
431 add_perf, close_op, reopen_op, comment_a, edit_comment,
432 ];
433
434 let mut canonical_dag = Dag::new();
435 for op in &all_ops {
436 canonical_dag.insert_unchecked(op.clone()).unwrap();
437 }
438 let expected = IssueState::from_dag(&canonical_dag).unwrap();
439
440 let mut indices: Vec<usize> = (0..all_ops.len()).collect();
442 for (i, &swap_seed) in perm.iter().enumerate() {
443 let a = i % all_ops.len();
444 let b = swap_seed % all_ops.len();
445 indices.swap(a, b);
446 }
447 let mut peer_dag = Dag::new();
448 for idx in indices {
449 peer_dag.insert_unchecked(all_ops[idx].clone()).unwrap();
450 }
451 for dup in dups {
452 let op = &all_ops[dup % all_ops.len()];
453 peer_dag.insert_unchecked(op.clone()).unwrap();
454 }
455
456 let actual = IssueState::from_dag(&peer_dag).unwrap();
457 assert_eq!(actual, expected);
458 assert_eq!(peer_dag.len(), all_ops.len());
459 });
460 }
461 }
462}