kernable-sdk 0.2.2

Write event-sourced business logic in Rust; the kernable kernel does the rest.
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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
//! Workers: run the commands of aggregates.

use std::{
    collections::{BTreeMap, HashMap},
    sync::{
        Arc, Mutex,
        atomic::{AtomicBool, AtomicU64, Ordering},
    },
    time::Duration,
};

use kernable_core::{
    PROTOCOL,
    proto::{
        self, ChallengeResponse, EventSchema, Register, Rejection, Snapshot, WorkerAggregate,
        WorkerMessage, kernel_message::Msg as Out, worker_gateway_client::WorkerGatewayClient,
        worker_message::Msg as In,
    },
    signing,
};
use tokio::sync::{mpsc, watch};
use tokio_stream::wrappers::ReceiverStream;

use crate::{
    Aggregate, BoxError, Client, Rejected, State,
    domain::{Failure, Runnable},
    log,
};

struct WorkerInner {
    client: Client,
    /// The service it belongs to (`Options::service`); empty if none.
    service: String,
    /// Qualified command type -> the aggregate that runs it.
    by_command: Mutex<HashMap<String, Arc<dyn Runnable>>>,
    settings: Mutex<(u32, Duration)>,
    stopped: watch::Sender<bool>,
    ready: watch::Sender<bool>,
    /// Whether the first connect gets its own line; an app prints it in its overview instead.
    announce: AtomicBool,
    /// Sessions the kernel accepted so far.
    connects: AtomicU64,
}

/// Runs the commands of its aggregates: the kernel sends each command with the aggregate's
/// events, the worker decides and sends the new events back, signed. Cloning gives another
/// handle to the same worker. Made with [`crate::Kernable::worker`]; the configuring methods
/// return it, so they chain.
///
/// `run().await` processes commands until `stop()`. To do something once it is connected,
/// spawn it and wait: `let worker = kernable.worker(&cart_aggregate); tokio::spawn({ let worker
/// = worker.clone(); async move { worker.run().await } }); worker.ready().await;`.
#[derive(Clone)]
pub struct Worker {
    inner: Arc<WorkerInner>,
}

impl Worker {
    pub(crate) fn new(client: Client, service: String) -> Worker {
        Worker {
            inner: Arc::new(WorkerInner {
                client,
                service,
                by_command: Mutex::default(),
                settings: Mutex::new((16, Duration::from_secs(1))),
                stopped: watch::Sender::new(false),
                ready: watch::Sender::new(false),
                announce: AtomicBool::new(true),
                connects: AtomicU64::new(0),
            }),
        }
    }

    /// The same worker on another client: one partition's session.
    fn on(&self, client: Client) -> Worker {
        let child = Worker::new(client, self.inner.service.clone());
        *child.inner.by_command.lock().unwrap() = self.inner.by_command.lock().unwrap().clone();
        *child.inner.settings.lock().unwrap() = *self.inner.settings.lock().unwrap();
        child.announce(self.inner.announce.load(Ordering::SeqCst));
        child
    }

    /// Runs the commands of `aggregate`, too.
    pub fn aggregate<S: State>(&self, aggregate: &Aggregate<S>) -> Worker {
        self.runnable(Arc::new(aggregate.clone()))
    }

    /// Runs the commands of `runnable`, too: an aggregate of any state type.
    pub(crate) fn runnable(&self, runnable: Arc<dyn Runnable>) -> Worker {
        let mut by_command = self.inner.by_command.lock().unwrap();
        for t in runnable.command_types() {
            by_command.insert(
                format!("{}.{t}", runnable.domain().name()),
                Arc::clone(&runnable),
            );
        }
        drop(by_command);
        self.clone()
    }

    /// Commands executed in parallel (default 16).
    pub fn concurrency(&self, commands: u32) -> Worker {
        self.inner.settings.lock().unwrap().0 = commands;
        self.clone()
    }

    /// Delay before reconnecting after the session ends (default 1 s); twice as long after each
    /// further failed attempt, at most 30 s.
    pub fn reconnect(&self, delay: Duration) -> Worker {
        self.inner.settings.lock().unwrap().1 = delay;
        self.clone()
    }

    /// Whether the first connect gets its own line (default); an app prints it in its overview.
    pub(crate) fn announce(&self, announce: bool) {
        self.inner.announce.store(announce, Ordering::SeqCst);
    }

