kcode-k1-ese 0.1.0

Authority-scoped External Subsystem Enabler for Kennedy K1
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
use std::{
    collections::HashMap,
    path::Path,
    sync::{Arc, Mutex},
    time::{Duration, Instant},
};

use kcode_k1_ese_driver_state::{Claim, DriverState};
use kcode_k1_ese_format::{Event, decode, encode};
use kcode_k1_ese_store::{ApplyOutcome, EseStore};
use kcode_k1_groups::K1Groups;
use kcode_k1_peering::K1Peering;
use kcode_k1_txn_ordering::{K1TxnOrdering, Subsystem, SubsystemId};
use tokio::sync::watch;

pub use kcode_k1_ese_driver_state::SubmitOutcome;
pub use kcode_k1_ese_format::{Authority, ExternalSubsystem, GroupId, TxId, UserId};
pub use kcode_k1_ese_store::ExternalUpdate;

const SUBSYSTEM: &str = "k1-ese-subsystem";
const UNAVAILABLE: &str = "external subsystem is unavailable";

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum EseErrorKind {
    Unavailable,
    InvalidProgress,
    OperationConflict,
    DependencyUnavailable,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct EseError {
    kind: EseErrorKind,
    message: String,
}
impl EseError {
    pub const fn kind(&self) -> EseErrorKind {
        self.kind
    }
    pub fn message(&self) -> &str {
        &self.message
    }
    fn new(kind: EseErrorKind, message: impl Into<String>) -> Self {
        Self {
            kind,
            message: message.into(),
        }
    }
}

struct Shared {
    store: EseStore,
    state: DriverState,
    notices: Mutex<HashMap<ExternalSubsystem, watch::Sender<u64>>>,
}
impl Shared {
    fn dependency(&self, stage: &str, message: impl AsRef<str>) -> EseError {
        EseError::new(
            EseErrorKind::DependencyUnavailable,
            format!("{stage}: {}", message.as_ref()),
        )
    }

    fn ensure_available(&self) -> Result<(), EseError> {
        self.state
            .ensure_available()
            .map_err(|error| self.dependency("ESE availability", error))
    }

    fn receiver(&self, stream: &ExternalSubsystem) -> Result<watch::Receiver<u64>, EseError> {
        let mut notices = self
            .notices
            .lock()
            .map_err(|_| self.dependency("ESE notification", "lock failed"))?;
        Ok(notices
            .entry(stream.clone())
            .or_insert_with(|| watch::channel(0).0)
            .subscribe())
    }

    fn notify(&self, stream: &ExternalSubsystem) {
        if let Ok(notices) = self.notices.lock()
            && let Some(notice) = notices.get(stream)
        {
            notice.send_modify(|generation| *generation = generation.wrapping_add(1));
        }
    }

    fn fault_and_wake(&self) {
        let _ = self.state.fault();
        if let Ok(notices) = self.notices.lock() {
            for notice in notices.values() {
                notice.send_modify(|generation| *generation = generation.wrapping_add(1));
            }
        }
    }
}

struct EseSubsystem {
    shared: Arc<Shared>,
}
impl Subsystem for EseSubsystem {
    fn submit_txn(&self, id: TxId, payload: &[u8]) -> Result<(), String> {
        let event = match decode(payload) {
            Ok(event) => event,
            Err(error) => {
                self.shared.fault_and_wake();
                return Err(error);
            }
        };
        let outcome = match self.shared.store.apply(id, &event) {
            Ok(outcome) => outcome,
            Err(error) => {
                self.shared.fault_and_wake();
                return Err(error);
            }
        };
        if let (Event::Submit { stream, .. }, ApplyOutcome::Submitted { .. }) = (&event, outcome) {
            self.shared.notify(stream);
        }
        Ok(())
    }

    fn reorg(&self) -> Result<(), String> {
        self.shared.fault_and_wake();
        self.shared.store.discard()
    }
}

pub struct K1Ese {
    shared: Arc<Shared>,
    _ordering: Arc<K1TxnOrdering>,
    peering: Arc<K1Peering>,
    groups: Arc<K1Groups>,
    subsystem: SubsystemId,
}

impl K1Ese {
    pub fn open(
        root: &Path,
        ordering: Arc<K1TxnOrdering>,
        peering: Arc<K1Peering>,
        groups: Arc<K1Groups>,
    ) -> Result<Self, String> {
        let started = Instant::now();
        let store = EseStore::open(root)?;
        let cursor = store.checkpoint()?;
        let shared = Arc::new(Shared {
            store,
            state: DriverState::new(),
            notices: Mutex::new(HashMap::new()),
        });
        let subsystem = SubsystemId::from_str(SUBSYSTEM)?;
        if let Err(error) = ordering.register_subsystem(
            subsystem,
            cursor,
            Arc::new(EseSubsystem {
                shared: Arc::clone(&shared),
            }),
        ) {
            shared.fault_and_wake();
            return Err(error);
        }
        let elapsed = started.elapsed();
        if elapsed > Duration::from_millis(100) {
            eprintln!(
                "{{\"module\":\"kcode-k1-ese\",\"operation\":\"open\",\"elapsed_microseconds\":{},\"outcome\":\"ready\"}}",
                elapsed.as_micros()
            );
        }
        Ok(Self {
            shared,
            _ordering: ordering,
            peering,
            groups,
            subsystem,
        })
    }

    pub fn register(&self, actor: UserId, stream: ExternalSubsystem) -> Result<(), EseError> {
        self.shared.ensure_available()?;
        self.authorize(actor, stream.authority())?;
        if self
            .shared
            .store
            .registered(&stream)
            .map_err(|error| self.shared.dependency("inspect ESE registration", error))?
        {
            return Ok(());
        }
        let payload = encode(&Event::Register {
            actor,
            stream: stream.clone(),
        })
        .map_err(|error| self.shared.dependency("encode ESE registration", error))?;
        let submitted = self.peering.submit_txn(self.subsystem, &payload);
        let registered = self.shared.store.registered(&stream).map_err(|error| {
            self.shared
                .dependency("verify ESE registration callback", error)
        })?;
        match (submitted, registered) {
            (_, true) => Ok(()),
            (Err(error), false) => Err(self.shared.dependency("submit ESE registration", error)),
            (Ok(_), false) => {
                self.shared.fault_and_wake();
                Err(self.shared.dependency(
                    "verify ESE registration callback",
                    "callback evidence is missing",
                ))
            }
        }
    }

    pub fn submit(
        &self,
        actor: UserId,
        stream: ExternalSubsystem,
        operation_id: [u8; 32],
        payload: &[u8],
    ) -> Result<SubmitOutcome, EseError> {
        self.shared.ensure_available()?;
        self.authorize(actor, stream.authority())?;
        if !self
            .shared
            .store
            .registered(&stream)
            .map_err(|error| self.shared.dependency("inspect ESE stream", error))?
        {
            return Err(unavailable());
        }
        if let Some(update) = self
            .shared
            .store
            .operation(&stream, operation_id)
            .map_err(|error| self.shared.dependency("inspect ESE operation", error))?
        {
            if update.payload() != payload {
                return Err(conflict(
                    "external subsystem operation conflicts with its existing payload",
                ));
            }
            return Ok(SubmitOutcome::new(update.progress(), true));
        }
        match self
            .shared
            .state
            .claim(stream.clone(), operation_id, payload)
            .map_err(classify_state)?
        {
            Claim::Waiter(ticket) => self.shared.state.wait(ticket).map_err(classify_state),
            Claim::Owner(ticket) => {
                let result = self.submit_owned(actor, stream, operation_id, payload);
                self.shared
                    .state
                    .complete(
                        ticket,
                        result.clone().map_err(|error| error.message().to_owned()),
                    )
                    .map_err(|error| result.err().unwrap_or_else(|| classify_state(error)))
            }
        }
    }

    fn submit_owned(
        &self,
        actor: UserId,
        stream: ExternalSubsystem,
        operation_id: [u8; 32],
        payload: &[u8],
    ) -> Result<SubmitOutcome, EseError> {
        let bytes = encode(&Event::Submit {
            actor,
            stream: stream.clone(),
            operation_id,
            payload: payload.to_vec(),
        })
        .map_err(|error| self.shared.dependency("encode ESE submission", error))?;
        let submitted = self.peering.submit_txn(self.subsystem, &bytes);
        let evidence = self
            .shared
            .store
            .operation(&stream, operation_id)
            .map_err(|error| {
                self.shared
                    .dependency("verify ESE submission callback", error)
            })?;
        match (submitted, evidence) {
            (_, Some(update)) if update.payload() == payload => {
                Ok(SubmitOutcome::new(update.progress(), false))
            }
            (_, Some(_)) => {
                self.shared.fault_and_wake();
                Err(self.shared.dependency(
                    "verify ESE submission callback",
                    "payload evidence mismatch",
                ))
            }
            (Err(error), None) => Err(self.shared.dependency("submit ESE update", error)),
            (Ok(_), None) => {
                self.shared.fault_and_wake();
                Err(self.shared.dependency(
                    "verify ESE submission callback",
                    "callback evidence is missing",
                ))
            }
        }
    }

    pub fn history(
        &self,
        actor: UserId,
        stream: &ExternalSubsystem,
        after: Option<TxId>,
    ) -> Result<Vec<ExternalUpdate>, EseError> {
        self.shared.ensure_available()?;
        self.authorize(actor, stream.authority())?;
        match self.shared.store.history(stream, after) {
            Ok(Some(updates)) => Ok(updates),
            Ok(None) => Err(unavailable()),
            Err(error) if error.contains("progress") => {
                Err(EseError::new(EseErrorKind::InvalidProgress, error))
            }
            Err(error) => Err(self.shared.dependency("read ESE history", error)),
        }
    }

    pub async fn subscribe(
        &self,
        actor: UserId,
        stream: ExternalSubsystem,
        after: Option<TxId>,
    ) -> Result<Vec<ExternalUpdate>, EseError> {
        self.shared.ensure_available()?;
        self.authorize(actor, stream.authority())?;
        let mut receiver = self.shared.receiver(&stream)?;
        loop {
            let updates = self.history(actor, &stream, after)?;
            if !updates.is_empty() {
                return Ok(updates);
            }
            receiver.changed().await.map_err(|_| {
                self.shared
                    .dependency("wait for ESE update", "notification channel closed")
            })?;
            self.shared.ensure_available()?;
            self.authorize(actor, stream.authority())?;
        }
    }

    fn authorize(&self, actor: UserId, authority: Authority) -> Result<(), EseError> {
        match authority {
            Authority::User(user) if user == actor => Ok(()),
            Authority::User(_) => Err(unavailable()),
            Authority::Group(group) => {
                let groups = self
                    .groups
                    .groups_for_user(actor)
                    .map_err(|error| self.shared.dependency("resolve ESE authority", error))?;
                if groups.contains(&group) {
                    Ok(())
                } else {
                    Err(unavailable())
                }
            }
        }
    }
}

fn unavailable() -> EseError {
    EseError::new(EseErrorKind::Unavailable, UNAVAILABLE)
}
fn conflict(message: impl Into<String>) -> EseError {
    EseError::new(EseErrorKind::OperationConflict, message)
}
fn classify_state(message: String) -> EseError {
    let kind = if message.contains("conflicts") {
        EseErrorKind::OperationConflict
    } else {
        EseErrorKind::DependencyUnavailable
    };
    EseError::new(kind, message)
}

#[cfg(test)]
mod tests {
    use super::*;
    use async_trait::async_trait;
    use kcode_k1_ese_testkit::{Candidate, CandidateError, CandidateErrorKind, Harness};
    use std::path::Path;

    struct Adapter(Arc<K1Ese>);
    fn adapt(error: EseError) -> CandidateError {
        let kind = match error.kind() {
            EseErrorKind::Unavailable => CandidateErrorKind::Unavailable,
            EseErrorKind::InvalidProgress => CandidateErrorKind::InvalidProgress,
            EseErrorKind::OperationConflict => CandidateErrorKind::OperationConflict,
            EseErrorKind::DependencyUnavailable => CandidateErrorKind::DependencyUnavailable,
        };
        CandidateError::new(kind, error.message().to_owned())
    }
    #[async_trait]
    impl Candidate for Adapter {
        fn register(&self, actor: UserId, stream: ExternalSubsystem) -> Result<(), CandidateError> {
            self.0.register(actor, stream).map_err(adapt)
        }
        fn submit(
            &self,
            actor: UserId,
            stream: ExternalSubsystem,
            operation_id: [u8; 32],
            payload: &[u8],
        ) -> Result<kcode_k1_ese_testkit::SubmitOutcome, CandidateError> {
            self.0
                .submit(actor, stream, operation_id, payload)
                .map(|value| kcode_k1_ese_testkit::SubmitOutcome {
                    progress: value.progress(),
                    duplicate: value.duplicate(),
                })
                .map_err(adapt)
        }
        fn history(
            &self,
            actor: UserId,
            stream: &ExternalSubsystem,
            after: Option<TxId>,
        ) -> Result<Vec<ExternalUpdate>, CandidateError> {
            self.0.history(actor, stream, after).map_err(adapt)
        }
        async fn subscribe(
            &self,
            actor: UserId,
            stream: ExternalSubsystem,
            after: Option<TxId>,
        ) -> Result<Vec<ExternalUpdate>, CandidateError> {
            self.0.subscribe(actor, stream, after).await.map_err(adapt)
        }
    }
    struct TestHarness;
    impl Harness for TestHarness {
        fn open(
            &self,
            root: &Path,
            ordering: Arc<K1TxnOrdering>,
            peering: Arc<K1Peering>,
            groups: Arc<K1Groups>,
        ) -> Result<Arc<dyn Candidate>, String> {
            Ok(Arc::new(Adapter(Arc::new(K1Ese::open(
                root, ordering, peering, groups,
            )?))))
        }
    }
    #[tokio::test]
    async fn conformance() {
        kcode_k1_ese_testkit::verify(&TestHarness).await.unwrap();
    }
    #[test]
    fn package_is_bounded() {
        let files = [
            include_str!("../Cargo.toml"),
            include_str!("../Documentation.md"),
            include_str!("lib.rs"),
        ];
        assert!(
            files
                .iter()
                .flat_map(|file| file.lines())
                .filter(|line| !line.trim().is_empty())
                .count()
                < 500
        );
    }
}