Skip to main content

glass_dev/development/
collaboration.rs

1use super::{Actor, DevelopmentError, DevelopmentResult};
2use serde::{Deserialize, Serialize};
3use serde_json::Value;
4use std::{
5    collections::BTreeMap,
6    sync::mpsc::{self, Receiver, SyncSender, TrySendError},
7};
8
9#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
10#[serde(rename_all = "camelCase")]
11pub enum EditAccess {
12    Read,
13    Write,
14}
15
16#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
17#[serde(rename_all = "camelCase")]
18pub struct EditClaim {
19    pub actor: Actor,
20    pub path: String,
21    pub start_line: u32,
22    pub end_line: u32,
23    pub access: EditAccess,
24}
25
26#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
27#[serde(rename_all = "camelCase")]
28pub struct CollaborationEvent {
29    pub kind: String,
30    pub actor: Actor,
31    pub payload: Value,
32}
33
34#[derive(Debug, Default)]
35pub struct CollaborationBus {
36    claims: BTreeMap<String, Vec<EditClaim>>,
37    subscribers: Vec<SyncSender<CollaborationEvent>>,
38}
39
40impl CollaborationBus {
41    pub fn subscribe(&mut self) -> Receiver<CollaborationEvent> {
42        let (sender, receiver) = mpsc::sync_channel(128);
43        self.subscribers.push(sender);
44        receiver
45    }
46
47    pub fn claim(&mut self, claim: EditClaim) -> DevelopmentResult<()> {
48        if claim.path.is_empty()
49            || claim.path.len() > 512
50            || claim.start_line == 0
51            || claim.end_line < claim.start_line
52        {
53            return Err(DevelopmentError::InvalidInput(
54                "edit claim requires a bounded path and ordered one-based lines".into(),
55            ));
56        }
57        let claims = self.claims.entry(claim.path.clone()).or_default();
58        let overlaps = |other: &EditClaim| {
59            claim.start_line <= other.end_line && other.start_line <= claim.end_line
60        };
61        if claim.access == EditAccess::Write
62            && claims.iter().any(|other| {
63                other.actor.id != claim.actor.id
64                    && other.access == EditAccess::Write
65                    && overlaps(other)
66            })
67        {
68            return Err(DevelopmentError::Conflict(format!(
69                "{} overlaps another actor's write claim",
70                claim.path
71            )));
72        }
73        claims.retain(|other| {
74            !(other.actor.id == claim.actor.id
75                && other.start_line == claim.start_line
76                && other.end_line == claim.end_line)
77        });
78        claims.push(claim.clone());
79        self.publish(CollaborationEvent {
80            kind: "editor.claimed".into(),
81            actor: claim.actor.clone(),
82            payload: serde_json::to_value(claim)?,
83        });
84        Ok(())
85    }
86
87    pub fn release_actor(&mut self, actor_id: &str) {
88        for claims in self.claims.values_mut() {
89            claims.retain(|claim| claim.actor.id != actor_id);
90        }
91    }
92
93    pub fn claims(&self, path: &str) -> &[EditClaim] {
94        self.claims.get(path).map(Vec::as_slice).unwrap_or(&[])
95    }
96
97    pub fn publish(&mut self, event: CollaborationEvent) {
98        self.subscribers
99            .retain(|subscriber| match subscriber.try_send(event.clone()) {
100                Ok(()) | Err(TrySendError::Full(_)) => true,
101                Err(TrySendError::Disconnected(_)) => false,
102            });
103    }
104}
105
106#[cfg(test)]
107mod tests {
108    use super::*;
109
110    #[test]
111    fn overlapping_writers_fail_while_readers_and_events_remain_bounded() {
112        let mut bus = CollaborationBus::default();
113        let receiver = bus.subscribe();
114        bus.claim(EditClaim {
115            actor: Actor::local(),
116            path: "src/app.rs".into(),
117            start_line: 10,
118            end_line: 20,
119            access: EditAccess::Write,
120        })
121        .unwrap();
122        assert!(
123            bus.claim(EditClaim {
124                actor: Actor::external("codex"),
125                path: "src/app.rs".into(),
126                start_line: 15,
127                end_line: 16,
128                access: EditAccess::Write,
129            })
130            .is_err()
131        );
132        assert_eq!(receiver.try_recv().unwrap().kind, "editor.claimed");
133    }
134}