    /// Returns once the kernel accepted the worker; waits forever if it never connects.
    pub async fn ready(&self) {
        let _ = self.inner.ready.subscribe().wait_for(|r| *r).await;
    }

    /// Ends `run`, also from another task.
    pub fn stop(&self) {
        self.inner.stopped.send_replace(true);
    }

    /// Processes commands until `stop()`, reconnecting when the session drops. A handler's
    /// error or panic rejects that command (`handler_error`); it does not end `run`.
    pub async fn run(&self) {
        let mut stopped = self.inner.stopped.subscribe();
        let base = self.inner.settings.lock().unwrap().1;
        let Some(parts) =
            crate::partitions_of(&self.inner.client, "worker", base, &mut stopped).await
        else {
            return;
        };
        if parts.len() > 1 || !parts[0].0.is_empty() {
            // A session per partition: commands of every partition's tenants run here.
            let children: Vec<Worker> = parts.into_iter().map(|(_, c)| self.on(c)).collect();
            let this = self.clone();
            let all = children.clone();
            tokio::spawn(async move {
                for child in &all {
                    child.ready().await;
                }
                this.inner.ready.send_replace(true);
            });
            let stopping = {
                let (this, all) = (self.clone(), children.clone());
                tokio::spawn(async move {
                    let _ = this.inner.stopped.subscribe().wait_for(|s| *s).await;
                    for child in &all {
                        child.stop();
                    }
                })
            };
            let running: Vec<_> = children
                .into_iter()
                .map(|child| tokio::spawn(async move { child.run_one().await }))
                .collect();
            for run in running {
                let _ = run.await;
            }
            stopping.abort();
            return;
        }
        self.run_one().await;
    }

    /// The session loop on this worker's one kernel (or one partition).
    async fn run_one(&self) {
        let mut stopped = self.inner.stopped.subscribe();
        let mut attempt = 0;
        while !*stopped.borrow() {
            let connects = self.inner.connects.load(Ordering::SeqCst);
            let session = self.session();
            let result = tokio::select! {
                result = session => result,
                _ = stopped.wait_for(|s| *s) => return,
            };
            attempt = if self.inner.connects.load(Ordering::SeqCst) > connects {
                1
            } else {
                attempt + 1
            };
            let base = self.inner.settings.lock().unwrap().1;
            let log = &self.inner.client.log;
            let delay = log::reconnecting(log, "worker", result.err().as_ref(), base, attempt);
            tokio::select! {
                () = tokio::time::sleep(delay) => {}
                _ = stopped.wait_for(|s| *s) => return,
            }
        }
    }

