Skip to main content

kernable/
worker.rs

1//! Workers: run the commands of aggregates.
2
3use std::{
4    collections::{BTreeMap, HashMap},
5    sync::{
6        Arc, Mutex,
7        atomic::{AtomicBool, AtomicU64, Ordering},
8    },
9    time::Duration,
10};
11
12use kernable_core::{
13    PROTOCOL,
14    proto::{
15        self, ChallengeResponse, EventSchema, Register, Rejection, Snapshot, WorkerAggregate,
16        WorkerMessage, kernel_message::Msg as Out, worker_gateway_client::WorkerGatewayClient,
17        worker_message::Msg as In,
18    },
19    signing,
20};
21use tokio::sync::{mpsc, watch};
22use tokio_stream::wrappers::ReceiverStream;
23
24use crate::{
25    Aggregate, BoxError, Client, Rejected, State,
26    domain::{Failure, Runnable},
27    log,
28};
29
30struct WorkerInner {
31    client: Client,
32    /// The service it belongs to (`Options::service`); empty if none.
33    service: String,
34    /// Qualified command type -> the aggregate that runs it.
35    by_command: Mutex<HashMap<String, Arc<dyn Runnable>>>,
36    settings: Mutex<(u32, Duration)>,
37    stopped: watch::Sender<bool>,
38    ready: watch::Sender<bool>,
39    /// Whether the first connect gets its own line; an app prints it in its overview instead.
40    announce: AtomicBool,
41    /// Sessions the kernel accepted so far.
42    connects: AtomicU64,
43}
44
45/// Runs the commands of its aggregates: the kernel sends each command with the aggregate's
46/// events, the worker decides and sends the new events back, signed. Cloning gives another
47/// handle to the same worker. Made with [`crate::Kernable::worker`]; the configuring methods
48/// return it, so they chain.
49///
50/// `run().await` processes commands until `stop()`. To do something once it is connected,
51/// spawn it and wait: `let worker = kernable.worker(&cart_aggregate); tokio::spawn({ let worker
52/// = worker.clone(); async move { worker.run().await } }); worker.ready().await;`.
53#[derive(Clone)]
54pub struct Worker {
55    inner: Arc<WorkerInner>,
56}
57
58impl Worker {
59    pub(crate) fn new(client: Client, service: String) -> Worker {
60        Worker {
61            inner: Arc::new(WorkerInner {
62                client,
63                service,
64                by_command: Mutex::default(),
65                settings: Mutex::new((16, Duration::from_secs(1))),
66                stopped: watch::Sender::new(false),
67                ready: watch::Sender::new(false),
68                announce: AtomicBool::new(true),
69                connects: AtomicU64::new(0),
70            }),
71        }
72    }
73
74    /// The same worker on another client: one partition's session.
75    fn on(&self, client: Client) -> Worker {
76        let child = Worker::new(client, self.inner.service.clone());
77        *child.inner.by_command.lock().unwrap() = self.inner.by_command.lock().unwrap().clone();
78        *child.inner.settings.lock().unwrap() = *self.inner.settings.lock().unwrap();
79        child.announce(self.inner.announce.load(Ordering::SeqCst));
80        child
81    }
82
83    /// Runs the commands of `aggregate`, too.
84    pub fn aggregate<S: State>(&self, aggregate: &Aggregate<S>) -> Worker {
85        self.runnable(Arc::new(aggregate.clone()))
86    }
87
88    /// Runs the commands of `runnable`, too: an aggregate of any state type.
89    pub(crate) fn runnable(&self, runnable: Arc<dyn Runnable>) -> Worker {
90        let mut by_command = self.inner.by_command.lock().unwrap();
91        for t in runnable.command_types() {
92            by_command.insert(
93                format!("{}.{t}", runnable.domain().name()),
94                Arc::clone(&runnable),
95            );
96        }
97        drop(by_command);
98        self.clone()
99    }
100
101    /// Commands executed in parallel (default 16).
102    pub fn concurrency(&self, commands: u32) -> Worker {
103        self.inner.settings.lock().unwrap().0 = commands;
104        self.clone()
105    }
106
107    /// Delay before reconnecting after the session ends (default 1 s); twice as long after each
108    /// further failed attempt, at most 30 s.
109    pub fn reconnect(&self, delay: Duration) -> Worker {
110        self.inner.settings.lock().unwrap().1 = delay;
111        self.clone()
112    }
113
114    /// Whether the first connect gets its own line (default); an app prints it in its overview.
115    pub(crate) fn announce(&self, announce: bool) {
116        self.inner.announce.store(announce, Ordering::SeqCst);
117    }
118
119    /// Returns once the kernel accepted the worker; waits forever if it never connects.
120    pub async fn ready(&self) {
121        let _ = self.inner.ready.subscribe().wait_for(|r| *r).await;
122    }
123
124    /// Ends `run`, also from another task.
125    pub fn stop(&self) {
126        self.inner.stopped.send_replace(true);
127    }
128
129    /// Processes commands until `stop()`, reconnecting when the session drops. A handler's
130    /// error or panic rejects that command (`handler_error`); it does not end `run`.
131    pub async fn run(&self) {
132        let mut stopped = self.inner.stopped.subscribe();
133        let base = self.inner.settings.lock().unwrap().1;
134        let Some(parts) =
135            crate::partitions_of(&self.inner.client, "worker", base, &mut stopped).await
136        else {
137            return;
138        };
139        if parts.len() > 1 || !parts[0].0.is_empty() {
140            // A session per partition: commands of every partition's tenants run here.
141            let children: Vec<Worker> = parts.into_iter().map(|(_, c)| self.on(c)).collect();
142            let this = self.clone();
143            let all = children.clone();
144            tokio::spawn(async move {
145                for child in &all {
146                    child.ready().await;
147                }
148                this.inner.ready.send_replace(true);
149            });
150            let stopping = {
151                let (this, all) = (self.clone(), children.clone());
152                tokio::spawn(async move {
153                    let _ = this.inner.stopped.subscribe().wait_for(|s| *s).await;
154                    for child in &all {
155                        child.stop();
156                    }
157                })
158            };
159            let running: Vec<_> = children
160                .into_iter()
161                .map(|child| tokio::spawn(async move { child.run_one().await }))
162                .collect();
163            for run in running {
164                let _ = run.await;
165            }
166            stopping.abort();
167            return;
168        }
169        self.run_one().await;
170    }
171
172    /// The session loop on this worker's one kernel (or one partition).
173    async fn run_one(&self) {
174        let mut stopped = self.inner.stopped.subscribe();
175        let mut attempt = 0;
176        while !*stopped.borrow() {
177            let connects = self.inner.connects.load(Ordering::SeqCst);
178            let session = self.session();
179            let result = tokio::select! {
180                result = session => result,
181                _ = stopped.wait_for(|s| *s) => return,
182            };
183            attempt = if self.inner.connects.load(Ordering::SeqCst) > connects {
184                1
185            } else {
186                attempt + 1
187            };
188            let base = self.inner.settings.lock().unwrap().1;
189            let log = &self.inner.client.log;
190            let delay = log::reconnecting(log, "worker", result.err().as_ref(), base, attempt);
191            tokio::select! {
192                () = tokio::time::sleep(delay) => {}
193                _ = stopped.wait_for(|s| *s) => return,
194            }
195        }
196    }
197
198    async fn session(&self) -> Result<(), BoxError> {
199        let client = &self.inner.client;
200        let (concurrency, _) = *self.inner.settings.lock().unwrap();
201        let by_command = self.inner.by_command.lock().unwrap().clone();
202        let (tx, rx) = mpsc::channel(1024);
203        let msg = |m: In| WorkerMessage { msg: Some(m) };
204        tx.send(msg(In::Register(Register {
205            worker_id: format!("rust-{}", std::process::id()),
206            key_id: client.key_id.clone(),
207            aggregates: aggregates(&by_command),
208            max_concurrency: concurrency,
209            event_schemas: event_schemas(&by_command),
210            protocol: PROTOCOL,
211            service: self.inner.service.clone(),
212            deployment: client.deployment.clone(),
213        })))
214        .await?;
215        let (at, channel) = client.channel();
216        let ended = |status: tonic::Status| {
217            client.ended(at, &status);
218            status
219        };
220        let mut inbound = WorkerGatewayClient::new(channel)
221            .session(client.request(ReceiverStream::new(rx)))
222            .await
223            .map_err(ended)?
224            .into_inner();
225        // A command this worker cannot read ends the session: it reconnects and is refused
226        // until it is updated.
227        let (fail, mut failed) = mpsc::channel::<String>(1);
228        // Executes whose history is still coming, by lease.
229        let mut partial: HashMap<String, proto::Execute> = HashMap::new();
230        loop {
231            let m = tokio::select! {
232                m = inbound.message() => m.map_err(ended)?,
233                Some(reason) = failed.recv() => return Err(reason.into()),
234            };
235            let Some(m) = m else {
236                return Ok(());
237            };
238            let x = match m.msg {
239                Some(Out::Challenge(c)) => {
240                    let sig = client.sign(&signing::challenge_message(&c.nonce)).sig;
241                    tx.send(msg(In::ChallengeResponse(ChallengeResponse { sig })))
242                        .await?;
243                    continue;
244                }
245                Some(Out::Registered(r)) => {
246                    if !r.reader_of.is_empty() {
247                        client.log.info("worker", || {
248                            format!(
249                                "connected to a reader: commands run on the writer ({}); this worker gets none here",
250                                r.reader_of
251                            )
252                        });
253                    }
254                    if self.inner.connects.fetch_add(1, Ordering::SeqCst) > 0 {
255                        client.log.info("worker", || "connected again".into());
256                    } else if self.inner.announce.load(Ordering::SeqCst) {
257                        let command_types: Vec<String> = by_command.keys().cloned().collect();
258                        client.log.info("worker", || {
259                            log::worker_connected(&client.log.peer, &command_types)
260                        });
261                    }
262                    self.inner.ready.send_replace(true);
263                    continue;
264                }
265                Some(Out::Execute(x)) => x,
266                // A long history comes in parts.
267                Some(Out::ExecuteMore(rest)) => {
268                    let Some(mut x) = partial.remove(&rest.lease_id) else {
269                        continue;
270                    };
271                    x.history.extend(rest.history);
272                    x.vault.extend(rest.vault);
273                    x.more = rest.more;
274                    x
275                }
276                None => continue,
277            };
278            if x.more {
279                partial.insert(x.lease_id.clone(), x);
280                continue;
281            }
282            let command = x.command.clone().unwrap_or_default();
283            let aggregate = by_command
284                .get(&format!("{}.{}", command.domain, command.command_type))
285                .filter(|a| a.name() == command.aggregate_type)
286                .cloned();
287            let (client, tx, fail) = (client.clone(), tx.clone(), fail.clone());
288            tokio::spawn(async move {
289                let outcome = match aggregate {
290                    Some(aggregate) => {
291                        let execute = x.clone();
292                        let running =
293                            tokio::task::spawn_blocking(move || aggregate.execute(&execute));
294                        // A handler cannot be stopped from outside; one that runs past
295                        // its lease at least shows.
296                        let lease =
297                            u64::try_from(x.deadline - crate::context::now_ms()).unwrap_or(0);
298                        let stream = format!(
299                            "{}.{} {}/{}",
300                            command.domain,
301                            command.command_type,
302                            command.aggregate_type,
303                            command.aggregate_id
304                        );
305                        let line = || {
306                            format!(
307                                "{stream} still running after its lease ended: the kernel \
308                                     gives it to another worker; is the handler stuck?"
309                            )
310                        };
311                        let finished = log::watched(
312                            &client.log,
313                            "worker",
314                            Duration::from_millis(lease),
315                            line,
316                            running,
317                        );
318                        match finished.await {
319                            Ok(outcome) => (x, outcome),
320                            // A panic outside the handlers' own guard (an eraser, say)
321                            // still answers the command.
322                            Err(e) => {
323                                let text = match e.try_into_panic() {
324                                    Ok(panic) => crate::domain::panic_text(panic.as_ref()),
325                                    Err(e) => e.to_string(),
326                                };
327                                (x, Err(Failure::Error(text)))
328                            }
329                        }
330                    }
331                    None => {
332                        let reason = Rejected::new(format!(
333                            "no handler for {} on {}.{}",
334                            command.command_type, command.domain, command.aggregate_type
335                        ))
336                        .code("unknown_command");
337                        (x, Err(Failure::Rejected(reason)))
338                    }
339                };
340                let reply = match reply(&client, outcome) {
341                    Ok(reply) => reply,
342                    Err(reason) => {
343                        client.log.error("worker", || reason.clone());
344                        let _ = fail.send(reason).await;
345                        return;
346                    }
347                };
348                client.log.debug("worker", || {
349                    let outcome = match &reply {
350                        In::Result(r) => Ok(r.events.len()),
351                        In::Rejection(r) => Err(r.reason.as_ref().map_or("", |r| r.code.as_str())),
352                        _ => Err(""),
353                    };
354                    log::command_done(
355                        &format!("{}.{}", command.domain, command.command_type),
356                        &command.aggregate_type,
357                        &command.aggregate_id,
358                        outcome,
359                    )
360                });
361                let _ = tx.send(msg(reply)).await;
362            });
363        }
364    }
365}
366
367/// The signed result or rejection for an executed command, or why the worker cannot read it.
368fn reply(
369    client: &Client,
370    (x, outcome): (proto::Execute, Result<crate::domain::Executed, Failure>),
371) -> Result<In, String> {
372    let cmd = x.command.unwrap_or_default();
373    let reason = match outcome {
374        Ok(done) => {
375            let snapshot = done.snapshot.map(|(version, schema, state)| {
376                let worker_sig =
377                    client.sign(&signing::snapshot_message(&cmd, version, &schema, &state));
378                Snapshot {
379                    version,
380                    schema,
381                    state,
382                    worker_sig: Some(worker_sig),
383                }
384            });
385            let worker_sig = client.sign(&signing::result_message(
386                &cmd,
387                x.expected_version,
388                &done.events,
389            ));
390            let index_sig = index_sig(
391                &cmd,
392                x.expected_version,
393                (&done.keys, &done.facts, &done.requires),
394                |m| client.sign(m),
395            );
396            return Ok(In::Result(proto::Result {
397                lease_id: x.lease_id,
398                events: done.events,
399                worker_sig: Some(worker_sig),
400                snapshot,
401                vault: done.vault,
402                keys: done.keys,
403                facts: done.facts,
404                requires: done.requires,
405                index_sig,
406            }));
407        }
408        Err(Failure::Schema(reason)) => return Err(reason),
409        Err(Failure::Rejected(r)) => r,
410        Err(Failure::Error(message)) => {
411            // An unexpected error's text may hold personal data or internals, and a rejection is
412            // kept for good: it says only that the handler failed; the log has the rest.
413            client.log.error("worker", || {
414                format!(
415                    "{}.{} {}/{} failed: {message}",
416                    cmd.domain, cmd.command_type, cmd.aggregate_type, cmd.aggregate_id
417                )
418            });
419            Rejected::new("handler failed").code("handler_error")
420        }
421    };
422    let reason = reason.to_wire();
423    let worker_sig = client.sign(&signing::rejection_message(&cmd.command_id, &reason));
424    Ok(In::Rejection(Rejection {
425        lease_id: x.lease_id,
426        reason: Some(reason),
427        worker_sig: Some(worker_sig),
428    }))
429}
430
431/// The signature over the unique keys, facts and requirements of a result for `cmd` at
432/// `expected_version`; none if it has none of them.
433fn index_sig(
434    cmd: &proto::Command,
435    expected_version: u64,
436    (keys, facts, requires): (&[proto::UniqueKey], &[String], &[proto::Requirement]),
437    sign: impl FnOnce(&[u8]) -> proto::Signature,
438) -> Option<proto::Signature> {
439    if keys.is_empty() && facts.is_empty() && requires.is_empty() {
440        return None;
441    }
442    Some(sign(&signing::index_message(
443        cmd,
444        expected_version,
445        keys,
446        facts,
447        requires,
448    )))
449}
450
451/// An aggregate's qualified type: `shop.Cart`.
452fn qualified(aggregate: &dyn Runnable) -> String {
453    format!("{}.{}", aggregate.domain().name(), aggregate.name())
454}
455
456/// The worker's aggregates with their qualified command types, as it registers them.
457fn aggregates(by_command: &HashMap<String, Arc<dyn Runnable>>) -> Vec<WorkerAggregate> {
458    let mut grouped: BTreeMap<String, Vec<String>> = BTreeMap::new();
459    for (command_type, aggregate) in by_command {
460        grouped
461            .entry(qualified(aggregate.as_ref()))
462            .or_default()
463            .push(command_type.clone());
464    }
465    grouped
466        .into_iter()
467        .map(|(aggregate_type, mut command_types)| {
468            command_types.sort();
469            WorkerAggregate {
470                aggregate_type,
471                command_types,
472            }
473        })
474        .collect()
475}
476
477/// The payload versions the worker writes, for every event type its aggregates know: those
478/// they apply and those their domains declare. Without a deployment the kernel refuses the
479/// worker if the store already holds a newer one; with one it rejects commands on aggregates
480/// holding a newer schema, or a type not listed here (`unknown_history`).
481fn event_schemas(by_command: &HashMap<String, Arc<dyn Runnable>>) -> Vec<EventSchema> {
482    let mut schemas = HashMap::new();
483    for aggregate in by_command.values() {
484        let domain = aggregate.domain();
485        for t in aggregate.event_types() {
486            schemas.insert(format!("{}.{t}", domain.name()), domain.schema_of(&t));
487        }
488    }
489    schemas
490        .into_iter()
491        .map(|(event_type, schema)| EventSchema { event_type, schema })
492        .collect()
493}
494
495#[cfg(test)]
496mod tests {
497    use serde::{Deserialize, Serialize};
498    use serde_json::{Value, json};
499
500    use super::*;
501    use crate::{NewEvent, Requirement, Unique, domain, domain::Runnable};
502
503    #[derive(Clone, Default, Serialize, Deserialize)]
504    struct Order {
505        number: Option<String>,
506        email: Option<String>,
507        customer: String,
508        open: bool,
509        paid: bool,
510    }
511
512    /// The index of a result is signed as the shared test vector `result_index` says: value
513    /// hashes, scopes and subjects of the keys in declaration order, the true facts, and the
514    /// requirements from the command's data.
515    #[test]
516    fn the_index_of_a_result_is_signed_as_the_test_vectors_say() {
517        let path = concat!(
518            env!("CARGO_MANIFEST_DIR"),
519            "/../../proto/test-vectors/signing.json"
520        );
521        let vectors: Value = serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap();
522        let vector = &vectors["result_index"];
523        let input = &vector["input"]["command"];
524        fn text(v: &Value) -> String {
525            v.as_str().unwrap().to_owned()
526        }
527
528        let orders = domain("orders");
529        let order = orders.aggregate("Order", Order::default());
530        order.apply("OrderPlaced", |s, d: Value, _evt, _ctx| {
531            *s = Order {
532                number: Some(text(&d["number"])),
533                email: Some(text(&d["email"])),
534                customer: text(&d["customerId"]),
535                open: true,
536                paid: true,
537            }
538        });
539        order.command("PlaceOrder", |_, d: Value, _cmd, _ctx| {
540            let placed = json!({ "number": "A-1001", "email": "max@example.com", "customerId": d["customerId"] });
541            Ok(vec![NewEvent::new("OrderPlaced", placed)])
542        });
543        order
544            .unique("number", |s| s.number.clone(), Unique::tenant())
545            .unique(
546                "email",
547                |s| s.email.clone(),
548                Unique::global().personal(|s: &Order| Some(s.customer.clone())),
549            )
550            .fact("open", |s| s.open)
551            .fact("closed", |s| !s.open)
552            .fact("paid", |s| s.paid)
553            .requires("PlaceOrder", |_, d: Value| {
554                [
555                    Requirement::new(
556                        "identity",
557                        "Customer",
558                        d["customerId"].as_str().unwrap(),
559                        "active",
560                    ),
561                    Requirement::by_key("funds", "Vehicle", "isin", "VEH-lyra", "woundUp").absent(),
562                ]
563            });
564
565        let cmd = proto::Command {
566            command_id: text(&input["command_id"]),
567            tenant_id: text(&input["tenant_id"]),
568            domain: text(&input["domain"]),
569            aggregate_type: text(&input["aggregate_type"]),
570            aggregate_id: text(&input["aggregate_id"]),
571            command_type: text(&input["command_type"]),
572            payload: hex::decode(text(&input["payload_hex"])).unwrap(),
573            ..Default::default()
574        };
575        let expected_version = vector["input"]["expected_version"].as_u64().unwrap();
576        let execute = proto::Execute {
577            command: Some(cmd.clone()),
578            expected_version,
579            ..Default::default()
580        };
581        let done = order
582            .execute(&execute)
583            .unwrap_or_else(|_| panic!("executes"));
584        let key = signing::signing_key_from_hex(&text(&vectors["key"]["seed"])).unwrap();
585        let mut signed = Vec::new();
586        let sig = index_sig(
587            &cmd,
588            expected_version,
589            (&done.keys, &done.facts, &done.requires),
590            |m| {
591                signed = m.to_vec();
592                signing::sign(&key, m)
593            },
594        )
595        .unwrap();
596        assert_eq!(hex::encode(&signed), text(&vector["message"]));
597        assert_eq!(hex::encode(&sig.sig), text(&vector["signature"]));
598
599        // Without keys, facts or requirements, a result has no index signature.
600        let none = index_sig(&cmd, expected_version, (&[], &[], &[]), |_| unreachable!());
601        assert!(none.is_none());
602    }
603
604    /// A worker lists every event type it knows: those its aggregates only apply (at 1 unless
605    /// declared), and those its domain declares, at the declared schema.
606    #[test]
607    fn the_event_schemas_list_applied_and_declared_types() {
608        let shop = domain("shop");
609        shop.event("ItemAdded", 2).upcast(1, |v| v);
610        shop.event("Noted", 3).upcast(1, |v| v).upcast(2, |v| v);
611        let cart = shop.aggregate("Cart", 0u32);
612        cart.apply("ItemAdded", |n, _: Value, _evt, _ctx| *n += 1);
613        cart.apply("Cleared", |n, _: Value, _evt, _ctx| *n = 0);
614        cart.command("Add", |_, _: Value, _cmd, _ctx| {
615            Ok(vec![NewEvent::new("ItemAdded", ())])
616        });
617        let mut by_command: HashMap<String, Arc<dyn Runnable>> = HashMap::new();
618        by_command.insert("shop.Add".into(), Arc::new(cart));
619        let mut schemas: Vec<(String, u32)> = event_schemas(&by_command)
620            .into_iter()
621            .map(|s| (s.event_type, s.schema))
622            .collect();
623        schemas.sort();
624        assert_eq!(
625            schemas,
626            [
627                ("shop.Cleared".to_owned(), 1),
628                ("shop.ItemAdded".to_owned(), 2),
629                ("shop.Noted".to_owned(), 3),
630            ]
631        );
632    }
633}