Skip to main content

kcode_k1_ese/
lib.rs

1use std::{
2    collections::HashMap,
3    path::Path,
4    sync::{Arc, Mutex},
5    time::{Duration, Instant},
6};
7
8use kcode_k1_ese_driver_state::{Claim, DriverState};
9use kcode_k1_ese_format::{Event, decode, encode};
10use kcode_k1_ese_store::{ApplyOutcome, EseStore};
11use kcode_k1_groups::K1Groups;
12use kcode_k1_peering::K1Peering;
13use kcode_k1_txn_ordering::{K1TxnOrdering, Subsystem, SubsystemId};
14use tokio::sync::watch;
15
16pub use kcode_k1_ese_driver_state::SubmitOutcome;
17pub use kcode_k1_ese_format::{Authority, ExternalSubsystem, GroupId, TxId, UserId};
18pub use kcode_k1_ese_store::ExternalUpdate;
19
20const SUBSYSTEM: &str = "k1-ese-subsystem";
21const UNAVAILABLE: &str = "external subsystem is unavailable";
22
23#[derive(Clone, Copy, Debug, Eq, PartialEq)]
24pub enum EseErrorKind {
25    Unavailable,
26    InvalidProgress,
27    OperationConflict,
28    DependencyUnavailable,
29}
30
31#[derive(Clone, Debug, Eq, PartialEq)]
32pub struct EseError {
33    kind: EseErrorKind,
34    message: String,
35}
36impl EseError {
37    pub const fn kind(&self) -> EseErrorKind {
38        self.kind
39    }
40    pub fn message(&self) -> &str {
41        &self.message
42    }
43    fn new(kind: EseErrorKind, message: impl Into<String>) -> Self {
44        Self {
45            kind,
46            message: message.into(),
47        }
48    }
49}
50
51struct Shared {
52    store: EseStore,
53    state: DriverState,
54    notices: Mutex<HashMap<ExternalSubsystem, watch::Sender<u64>>>,
55}
56impl Shared {
57    fn dependency(&self, stage: &str, message: impl AsRef<str>) -> EseError {
58        EseError::new(
59            EseErrorKind::DependencyUnavailable,
60            format!("{stage}: {}", message.as_ref()),
61        )
62    }
63
64    fn ensure_available(&self) -> Result<(), EseError> {
65        self.state
66            .ensure_available()
67            .map_err(|error| self.dependency("ESE availability", error))
68    }
69
70    fn receiver(&self, stream: &ExternalSubsystem) -> Result<watch::Receiver<u64>, EseError> {
71        let mut notices = self
72            .notices
73            .lock()
74            .map_err(|_| self.dependency("ESE notification", "lock failed"))?;
75        Ok(notices
76            .entry(stream.clone())
77            .or_insert_with(|| watch::channel(0).0)
78            .subscribe())
79    }
80
81    fn notify(&self, stream: &ExternalSubsystem) {
82        if let Ok(notices) = self.notices.lock()
83            && let Some(notice) = notices.get(stream)
84        {
85            notice.send_modify(|generation| *generation = generation.wrapping_add(1));
86        }
87    }
88
89    fn fault_and_wake(&self) {
90        let _ = self.state.fault();
91        if let Ok(notices) = self.notices.lock() {
92            for notice in notices.values() {
93                notice.send_modify(|generation| *generation = generation.wrapping_add(1));
94            }
95        }
96    }
97}
98
99struct EseSubsystem {
100    shared: Arc<Shared>,
101}
102impl Subsystem for EseSubsystem {
103    fn submit_txn(&self, id: TxId, payload: &[u8]) -> Result<(), String> {
104        let event = match decode(payload) {
105            Ok(event) => event,
106            Err(error) => {
107                self.shared.fault_and_wake();
108                return Err(error);
109            }
110        };
111        let outcome = match self.shared.store.apply(id, &event) {
112            Ok(outcome) => outcome,
113            Err(error) => {
114                self.shared.fault_and_wake();
115                return Err(error);
116            }
117        };
118        if let (Event::Submit { stream, .. }, ApplyOutcome::Submitted { .. }) = (&event, outcome) {
119            self.shared.notify(stream);
120        }
121        Ok(())
122    }
123
124    fn reorg(&self) -> Result<(), String> {
125        self.shared.fault_and_wake();
126        self.shared.store.discard()
127    }
128}
129
130pub struct K1Ese {
131    shared: Arc<Shared>,
132    _ordering: Arc<K1TxnOrdering>,
133    peering: Arc<K1Peering>,
134    groups: Arc<K1Groups>,
135    subsystem: SubsystemId,
136}
137
138impl K1Ese {
139    pub fn open(
140        root: &Path,
141        ordering: Arc<K1TxnOrdering>,
142        peering: Arc<K1Peering>,
143        groups: Arc<K1Groups>,
144    ) -> Result<Self, String> {
145        let started = Instant::now();
146        let store = EseStore::open(root)?;
147        let cursor = store.checkpoint()?;
148        let shared = Arc::new(Shared {
149            store,
150            state: DriverState::new(),
151            notices: Mutex::new(HashMap::new()),
152        });
153        let subsystem = SubsystemId::from_str(SUBSYSTEM)?;
154        if let Err(error) = ordering.register_subsystem(
155            subsystem,
156            cursor,
157            Arc::new(EseSubsystem {
158                shared: Arc::clone(&shared),
159            }),
160        ) {
161            shared.fault_and_wake();
162            return Err(error);
163        }
164        let elapsed = started.elapsed();
165        if elapsed > Duration::from_millis(100) {
166            eprintln!(
167                "{{\"module\":\"kcode-k1-ese\",\"operation\":\"open\",\"elapsed_microseconds\":{},\"outcome\":\"ready\"}}",
168                elapsed.as_micros()
169            );
170        }
171        Ok(Self {
172            shared,
173            _ordering: ordering,
174            peering,
175            groups,
176            subsystem,
177        })
178    }
179
180    pub fn register(&self, actor: UserId, stream: ExternalSubsystem) -> Result<(), EseError> {
181        self.shared.ensure_available()?;
182        self.authorize(actor, stream.authority())?;
183        if self
184            .shared
185            .store
186            .registered(&stream)
187            .map_err(|error| self.shared.dependency("inspect ESE registration", error))?
188        {
189            return Ok(());
190        }
191        let payload = encode(&Event::Register {
192            actor,
193            stream: stream.clone(),
194        })
195        .map_err(|error| self.shared.dependency("encode ESE registration", error))?;
196        let submitted = self.peering.submit_txn(self.subsystem, &payload);
197        let registered = self.shared.store.registered(&stream).map_err(|error| {
198            self.shared
199                .dependency("verify ESE registration callback", error)
200        })?;
201        match (submitted, registered) {
202            (_, true) => Ok(()),
203            (Err(error), false) => Err(self.shared.dependency("submit ESE registration", error)),
204            (Ok(_), false) => {
205                self.shared.fault_and_wake();
206                Err(self.shared.dependency(
207                    "verify ESE registration callback",
208                    "callback evidence is missing",
209                ))
210            }
211        }
212    }
213
214    pub fn submit(
215        &self,
216        actor: UserId,
217        stream: ExternalSubsystem,
218        operation_id: [u8; 32],
219        payload: &[u8],
220    ) -> Result<SubmitOutcome, EseError> {
221        self.shared.ensure_available()?;
222        self.authorize(actor, stream.authority())?;
223        if !self
224            .shared
225            .store
226            .registered(&stream)
227            .map_err(|error| self.shared.dependency("inspect ESE stream", error))?
228        {
229            return Err(unavailable());
230        }
231        if let Some(update) = self
232            .shared
233            .store
234            .operation(&stream, operation_id)
235            .map_err(|error| self.shared.dependency("inspect ESE operation", error))?
236        {
237            if update.payload() != payload {
238                return Err(conflict(
239                    "external subsystem operation conflicts with its existing payload",
240                ));
241            }
242            return Ok(SubmitOutcome::new(update.progress(), true));
243        }
244        match self
245            .shared
246            .state
247            .claim(stream.clone(), operation_id, payload)
248            .map_err(classify_state)?
249        {
250            Claim::Waiter(ticket) => self.shared.state.wait(ticket).map_err(classify_state),
251            Claim::Owner(ticket) => {
252                let result = self.submit_owned(actor, stream, operation_id, payload);
253                self.shared
254                    .state
255                    .complete(
256                        ticket,
257                        result.clone().map_err(|error| error.message().to_owned()),
258                    )
259                    .map_err(|error| result.err().unwrap_or_else(|| classify_state(error)))
260            }
261        }
262    }
263
264    fn submit_owned(
265        &self,
266        actor: UserId,
267        stream: ExternalSubsystem,
268        operation_id: [u8; 32],
269        payload: &[u8],
270    ) -> Result<SubmitOutcome, EseError> {
271        let bytes = encode(&Event::Submit {
272            actor,
273            stream: stream.clone(),
274            operation_id,
275            payload: payload.to_vec(),
276        })
277        .map_err(|error| self.shared.dependency("encode ESE submission", error))?;
278        let submitted = self.peering.submit_txn(self.subsystem, &bytes);
279        let evidence = self
280            .shared
281            .store
282            .operation(&stream, operation_id)
283            .map_err(|error| {
284                self.shared
285                    .dependency("verify ESE submission callback", error)
286            })?;
287        match (submitted, evidence) {
288            (_, Some(update)) if update.payload() == payload => {
289                Ok(SubmitOutcome::new(update.progress(), false))
290            }
291            (_, Some(_)) => {
292                self.shared.fault_and_wake();
293                Err(self.shared.dependency(
294                    "verify ESE submission callback",
295                    "payload evidence mismatch",
296                ))
297            }
298            (Err(error), None) => Err(self.shared.dependency("submit ESE update", error)),
299            (Ok(_), None) => {
300                self.shared.fault_and_wake();
301                Err(self.shared.dependency(
302                    "verify ESE submission callback",
303                    "callback evidence is missing",
304                ))
305            }
306        }
307    }
308
309    pub fn history(
310        &self,
311        actor: UserId,
312        stream: &ExternalSubsystem,
313        after: Option<TxId>,
314    ) -> Result<Vec<ExternalUpdate>, EseError> {
315        self.shared.ensure_available()?;
316        self.authorize(actor, stream.authority())?;
317        match self.shared.store.history(stream, after) {
318            Ok(Some(updates)) => Ok(updates),
319            Ok(None) => Err(unavailable()),
320            Err(error) if error.contains("progress") => {
321                Err(EseError::new(EseErrorKind::InvalidProgress, error))
322            }
323            Err(error) => Err(self.shared.dependency("read ESE history", error)),
324        }
325    }
326
327    pub async fn subscribe(
328        &self,
329        actor: UserId,
330        stream: ExternalSubsystem,
331        after: Option<TxId>,
332    ) -> Result<Vec<ExternalUpdate>, EseError> {
333        self.shared.ensure_available()?;
334        self.authorize(actor, stream.authority())?;
335        let mut receiver = self.shared.receiver(&stream)?;
336        loop {
337            let updates = self.history(actor, &stream, after)?;
338            if !updates.is_empty() {
339                return Ok(updates);
340            }
341            receiver.changed().await.map_err(|_| {
342                self.shared
343                    .dependency("wait for ESE update", "notification channel closed")
344            })?;
345            self.shared.ensure_available()?;
346            self.authorize(actor, stream.authority())?;
347        }
348    }
349
350    fn authorize(&self, actor: UserId, authority: Authority) -> Result<(), EseError> {
351        match authority {
352            Authority::User(user) if user == actor => Ok(()),
353            Authority::User(_) => Err(unavailable()),
354            Authority::Group(group) => {
355                let groups = self
356                    .groups
357                    .groups_for_user(actor)
358                    .map_err(|error| self.shared.dependency("resolve ESE authority", error))?;
359                if groups.contains(&group) {
360                    Ok(())
361                } else {
362                    Err(unavailable())
363                }
364            }
365        }
366    }
367}
368
369fn unavailable() -> EseError {
370    EseError::new(EseErrorKind::Unavailable, UNAVAILABLE)
371}
372fn conflict(message: impl Into<String>) -> EseError {
373    EseError::new(EseErrorKind::OperationConflict, message)
374}
375fn classify_state(message: String) -> EseError {
376    let kind = if message.contains("conflicts") {
377        EseErrorKind::OperationConflict
378    } else {
379        EseErrorKind::DependencyUnavailable
380    };
381    EseError::new(kind, message)
382}
383
384#[cfg(test)]
385mod tests {
386    use super::*;
387    use async_trait::async_trait;
388    use kcode_k1_ese_testkit::{Candidate, CandidateError, CandidateErrorKind, Harness};
389    use std::path::Path;
390
391    struct Adapter(Arc<K1Ese>);
392    fn adapt(error: EseError) -> CandidateError {
393        let kind = match error.kind() {
394            EseErrorKind::Unavailable => CandidateErrorKind::Unavailable,
395            EseErrorKind::InvalidProgress => CandidateErrorKind::InvalidProgress,
396            EseErrorKind::OperationConflict => CandidateErrorKind::OperationConflict,
397            EseErrorKind::DependencyUnavailable => CandidateErrorKind::DependencyUnavailable,
398        };
399        CandidateError::new(kind, error.message().to_owned())
400    }
401    #[async_trait]
402    impl Candidate for Adapter {
403        fn register(&self, actor: UserId, stream: ExternalSubsystem) -> Result<(), CandidateError> {
404            self.0.register(actor, stream).map_err(adapt)
405        }
406        fn submit(
407            &self,
408            actor: UserId,
409            stream: ExternalSubsystem,
410            operation_id: [u8; 32],
411            payload: &[u8],
412        ) -> Result<kcode_k1_ese_testkit::SubmitOutcome, CandidateError> {
413            self.0
414                .submit(actor, stream, operation_id, payload)
415                .map(|value| kcode_k1_ese_testkit::SubmitOutcome {
416                    progress: value.progress(),
417                    duplicate: value.duplicate(),
418                })
419                .map_err(adapt)
420        }
421        fn history(
422            &self,
423            actor: UserId,
424            stream: &ExternalSubsystem,
425            after: Option<TxId>,
426        ) -> Result<Vec<ExternalUpdate>, CandidateError> {
427            self.0.history(actor, stream, after).map_err(adapt)
428        }
429        async fn subscribe(
430            &self,
431            actor: UserId,
432            stream: ExternalSubsystem,
433            after: Option<TxId>,
434        ) -> Result<Vec<ExternalUpdate>, CandidateError> {
435            self.0.subscribe(actor, stream, after).await.map_err(adapt)
436        }
437    }
438    struct TestHarness;
439    impl Harness for TestHarness {
440        fn open(
441            &self,
442            root: &Path,
443            ordering: Arc<K1TxnOrdering>,
444            peering: Arc<K1Peering>,
445            groups: Arc<K1Groups>,
446        ) -> Result<Arc<dyn Candidate>, String> {
447            Ok(Arc::new(Adapter(Arc::new(K1Ese::open(
448                root, ordering, peering, groups,
449            )?))))
450        }
451    }
452    #[tokio::test]
453    async fn conformance() {
454        kcode_k1_ese_testkit::verify(&TestHarness).await.unwrap();
455    }
456    #[test]
457    fn package_is_bounded() {
458        let files = [
459            include_str!("../Cargo.toml"),
460            include_str!("../Documentation.md"),
461            include_str!("lib.rs"),
462        ];
463        assert!(
464            files
465                .iter()
466                .flat_map(|file| file.lines())
467                .filter(|line| !line.trim().is_empty())
468                .count()
469                < 500
470        );
471    }
472}