    async fn session(&self) -> Result<(), BoxError> {
        let client = &self.inner.client;
        let (concurrency, _) = *self.inner.settings.lock().unwrap();
        let by_command = self.inner.by_command.lock().unwrap().clone();
        let (tx, rx) = mpsc::channel(1024);
        let msg = |m: In| WorkerMessage { msg: Some(m) };
        tx.send(msg(In::Register(Register {
            worker_id: format!("rust-{}", std::process::id()),
            key_id: client.key_id.clone(),
            aggregates: aggregates(&by_command),
            max_concurrency: concurrency,
            event_schemas: event_schemas(&by_command),
            protocol: PROTOCOL,
            service: self.inner.service.clone(),
            deployment: client.deployment.clone(),
        })))
        .await?;
        let (at, channel) = client.channel();
        let ended = |status: tonic::Status| {
            client.ended(at, &status);
            status
        };
        let mut inbound = WorkerGatewayClient::new(channel)
            .session(client.request(ReceiverStream::new(rx)))
            .await
            .map_err(ended)?
            .into_inner();
        // A command this worker cannot read ends the session: it reconnects and is refused
        // until it is updated.
        let (fail, mut failed) = mpsc::channel::<String>(1);
        // Executes whose history is still coming, by lease.
        let mut partial: HashMap<String, proto::Execute> = HashMap::new();
        loop {
            let m = tokio::select! {
                m = inbound.message() => m.map_err(ended)?,
                Some(reason) = failed.recv() => return Err(reason.into()),
            };
            let Some(m) = m else {
                return Ok(());
            };
            let x = match m.msg {
                Some(Out::Challenge(c)) => {
                    let sig = client.sign(&signing::challenge_message(&c.nonce)).sig;
                    tx.send(msg(In::ChallengeResponse(ChallengeResponse { sig })))
                        .await?;
                    continue;
                }
                Some(Out::Registered(r)) => {
                    if !r.reader_of.is_empty() {
                        client.log.info("worker", || {
                            format!(
                                "connected to a reader: commands run on the writer ({}); this worker gets none here",
                                r.reader_of
                            )
                        });
                    }
                    if self.inner.connects.fetch_add(1, Ordering::SeqCst) > 0 {
                        client.log.info("worker", || "connected again".into());
                    } else if self.inner.announce.load(Ordering::SeqCst) {
                        let command_types: Vec<String> = by_command.keys().cloned().collect();
                        client.log.info("worker", || {
                            log::worker_connected(&client.log.peer, &command_types)
                        });
                    }
                    self.inner.ready.send_replace(true);
                    continue;
                }
                Some(Out::Execute(x)) => x,
                // A long history comes in parts.
                Some(Out::ExecuteMore(rest)) => {
                    let Some(mut x) = partial.remove(&rest.lease_id) else {
                        continue;
                    };
                    x.history.extend(rest.history);
                    x.vault.extend(rest.vault);
                    x.more = rest.more;
                    x
                }
                None => continue,
            };
            if x.more {
                partial.insert(x.lease_id.clone(), x);
                continue;
            }
            let command = x.command.clone().unwrap_or_default();
            let aggregate = by_command
                .get(&format!("{}.{}", command.domain, command.command_type))
                .filter(|a| a.name() == command.aggregate_type)
                .cloned();
            let (client, tx, fail) = (client.clone(), tx.clone(), fail.clone());
            tokio::spawn(async move {
                let outcome = match aggregate {
                    Some(aggregate) => {
                        let execute = x.clone();
                        let running =
                            tokio::task::spawn_blocking(move || aggregate.execute(&execute));
                        // A handler cannot be stopped from outside; one that runs past
                        // its lease at least shows.
                        let lease =
                            u64::try_from(x.deadline - crate::context::now_ms()).unwrap_or(0);
                        let stream = format!(
                            "{}.{} {}/{}",
                            command.domain,
                            command.command_type,
                            command.aggregate_type,
                            command.aggregate_id
                        );
                        let line = || {
                            format!(
                                "{stream} still running after its lease ended: the kernel \
                                     gives it to another worker; is the handler stuck?"
                            )
                        };
                        let finished = log::watched(
                            &client.log,
                            "worker",
                            Duration::from_millis(lease),
                            line,
                            running,
                        );
                        match finished.await {
                            Ok(outcome) => (x, outcome),
                            // A panic outside the handlers' own guard (an eraser, say)
                            // still answers the command.
                            Err(e) => {
                                let text = match e.try_into_panic() {
                                    Ok(panic) => crate::domain::panic_text(panic.as_ref()),
                                    Err(e) => e.to_string(),
                                };
                                (x, Err(Failure::Error(text)))
                            }
                        }
                    }
                    None => {
                        let reason = Rejected::new(format!(
                            "no handler for {} on {}.{}",
                            command.command_type, command.domain, command.aggregate_type
                        ))
                        .code("unknown_command");
                        (x, Err(Failure::Rejected(reason)))
                    }
                };
                let reply = match reply(&client, outcome) {
                    Ok(reply) => reply,
                    Err(reason) => {
                        client.log.error("worker", || reason.clone());
                        let _ = fail.send(reason).await;
                        return;
                    }
                };
                client.log.debug("worker", || {
                    let outcome = match &reply {
                        In::Result(r) => Ok(r.events.len()),
                        In::Rejection(r) => Err(r.reason.as_ref().map_or("", |r| r.code.as_str())),
                        _ => Err(""),
                    };
                    log::command_done(
                        &format!("{}.{}", command.domain, command.command_type),
                        &command.aggregate_type,
                        &command.aggregate_id,
                        outcome,
                    )
                });
                let _ = tx.send(msg(reply)).await;
            });
        }
    }
}

/// The signed result or rejection for an executed command, or why the worker cannot read it.
fn reply(
    client: &Client,
    (x, outcome): (proto::Execute, Result<crate::domain::Executed, Failure>),
) -> Result<In, String> {
    let cmd = x.command.unwrap_or_default();
    let reason = match outcome {
        Ok(done) => {
            let snapshot = done.snapshot.map(|(version, schema, state)| {
                let worker_sig =
                    client.sign(&signing::snapshot_message(&cmd, version, &schema, &state));
                Snapshot {
                    version,
                    schema,
                    state,
                    worker_sig: Some(worker_sig),
                }
            });
            let worker_sig = client.sign(&signing::result_message(
                &cmd,
                x.expected_version,
                &done.events,
            ));
            let index_sig = index_sig(
                &cmd,
                x.expected_version,
                (&done.keys, &done.facts, &done.requires),
                |m| client.sign(m),
            );
            return Ok(In::Result(proto::Result {
                lease_id: x.lease_id,
                events: done.events,
                worker_sig: Some(worker_sig),
                snapshot,
                vault: done.vault,
                keys: done.keys,
                facts: done.facts,
                requires: done.requires,
                index_sig,
            }));
        }
        Err(Failure::Schema(reason)) => return Err(reason),
        Err(Failure::Rejected(r)) => r,
        Err(Failure::Error(message)) => {
            // An unexpected error's text may hold personal data or internals, and a rejection is
            // kept for good: it says only that the handler failed; the log has the rest.
            client.log.error("worker", || {
                format!(
                    "{}.{} {}/{} failed: {message}",
                    cmd.domain, cmd.command_type, cmd.aggregate_type, cmd.aggregate_id
                )
            });
            Rejected::new("handler failed").code("handler_error")
        }
    };
    let reason = reason.to_wire();
    let worker_sig = client.sign(&signing::rejection_message(&cmd.command_id, &reason));
    Ok(In::Rejection(Rejection {
        lease_id: x.lease_id,
        reason: Some(reason),
        worker_sig: Some(worker_sig),
    }))
}

/// The signature over the unique keys, facts and requirements of a result for `cmd` at
/// `expected_version`; none if it has none of them.
fn index_sig(
    cmd: &proto::Command,
    expected_version: u64,
    (keys, facts, requires): (&[proto::UniqueKey], &[String], &[proto::Requirement]),
    sign: impl FnOnce(&[u8]) -> proto::Signature,
) -> Option<proto::Signature> {
    if keys.is_empty() && facts.is_empty() && requires.is_empty() {
        return None;
    }
    Some(sign(&signing::index_message(
        cmd,
        expected_version,
        keys,
        facts,
        requires,
    )))
}

/// An aggregate's qualified type: `shop.Cart`.
fn qualified(aggregate: &dyn Runnable) -> String {
    format!("{}.{}", aggregate.domain().name(), aggregate.name())
}

/// The worker's aggregates with their qualified command types, as it registers them.
fn aggregates(by_command: &HashMap<String, Arc<dyn Runnable>>) -> Vec<WorkerAggregate> {
    let mut grouped: BTreeMap<String, Vec<String>> = BTreeMap::new();
    for (command_type, aggregate) in by_command {
        grouped
            .entry(qualified(aggregate.as_ref()))
            .or_default()
            .push(command_type.clone());
    }
    grouped
        .into_iter()
        .map(|(aggregate_type, mut command_types)| {
            command_types.sort();
            WorkerAggregate {
                aggregate_type,
                command_types,
            }
        })
        .collect()
}

/// The payload versions the worker writes, for every event type its aggregates know: those
/// they apply and those their domains declare. Without a deployment the kernel refuses the
/// worker if the store already holds a newer one; with one it rejects commands on aggregates
/// holding a newer schema, or a type not listed here (`unknown_history`).
fn event_schemas(by_command: &HashMap<String, Arc<dyn Runnable>>) -> Vec<EventSchema> {
    let mut schemas = HashMap::new();
    for aggregate in by_command.values() {
        let domain = aggregate.domain();
        for t in aggregate.event_types() {
            schemas.insert(format!("{}.{t}", domain.name()), domain.schema_of(&t));
        }
    }
    schemas
        .into_iter()
        .map(|(event_type, schema)| EventSchema { event_type, schema })
        .collect()
}

#[cfg(test)]
mod tests {
    use serde::{Deserialize, Serialize};
    use serde_json::{Value, json};

    use super::*;
    use crate::{NewEvent, Requirement, Unique, domain, domain::Runnable};

    #[derive(Clone, Default, Serialize, Deserialize)]
    struct Order {
        number: Option<String>,
        email: Option<String>,
        customer: String,
        open: bool,
        paid: bool,
    }

    /// The index of a result is signed as the shared test vector `result_index` says: value
    /// hashes, scopes and subjects of the keys in declaration order, the true facts, and the
    /// requirements from the command's data.
    #[test]
    fn the_index_of_a_result_is_signed_as_the_test_vectors_say() {
        let path = concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../../proto/test-vectors/signing.json"
        );
        let vectors: Value = serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap();
        let vector = &vectors["result_index"];
        let input = &vector["input"]["command"];
        fn text(v: &Value) -> String {
            v.as_str().unwrap().to_owned()
        }

        let orders = domain("orders");
        let order = orders.aggregate("Order", Order::default());
        order.apply("OrderPlaced", |s, d: Value, _evt, _ctx| {
            *s = Order {
                number: Some(text(&d["number"])),
                email: Some(text(&d["email"])),
                customer: text(&d["customerId"]),
                open: true,
                paid: true,
            }
        });
        order.command("PlaceOrder", |_, d: Value, _cmd, _ctx| {
            let placed = json!({ "number": "A-1001", "email": "max@example.com", "customerId": d["customerId"] });
            Ok(vec![NewEvent::new("OrderPlaced", placed)])
        });
        order
            .unique("number", |s| s.number.clone(), Unique::tenant())
            .unique(
                "email",
                |s| s.email.clone(),
                Unique::global().personal(|s: &Order| Some(s.customer.clone())),
            )
            .fact("open", |s| s.open)
            .fact("closed", |s| !s.open)
            .fact("paid", |s| s.paid)
            .requires("PlaceOrder", |_, d: Value| {
                [
                    Requirement::new(
                        "identity",
                        "Customer",
                        d["customerId"].as_str().unwrap(),
                        "active",
                    ),
                    Requirement::by_key("funds", "Vehicle", "isin", "VEH-lyra", "woundUp").absent(),
                ]
            });

        let cmd = proto::Command {
            command_id: text(&input["command_id"]),
            tenant_id: text(&input["tenant_id"]),
            domain: text(&input["domain"]),
            aggregate_type: text(&input["aggregate_type"]),
            aggregate_id: text(&input["aggregate_id"]),
            command_type: text(&input["command_type"]),
            payload: hex::decode(text(&input["payload_hex"])).unwrap(),
            ..Default::default()
        };
        let expected_version = vector["input"]["expected_version"].as_u64().unwrap();
        let execute = proto::Execute {
            command: Some(cmd.clone()),
            expected_version,
            ..Default::default()
        };
        let done = order
            .execute(&execute)
            .unwrap_or_else(|_| panic!("executes"));
        let key = signing::signing_key_from_hex(&text(&vectors["key"]["seed"])).unwrap();
        let mut signed = Vec::new();
        let sig = index_sig(
            &cmd,
            expected_version,
            (&done.keys, &done.facts, &done.requires),
            |m| {
                signed = m.to_vec();
                signing::sign(&key, m)
            },
        )
        .unwrap();
        assert_eq!(hex::encode(&signed), text(&vector["message"]));
        assert_eq!(hex::encode(&sig.sig), text(&vector["signature"]));

        // Without keys, facts or requirements, a result has no index signature.
        let none = index_sig(&cmd, expected_version, (&[], &[], &[]), |_| unreachable!());
        assert!(none.is_none());
    }

    /// A worker lists every event type it knows: those its aggregates only apply (at 1 unless
    /// declared), and those its domain declares, at the declared schema.
    #[test]
    fn the_event_schemas_list_applied_and_declared_types() {
        let shop = domain("shop");
        shop.event("ItemAdded", 2).upcast(1, |v| v);
        shop.event("Noted", 3).upcast(1, |v| v).upcast(2, |v| v);
        let cart = shop.aggregate("Cart", 0u32);
        cart.apply("ItemAdded", |n, _: Value, _evt, _ctx| *n += 1);
        cart.apply("Cleared", |n, _: Value, _evt, _ctx| *n = 0);
        cart.command("Add", |_, _: Value, _cmd, _ctx| {
            Ok(vec![NewEvent::new("ItemAdded", ())])
        });
        let mut by_command: HashMap<String, Arc<dyn Runnable>> = HashMap::new();
        by_command.insert("shop.Add".into(), Arc::new(cart));
        let mut schemas: Vec<(String, u32)> = event_schemas(&by_command)
            .into_iter()
            .map(|s| (s.event_type, s.schema))
            .collect();
        schemas.sort();
        assert_eq!(
            schemas,
            [
                ("shop.Cleared".to_owned(), 1),
                ("shop.ItemAdded".to_owned(), 2),
                ("shop.Noted".to_owned(), 3),
            ]
        );
    }
}