Skip to main content

kernable/
lib.rs

1//! kernable: write event-sourced business logic in Rust; the kernel does the rest.
2//!
3//! ```no_run
4//! use kernable::{Kernable, NewEvent, Options, Rejected, domain};
5//! use serde::{Deserialize, Serialize};
6//!
7//! #[derive(Clone, Default, Serialize, Deserialize)]
8//! struct Cart { items: u32, checked_out: bool }
9//!
10//! #[derive(Serialize, Deserialize)]
11//! struct AddItem { sku: String, qty: u32 }
12//!
13//! # async fn run() -> Result<(), kernable::BoxError> {
14//! let shop_domain = domain("shop");
15//! let cart_aggregate = shop_domain.aggregate("cart", Cart::default());
16//! cart_aggregate.apply("ItemAdded", |state, data: AddItem, _evt, _ctx| state.items += data.qty);
17//! cart_aggregate.command("AddItem", |state, data: AddItem, _cmd, _ctx| {
18//!     if state.checked_out {
19//!         return Err(Rejected::new("Cart is checked out"));
20//!     }
21//!     Ok(vec![NewEvent::new("ItemAdded", data)])
22//! });
23//! Kernable::new("app.key")?.worker(&cart_aggregate).run().await;
24//! # Ok(())
25//! # }
26//! ```
27
28mod app;
29mod context;
30mod data;
31mod domain;
32mod error;
33mod index;
34mod listener;
35mod log;
36mod messages;
37pub mod process;
38mod store;
39mod vault;
40mod worker;
41
42use std::{
43    collections::HashMap,
44    future::Future,
45    path::{Path, PathBuf},
46    sync::{Arc, RwLock},
47    time::{Duration, Instant, SystemTime, UNIX_EPOCH},
48};
49
50use ed25519_dalek::SigningKey;
51use kernable_core::{
52    PROTOCOL,
53    proto::{
54        self, ApplyRequest, Attribute, CancelRequest, Membership, ProcessActing,
55        ProcessRegistration, SubmitRequest, Wait as WireWait, cancel_result, command_result,
56        command_service_client::CommandServiceClient,
57        membership_service_client::MembershipServiceClient,
58        partition_service_client::PartitionServiceClient,
59        process_service_client::ProcessServiceClient, query_result,
60        query_service_client::QueryServiceClient,
61    },
62    signing, transport,
63};
64use serde::{Serialize, de::DeserializeOwned};
65use serde_json::Value;
66use tonic::{metadata::MetadataValue, transport::Channel};
67
68pub use app::{App, AppHandle};
69pub use context::{RequestContext, Timestamp};
70pub use data::{Cache, Data, Files, Listed, Listing};
71pub use domain::{
72    Aggregate, ApplyContext, CommandContext, CommandMeta, CommandSchema, Domain, EventMeta,
73    EventSchema, FoldEvent, NewEvent, QuerySchema, QueryTarget, State, domain,
74};
75pub use error::{BoxError, Error, Rejected};
76pub use index::{Index, Reindex, Requirement, Unique, UniqueKey, reindex_type};
77pub use kernable_core::transport::Tls;
78pub use kernable_sdk_macros::{command, event, query};
79pub use listener::{
80    Check, CheckKind, CheckOutcome, Listener, ListenerContext, ListenerHandle, MiddlewareOptions,
81    QueryContext, QueryMeta, StoredEventMeta, SubscribeOptions, Subscription, Target, When,
82};
83#[doc(hidden)]
84pub use messages::__private;
85pub use messages::{CommandType, EventType, Message, Of, QueryType, TypeKey};
86pub use process::Process;
87pub use store::Store;
88
89// The attributes name the crate `::kernable`; within it too (its tests).
90extern crate self as kernable;
91pub use worker::Worker;
92
93use context::{issued_now, random_id};
94use domain::{decode, encode};
95
96tokio::task_local! {
97    /// The name of the listener whose handler is running, for requests sent from it.
98    static HANDLING: String;
99}
100
101/// The listener whose handler runs this task, if any.
102fn handling() -> String {
103    HANDLING.try_with(Clone::clone).unwrap_or_default()
104}
105
106/// How to reach the kernel and as whom: the options of [`Kernable::new`], set with builder
107/// methods that each return the changed options.
108///
109/// `Options::default()` takes everything from the environment, else the defaults: the key from
110/// `KERNABLE_KEY`, else `app.key` in the current directory; the kernel from `KERNABLE_URL`,
111/// else `http://127.0.0.1:7233`; the grant from `KERNABLE_GRANT`, else the `.grant` file next
112/// to the key; the service from `KERNABLE_SERVICE`; the deployment from `KERNABLE_DEPLOYMENT`;
113/// TLS from `KERNABLE_TLS_CA`,
114/// `KERNABLE_TLS_CERT` and `KERNABLE_TLS_KEY`; the tenant `default`. A key file's path (`&str`,
115/// `String`, `&Path`, `PathBuf`) converts into options with only the key set, so
116/// `Kernable::new("app.key")` works too. Example:
117/// `Kernable::new(Options::new("shop.key").url("http://kernel:7233").service("shop"))?`.
118#[derive(Clone, Debug)]
119pub struct Options {
120    url: Option<String>,
121    key: Option<PathBuf>,
122    grant: Option<PathBuf>,
123    tenant: String,
124    service: Option<String>,
125    deployment: Option<String>,
126    context: RequestContext,
127    tls: Option<Tls>,
128    insecure: Option<bool>,
129    timeout: Duration,
130}
131
132/// How long a request waits, for the connection and the answer, unless told otherwise: above
133/// the kernel's own submit and settle timeouts.
134pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(60);
135
136/// Every option at its default: the key from `KERNABLE_KEY`, else `app.key` in the current
137/// directory; the service from `KERNABLE_SERVICE`, if set; the deployment from
138/// `KERNABLE_DEPLOYMENT`, if set; TLS from `KERNABLE_TLS_CA`, `KERNABLE_TLS_CERT` and
139/// `KERNABLE_TLS_KEY`, if set.
140impl Default for Options {
141    fn default() -> Options {
142        Options {
143            url: None,
144            key: None,
145            grant: None,
146            tenant: "default".into(),
147            service: None,
148            deployment: None,
149            context: RequestContext::default(),
150            tls: None,
151            insecure: None,
152            timeout: DEFAULT_TIMEOUT,
153        }
154    }
155}
156
157impl Options {
158    /// Options that sign with the key in the `.key` file at `key` (made with
159    /// `kernable keys new`), every other option at its default.
160    pub fn new(key: impl AsRef<Path>) -> Options {
161        Options {
162            key: Some(key.as_ref().to_owned()),
163            ..Options::default()
164        }
165    }
166
167    /// Kernel address: `http://host:port` (`host:port` works too) or, on Unix,
168    /// `unix:/path/to.sock`. For a pair of kernels with a standby, both, comma-separated
169    /// (`http://a:7233,http://b:7233`): the client turns to the other one when a kernel answers
170    /// `UNAVAILABLE` (a standby says `not_primary`) or cannot be reached. Default:
171    /// `KERNABLE_URL`, else `http://127.0.0.1:7233`, where `kernable start` listens.
172    pub fn url(mut self, url: impl Into<String>) -> Options {
173        self.url = Some(url.into());
174        self
175    }
176
177    /// The key's grant (`kernable grant`), sent with every call. Default: `KERNABLE_GRANT`, else
178    /// the `.grant` file next to the key file, if there is one.
179    pub fn grant(mut self, path: impl AsRef<Path>) -> Options {
180        self.grant = Some(path.as_ref().to_owned());
181        self
182    }
183
184    /// Default tenant for `submit`, `query`, files and the cache (default `default`).
185    pub fn tenant(mut self, tenant: impl Into<String>) -> Options {
186        self.tenant = tenant.into();
187        self
188    }
189
190    /// The service this process's workers and listeners belong to. The service's membership
191    /// (see [`Kernable::apply`]) decides what the kernel waits for: what it lists counts, the
192    /// service's other workers and listeners are dynamic, and only listeners it lists as
193    /// middlewares may check requests. Default: `KERNABLE_SERVICE`, else none (everything
194    /// registered counts).
195    pub fn service(mut self, service: impl Into<String>) -> Options {
196        self.service = Some(service.into());
197        self
198    }
199
200    /// The deployment of this process: the version of its code, e.g. `2026-11-11.1` or a commit
201    /// hash; 1 to 128 letters, digits, `-`, `_` and `.`. Its workers write it into every event
202    /// and get commands only while the service's membership names it (or names none); its read
203    /// models and middlewares run beside those of other deployments, each from its own
204    /// position, and its queries go to its own read models first. [`Kernable::apply`] names it
205    /// in the membership, so a rollback is starting the earlier code and applying again.
206    /// Default: `KERNABLE_DEPLOYMENT`, else none. An invalid one is [`Error::Config`] in
207    /// [`Kernable::new`].
208    pub fn deployment(mut self, deployment: impl Into<String>) -> Options {
209        self.deployment = Some(deployment.into());
210        self
211    }
212
213    /// Default request context, e.g. this service's identity; a request's own context replaces it.
214    pub fn context(mut self, context: RequestContext) -> Options {
215        self.context = context;
216        self
217    }
218
219    /// Mutual TLS for `host:port` URLs: the CA certificate and this process's certificate and key,
220    /// as paths of PEM files (`Tls { ca, cert, key }`, re-exported from the kernel's crate).
221    /// Default: `KERNABLE_TLS_CA`, `KERNABLE_TLS_CERT` and `KERNABLE_TLS_KEY`, if set (all three
222    /// or none).
223    pub fn tls(mut self, tls: Tls) -> Options {
224        self.tls = Some(tls);
225        self
226    }
227
228    /// Allows plain text to a kernel that is not on this machine. Without TLS, grants, signed
229    /// requests and vault values cross the network readable, so [`Kernable::new`] refuses such
230    /// a URL unless this is set. Default: `KERNABLE_INSECURE=1`, else not allowed.
231    pub fn insecure(mut self) -> Options {
232        self.insecure = Some(true);
233        self
234    }
235
236    /// How long a request (`submit`, `query`, files, cache, `apply`) waits in all: for the
237    /// connection, e.g. while the kernel restarts, and for its answer. Default 60 s. A
238    /// connection the network dropped silently is noticed within 40 s by keepalive pings, within
239    /// 4 s with several kernels (a pair), whose client then turns to the other.
240    /// A submit (by its command ID), a cancel, a query or a data or cache read (get, list) that
241    /// a kernel answers `UNAVAILABLE` (shutting down, handing over, a middleware or read model
242    /// not connected) is asked again with backoff within this time; any other request (a
243    /// write) may have run, and fails at once.
244    pub fn timeout(mut self, timeout: Duration) -> Options {
245        self.timeout = timeout;
246        self
247    }
248}
249
250/// The options for the key file at a path, with every other option at its default.
251impl From<&str> for Options {
252    fn from(key: &str) -> Options {
253        Options::new(key)
254    }
255}
256
257impl From<String> for Options {
258    fn from(key: String) -> Options {
259        Options::new(key)
260    }
261}
262
263impl From<&Path> for Options {
264    fn from(key: &Path) -> Options {
265        Options::new(key)
266    }
267}
268
269impl From<PathBuf> for Options {
270    fn from(key: PathBuf) -> Options {
271        Options::new(key)
272    }
273}
274
275/// The channels to the kernels at the URL: one, or the two kernels of a pair. Calls go to the
276/// current one; one that answers `UNAVAILABLE` (a standby says `not_primary`) or cannot be
277/// reached hands over to the next.
278pub(crate) struct Channels {
279    all: Vec<std::sync::Mutex<Channel>>,
280    /// Each channel's address and how to connect to it again (see [`Client::ended`]).
281    addresses: Vec<String>,
282    tls: Option<Tls>,
283    current: std::sync::atomic::AtomicUsize,
284    /// The newest position this client's own commands committed at on these kernels (one
285    /// partition): its queries wait for it, on whichever copy answers (read your writes).
286    seen: std::sync::atomic::AtomicU64,
287}
288
289/// What a client knows of the partitions: the map, read once (and again after a
290/// `wrong_partition`), and the channels to each partition.
291pub(crate) struct Partitions {
292    /// `None`: not read yet; `Some(None)`: the kernel serves every tenant.
293    map: tokio::sync::Mutex<Option<Option<proto::PartitionMap>>>,
294    channels: std::sync::Mutex<HashMap<String, Arc<Channels>>>,
295    tls: Option<Tls>,
296}
297
298/// The partitions of `client`, read again (backing off like a reconnect) while no kernel
299/// answers; `None` once `stopped`.
300pub(crate) async fn partitions_of(
301    client: &Client,
302    what: &str,
303    base: Duration,
304    stopped: &mut tokio::sync::watch::Receiver<bool>,
305) -> Option<Vec<(String, Client)>> {
306    let mut attempt = 0;
307    loop {
308        let read = tokio::select! {
309            read = client.partitions() => read,
310            _ = stopped.wait_for(|s| *s) => return None,
311        };
312        match read {
313            Ok(parts) => return Some(parts),
314            Err(status) => {
315                attempt += 1;
316                let error: BoxError = status.into();
317                let delay = log::reconnecting(&client.log, what, Some(&error), base, attempt);
318                tokio::select! {
319                    () = tokio::time::sleep(delay) => {}
320                    _ = stopped.wait_for(|s| *s) => return None,
321                }
322            }
323        }
324    }
325}
326
327/// The partition `map` assigns `tenant` to.
328pub(crate) fn partition_of<'a>(map: &'a proto::PartitionMap, tenant: &str) -> &'a str {
329    map.tenants
330        .iter()
331        .find(|t| t.tenant == tenant)
332        .map_or(map.default.as_str(), |t| t.partition.as_str())
333}
334
335/// Whether a kernel refused a call because its tenant is moving to another partition.
336pub(crate) fn moving(status: &tonic::Status) -> bool {
337    status.code() == tonic::Code::Unavailable && status.message().starts_with("moving")
338}
339
340/// How long a call waits for its tenant's move to end.
341const MOVE_WAIT: Duration = Duration::from_secs(30);
342
343/// Whether a kernel refused a call as one for a tenant of another partition.
344pub(crate) fn wrong_partition(status: &tonic::Status) -> bool {
345    status.code() == tonic::Code::FailedPrecondition
346        && status.message().starts_with("wrong_partition")
347}
348
349/// Channels to the kernel, this process's key and its grant: what every part needs to call.
350#[derive(Clone)]
351pub(crate) struct Client {
352    channels: Arc<Channels>,
353    parts: Arc<Partitions>,
354    key: Arc<SigningKey>,
355    key_id: String,
356    grant: Option<MetadataValue<tonic::metadata::Ascii>>,
357    log: log::Log,
358    timeout: Duration,
359    /// The deployment of this process ([`Options::deployment`]); empty if none.
360    deployment: String,
361}
362
363impl Client {
364    /// The partition map the first kernel holds, read once and again after `refresh`;
365    /// `None` if it serves every tenant.
366    pub(crate) async fn partition_map(
367        &self,
368        refresh: bool,
369    ) -> Result<Option<proto::PartitionMap>, tonic::Status> {
370        let mut held = self.parts.map.lock().await;
371        if refresh {
372            *held = None;
373        }
374        if let Some(map) = held.as_ref() {
375            return Ok(map.clone());
376        }
377        let request = proto::MapRequest { protocol: PROTOCOL };
378        let map = match self
379            .call_with(None, request, true, |channel, r| async move {
380                PartitionServiceClient::new(channel).map(r).await
381            })
382            .await
383        {
384            Ok(map) => Some(map),
385            Err(s) if matches!(s.code(), tonic::Code::NotFound | tonic::Code::Unimplemented) => {
386                None
387            }
388            Err(s) => return Err(s),
389        };
390        *held = Some(map.clone());
391        Ok(map)
392    }
393
394    /// This client on partition `name` of `map`.
395    fn on_partition(&self, map: &proto::PartitionMap, name: &str) -> Result<Client, tonic::Status> {
396        let partition = map
397            .partitions
398            .iter()
399            .find(|p| p.name == name)
400            .ok_or_else(|| {
401                tonic::Status::internal(format!("the partition map names no partition {name}"))
402            })?;
403        // `relay:<relay>/<copy>` is how partitions at other sites reach this one: not a client's way.
404        let own: Vec<&String> = partition
405            .addresses
406            .iter()
407            .filter(|a| !a.starts_with("relay:"))
408            .collect();
409        if own.is_empty() {
410            return Err(tonic::Status::unavailable(format!(
411                "partition {name} is reached only through a relay: a client needs one of its own addresses"
412            )));
413        }
414        let addresses = own.iter().map(|a| a.as_str()).collect::<Vec<_>>().join(",");
415        let mut cached = self.parts.channels.lock().unwrap();
416        let channels = match cached.get(&addresses) {
417            Some(channels) => Arc::clone(channels),
418            None => {
419                let all = own
420                    .iter()
421                    .map(|a| {
422                        transport::connect_lazy_among(a, self.parts.tls.as_ref(), own.len() > 1)
423                            .map(std::sync::Mutex::new)
424                            .map_err(|e| {
425                                tonic::Status::internal(format!("partition {name}, {a}: {e}"))
426                            })
427                    })
428                    .collect::<Result<Vec<_>, _>>()?;
429                let channels = Arc::new(Channels {
430                    all,
431                    addresses: own.iter().map(|a| a.to_string()).collect(),
432                    tls: self.parts.tls.clone(),
433                    current: Default::default(),
434                    seen: Default::default(),
435                });
436                cached.insert(addresses, Arc::clone(&channels));
437                channels
438            }
439        };
440        Ok(Client {
441            channels,
442            ..self.clone()
443        })
444    }
445
446    /// This client on `tenant`'s partition.
447    pub(crate) async fn for_tenant(&self, tenant: &str) -> Result<Client, tonic::Status> {
448        match self.partition_map(false).await? {
449            None => Ok(self.clone()),
450            Some(map) => {
451                let name = partition_of(&map, tenant).to_owned();
452                self.on_partition(&map, &name)
453            }
454        }
455    }
456
457    /// This client on the control partition, which takes memberships.
458    pub(crate) async fn control(&self) -> Result<Client, tonic::Status> {
459        match self.partition_map(false).await? {
460            None => Ok(self.clone()),
461            Some(map) => self.on_partition(&map, &map.control),
462        }
463    }
464
465    /// This client on every partition, by name; one, named `""`, without partitions.
466    pub(crate) async fn partitions(&self) -> Result<Vec<(String, Client)>, tonic::Status> {
467        match self.partition_map(false).await? {
468            None => Ok(vec![(String::new(), self.clone())]),
469            Some(map) => map
470                .partitions
471                .iter()
472                .map(|p| Ok((p.name.clone(), self.on_partition(&map, &p.name)?)))
473                .collect(),
474        }
475    }
476
477    /// `call` on `tenant`'s partition, sent anew after reading the map again on
478    /// `wrong_partition`, and while the tenant moves (`moving`, refused before it took effect)
479    /// for up to 30 s.
480    pub(crate) async fn routed<R, Fut>(
481        &self,
482        tenant: &str,
483        mut call: impl FnMut(Client) -> Fut,
484    ) -> Result<R, tonic::Status>
485    where
486        Fut: Future<Output = Result<R, tonic::Status>>,
487    {
488        let mut attempt = 0;
489        let deadline = Instant::now() + MOVE_WAIT;
490        let mut pause = Duration::from_millis(50);
491        loop {
492            let client = self.for_tenant(tenant).await?;
493            match call(client).await {
494                Err(status) if moving(&status) && Instant::now() + pause < deadline => {
495                    tokio::time::sleep(pause).await;
496                    pause = (pause * 2).min(Duration::from_secs(1));
497                }
498                Err(status) if attempt < 3 && wrong_partition(&status) => {
499                    attempt += 1;
500                    self.partition_map(true).await?;
501                }
502                result => return result,
503            }
504        }
505    }
506
507    /// The current channel, with its index for [`Client::ended`].
508    pub(crate) fn channel(&self) -> (usize, Channel) {
509        let at = self
510            .channels
511            .current
512            .load(std::sync::atomic::Ordering::SeqCst);
513        (at, self.channels.all[at].lock().unwrap().clone())
514    }
515
516    /// A call or stream on channel `at` ended with `status`: a kernel that is not the primary,
517    /// or cannot be reached, hands over to the next address. A refusal that a damaged
518    /// connection can cause (see [`stale_connection`]) replaces the channel's connection, so the
519    /// next call starts on a new one.
520    pub(crate) fn ended(&self, at: usize, status: &tonic::Status) -> bool {
521        if stale_connection(status)
522            && let Ok(fresh) = transport::connect_lazy_among(
523                &self.channels.addresses[at],
524                self.channels.tls.as_ref(),
525                self.channels.all.len() > 1,
526            )
527        {
528            *self.channels.all[at].lock().unwrap() = fresh;
529        }
530        let n = self.channels.all.len();
531        let away = status.code() == tonic::Code::Unavailable || not_connected(status);
532        if n > 1 && away {
533            let _ = self.channels.current.compare_exchange(
534                at,
535                (at + 1) % n,
536                std::sync::atomic::Ordering::SeqCst,
537                std::sync::atomic::Ordering::SeqCst,
538            );
539        }
540        n > 1 && away
541    }
542
543    /// A unary call of `message` (sent with the grant) through `call`. While the kernel cannot
544    /// be reached it waits and tries again, but only after failures to connect: the request
545    /// never left, so a write cannot run twice. With several addresses, it also tries the next
546    /// after `UNAVAILABLE` (a standby's `not_primary`; a resubmit is safe, as commands are
547    /// idempotent by ID). Gives up after `timeout` (default: the client's) in all. For calls
548    /// that are safe to repeat, use [`call_with`](Self::call_with).
549    async fn call<T: Clone, R, Fut>(
550        &self,
551        timeout: Option<Duration>,
552        message: T,
553        call: impl FnMut(Channel, tonic::Request<T>) -> Fut,
554    ) -> Result<R, tonic::Status>
555    where
556        Fut: Future<Output = Result<tonic::Response<R>, tonic::Status>>,
557    {
558        self.call_with(timeout, message, false, call).await
559    }
560
561    /// Like [`call`](Self::call); `idempotent` (a command, by its ID: the kernel answers a
562    /// resubmission with the stored result; a cancel; a query or another read), it also tries
563    /// again, with backoff until the deadline, when a kernel answers `UNAVAILABLE`, and for a
564    /// short while when the connection dropped with the request under way: whether it ran is
565    /// unknown, and running it again is safe.
566    async fn call_with<T: Clone, R, Fut>(
567        &self,
568        timeout: Option<Duration>,
569        message: T,
570        idempotent: bool,
571        mut call: impl FnMut(Channel, tonic::Request<T>) -> Fut,
572    ) -> Result<R, tonic::Status>
573    where
574        Fut: Future<Output = Result<tonic::Response<R>, tonic::Status>>,
575    {
576        let timeout = timeout.unwrap_or(self.timeout);
577        let deadline = Instant::now() + timeout;
578        let mut pause = Duration::from_millis(50);
579        // Since when the request may have reached a kernel that then went away: from then on it
580        // is tried again for a short while only (a handover, a switchover), not until the
581        // deadline (a crash the caller should hear of).
582        let mut dropped_at: Option<Instant> = None;
583        loop {
584            let left = deadline.saturating_duration_since(Instant::now());
585            let mut request = self.request(message.clone());
586            request.set_timeout(left);
587            let (at, channel) = self.channel();
588            let result = match tokio::time::timeout(left, call(channel, request)).await {
589                Ok(result) => result,
590                Err(_) => Err(tonic::Status::deadline_exceeded(format!(
591                    "no answer from the kernel within {} ms",
592                    timeout.as_millis()
593                ))),
594            };
595            match result {
596                Ok(response) => return Ok(response.into_inner()),
597                Err(status) if Instant::now() + pause < deadline && self.ended(at, &status) => {
598                    tokio::time::sleep(pause).await;
599                    pause = (pause * 2).min(MAX_PAUSE);
600                }
601                // A kernel that answers UNAVAILABLE (shutting down, handing over, a read model
602                // or middleware not connected yet) is asked again until the deadline, also at a
603                // single address; only an idempotent call, so a request that ran is never run a
604                // second time. A tenant that moves is waited for by `routed`, a dropped
605                // connection below.
606                Err(status)
607                    if idempotent
608                        && status.code() == tonic::Code::Unavailable
609                        && !moving(&status)
610                        && !dropped(&status)
611                        && !not_connected(&status)
612                        && Instant::now() + pause < deadline =>
613                {
614                    tokio::time::sleep(pause).await;
615                    pause = (pause * 2).min(MAX_PAUSE);
616                }
617                Err(status)
618                    if (not_connected(&status) || (idempotent && dropped(&status)))
619                        && Instant::now() + pause < deadline
620                        && dropped_at.is_none_or(|at| at.elapsed() < DROPPED_RETRY) =>
621                {
622                    if dropped(&status) {
623                        dropped_at.get_or_insert_with(Instant::now);
624                    }
625                    tokio::time::sleep(pause).await;
626                    pause = (pause * 2).min(MAX_PAUSE);
627                }
628                Err(status) if not_connected(&status) => {
629                    return Err(tonic::Status::deadline_exceeded(format!(
630                        "no connection to the kernel within {} ms: {}",
631                        timeout.as_millis(),
632                        status.message()
633                    )));
634                }
635                Err(status) => return Err(status),
636            }
637        }
638    }
639
640    /// `message` as a request that carries the grant.
641    fn request<T>(&self, message: T) -> tonic::Request<T> {
642        let mut request = tonic::Request::new(message);
643        if let Some(grant) = &self.grant {
644            request
645                .metadata_mut()
646                .insert("kernable-grant", grant.clone());
647        }
648        request
649    }
650
651    fn sign(&self, message: &[u8]) -> proto::Signature {
652        signing::sign(&self.key, message)
653    }
654}
655
656/// A connection to the kernel: submits commands, asks queries, and runs workers and listeners.
657/// Cloning gives another handle to the same connection.
658///
659/// The calls to the kernel are `async` and need a Tokio runtime (`#[tokio::main]`). Workers,
660/// listeners and apps run until stopped: `run().await` them, or `tokio::spawn` them and wait
661/// for `ready()`. Workers and listeners print connection lines to stderr up to the level
662/// `KERNABLE_LOG` names (`off`, `error`, `warn`, `info` (default), `debug`). Example:
663/// `let kernable = Kernable::new("app.key")?; let outcome =
664/// kernable.submit(Submit::new("shop", "cart", "c1", "AddItem").data(json!({ "qty": 2 }))).await?;`
665#[derive(Clone)]
666pub struct Kernable {
667    client: Client,
668    tenant: String,
669    context: RequestContext,
670    domains: Arc<RwLock<HashMap<String, Domain>>>,
671    /// The service of this process's workers and listeners; empty if none.
672    service: String,
673}
674
675impl Kernable {
676    /// A client for the kernel `options` names, or with only a key file's path, for the default
677    /// kernel; `Options::default()` takes everything from the environment (see [`Options`]). It
678    /// connects on first use and again after the connection drops. Needs a Tokio runtime.
679    /// [`Error::Config`] if the key, grant or TLS files cannot be read, only some of the TLS
680    /// variables are set, or the URL or the deployment is invalid. Example: `Kernable::new("app.key")?`.
681    pub fn new(options: impl Into<Options>) -> Result<Kernable, Error> {
682        let options = options.into();
683        let url = options
684            .url
685            .or_else(|| std::env::var("KERNABLE_URL").ok())
686            .unwrap_or_else(|| "http://127.0.0.1:7233".into());
687        let key_file = options
688            .key
689            .or_else(|| std::env::var_os("KERNABLE_KEY").map(PathBuf::from))
690            .unwrap_or_else(|| PathBuf::from("app.key"));
691        let key = signing::read_signing_key(&key_file)
692            .map_err(|e| Error::Config(format!("key {}: {e}", key_file.display())))?;
693        let explicit = options
694            .grant
695            .clone()
696            .or_else(|| std::env::var_os("KERNABLE_GRANT").map(PathBuf::from));
697        let grant_file = explicit
698            .clone()
699            .unwrap_or_else(|| key_file.with_extension("grant"));
700        let grant = if explicit.is_some() || grant_file.exists() {
701            let hex = std::fs::read_to_string(&grant_file)
702                .map_err(|e| Error::Config(format!("grant {}: {e}", grant_file.display())))?;
703            let mut grant: MetadataValue<tonic::metadata::Ascii> = hex
704                .trim()
705                .parse()
706                .map_err(|_| Error::Config(format!("grant {} is not hex", grant_file.display())))?;
707            // Sent in full with every request, never kept in HTTP/2's header table: a value
708            // damaged there would be read wrong for every later request on the connection,
709            // and a credential stays out of compression (CRIME-like attacks).
710            grant.set_sensitive(true);
711            Some(grant)
712        } else {
713            None
714        };
715        let tls = match options.tls {
716            Some(tls) => Some(tls),
717            None => tls_from_env()?,
718        };
719        let insecure = options
720            .insecure
721            .unwrap_or_else(|| std::env::var("KERNABLE_INSECURE").is_ok_and(|v| v == "1"));
722        if tls.is_none() && !insecure && !local(&url) {
723            return Err(Error::Config(format!(
724                "{url} is not on this machine: connect with TLS (Options::tls), or allow plain \
725                 text with Options::insecure"
726            )));
727        }
728        // A pair of kernels: several addresses, comma-separated. Its connections are pinged
729        // often, so one the network cut off ends within seconds and the client turns to the
730        // other kernel.
731        let urls: Vec<&str> = url
732            .split(',')
733            .map(str::trim)
734            .filter(|u| !u.is_empty())
735            .collect();
736        let several = urls.len() > 1;
737        let all = urls
738            .iter()
739            .map(|u| {
740                transport::connect_lazy_among(u, tls.as_ref(), several)
741                    .map(std::sync::Mutex::new)
742                    .map_err(|e| Error::Config(format!("kernel {u}: {e}")))
743            })
744            .collect::<Result<Vec<_>, _>>()?;
745        if all.is_empty() {
746            return Err(Error::Config("no kernel address".into()));
747        }
748        let channels = Arc::new(Channels {
749            all,
750            addresses: urls.iter().map(|u| u.to_string()).collect(),
751            tls: tls.clone(),
752            current: Default::default(),
753            seen: Default::default(),
754        });
755        let service = options
756            .service
757            .or_else(|| std::env::var("KERNABLE_SERVICE").ok())
758            .unwrap_or_default();
759        let deployment = options
760            .deployment
761            .or_else(|| std::env::var("KERNABLE_DEPLOYMENT").ok())
762            .unwrap_or_default();
763        check_deployment(&deployment)?;
764        let key_id = signing::key_id(&key.verifying_key());
765        let log = log::Log::new(&url, &key_file, &key_id);
766        // Whoever can read the key file can sign as this process.
767        #[cfg(unix)]
768        if let Ok(meta) = std::fs::metadata(&key_file) {
769            let mode = std::os::unix::fs::PermissionsExt::mode(&meta.permissions()) & 0o777;
770            if mode & 0o077 != 0 {
771                let path = key_file.display();
772                log.warn("key", || {
773                    format!("{path} can be read by other users (mode {mode:o}): chmod 600 {path}")
774                });
775            }
776        }
777        Ok(Kernable {
778            client: Client {
779                channels,
780                parts: Arc::new(Partitions {
781                    map: tokio::sync::Mutex::default(),
782                    channels: Default::default(),
783                    tls: tls.clone(),
784                }),
785                key_id,
786                key: Arc::new(key),
787                grant,
788                log,
789                timeout: options.timeout,
790                deployment,
791            },
792            tenant: options.tenant,
793            context: options.context,
794            domains: Arc::default(),
795            service,
796        })
797    }
798
799    /// Seals the vault fields of this domain's commands when submitting them (see
800    /// [`Domain::command`]) and sends the target of its queries asked by name (see
801    /// [`Domain::query`]). Returns another handle to this connection, so it chains:
802    /// `Kernable::new("app.key")?.with_domain(&shop_domain)`.
803    pub fn with_domain(&self, domain: &Domain) -> Kernable {
804        self.domains
805            .write()
806            .unwrap()
807            .insert(domain.name().to_owned(), domain.clone());
808        self.clone()
809    }
810
811    /// A worker that runs the commands of `aggregate`; add more with [`Worker::aggregate`]. It
812    /// belongs to this connection's service (see [`Options::service`]). Nothing runs until
813    /// [`Worker::run`] is awaited: `kernable.worker(&cart_aggregate).run().await`.
814    pub fn worker<S: State>(&self, aggregate: &Aggregate<S>) -> Worker {
815        Worker::new(self.client.clone(), self.service.clone()).aggregate(aggregate)
816    }
817
818    /// Runs `listener` (a read model or reactor of a domain) on this connection: the handle
819    /// processes its events with `run()`. Each call gives a new handle. The listener belongs to
820    /// this connection's service (see [`Options::service`]). Example:
821    /// `kernable.listener(&carts_readmodel).run().await`.
822    pub fn listener(&self, listener: &Listener) -> ListenerHandle {
823        ListenerHandle::new(self, listener, self.service.clone())
824    }
825
826    /// Files of the default tenant: bytes up to 16 MiB per key, kept by the kernel outside the
827    /// signed event log; see [`Files`]. Example:
828    /// `kernable.data().put("shop", "invoices/c1.pdf", bytes, "application/pdf").await?`.
829    pub fn data(&self) -> Files {
830        Files::new(
831            self.client.clone(),
832            self.tenant.clone(),
833            self.context.clone(),
834        )
835    }
836
837    /// The kernel's cache for the default tenant: values up to 1 MiB per key, optionally with a
838    /// TTL, lost when the kernel restarts; see [`Cache`]. Example:
839    /// `kernable.cache().set("shop", "rate:c1", "3", Some(Duration::from_secs(60))).await?`.
840    pub fn cache(&self) -> Cache {
841        Cache::new(
842            self.client.clone(),
843            self.tenant.clone(),
844            self.context.clone(),
845        )
846    }
847
848    /// Replaces the membership of a service (default: this connection's, see
849    /// [`Options::service`]): the workers, listeners and middlewares the kernel waits for, plus
850    /// free metadata. Apply it once per deploy (e.g. from a deploy script), not from every
851    /// process: the newest apply wins, and an older one that arrives late is refused. The key needs the `manage` grant for the service. A
852    /// middleware the new membership no longer lists stops checking. It names the deployment
853    /// that serves the service ([`Manifest::deployment`], default this connection's, see
854    /// [`Options::deployment`]): its workers run the commands and its read models answer. A
855    /// membership that names another deployment than the serving one switches to it as
856    /// [`Manifest::switch`] says: by default only once that deployment has caught up, refused
857    /// before with `not_caught_up`, and never back to one that served before (`served_before`;
858    /// [`Error::waits_for_switch`]). Example:
859    /// `kernable.apply(Manifest::new().service("shop").worker(&cart_aggregate).listener(&carts_readmodel)).await?`.
860    /// [`Error::Config`] if neither the manifest nor the connection names a service, or the
861    /// deployment is invalid, [`Error::Status`] if the kernel refuses it.
862    pub async fn apply(&self, manifest: Manifest) -> Result<(), Error> {
863        let service = manifest
864            .service
865            .clone()
866            .unwrap_or_else(|| self.service.clone());
867        if service.is_empty() {
868            return Err(Error::Config(
869                "apply needs a service: set it with Manifest::service or Options::service".into(),
870            ));
871        }
872        let deployment = manifest
873            .deployment
874            .clone()
875            .unwrap_or_else(|| self.client.deployment.clone());
876        check_deployment(&deployment)?;
877        let manifest_switch = manifest.switch;
878        let membership = membership(service, deployment, manifest, issued_now());
879        let sig = self.client.sign(&signing::membership_message(&membership));
880        let request = ApplyRequest {
881            membership: Some(membership),
882            sig: Some(sig),
883            protocol: PROTOCOL,
884            force: manifest_switch == Switch::Now,
885            no_switch: manifest_switch == Switch::Never,
886            no_rollback: manifest_switch == Switch::CaughtUp,
887        };
888        // The same membership again is fine (the kernel takes a retried deploy), so a request
889        // whose connection dropped, or a kernel starting, is asked again.
890        self.client
891            .control()
892            .await?
893            .call_with(None, request, true, |channel, r| async move {
894                MembershipServiceClient::new(channel).apply(r).await
895            })
896            .await?;
897        Ok(())
898    }
899
900    /// Registers a business process with the kernel (see [`process`]): its model, signed. The
901    /// kernel numbers the versions: a model equal to the newest version registers nothing
902    /// ([`process::Registered::new`] is `false`), a different one becomes the next version;
903    /// running cases finish on the version they started with. An app registers its domains'
904    /// processes itself ([`Kernable::app`]). The key needs the `process` grant for the process,
905    /// and `submit`, `query` and `listen` for the commands, queries and events it names.
906    /// [`Error::Config`] if the model is invalid ([`Process::model`]), [`Error::Status`] if the
907    /// kernel refuses it (`INVALID_ARGUMENT` names the step and why).
908    pub async fn register_process(&self, process: &Process) -> Result<process::Registered, Error> {
909        let model = serde_json::to_vec(&process.model()?)?;
910        let issued_at = issued_now();
911        let sig = self
912            .client
913            .sign(&signing::process_message(&model, issued_at));
914        let request = ProcessRegistration {
915            model,
916            issued_at,
917            sig: Some(sig),
918            protocol: PROTOCOL,
919        };
920        let registered = self
921            .client
922            .control()
923            .await?
924            .call(None, request, |channel, r| async move {
925                ProcessServiceClient::new(channel).register(r).await
926            })
927            .await?;
928        Ok(process::Registered {
929            name: registered.name,
930            version: registered.version,
931            new: registered.new,
932        })
933    }
934
935    /// Sets as whom the process `name` (qualified: `shop.fulfilment`) acts: the request context
936    /// its commands and queries carry (sender tenant, identity, session), instead of
937    /// `process:<name>`. The kernel keeps it with the process, replicated to every partition.
938    /// The kernable kit calls it for every process it gives an identity and an API key. Returns
939    /// whether it changed (`false`: it acted so already). The key needs the `process` grant for
940    /// the process; [`Error::Status`] if the kernel refuses (`NOT_FOUND`: no such process).
941    pub async fn process_act(&self, name: &str, context: RequestContext) -> Result<bool, Error> {
942        let context = context.to_wire();
943        let issued_at = issued_now();
944        let sig = self.client.sign(&signing::process_act_message(
945            name,
946            Some(&context),
947            issued_at,
948        ));
949        let request = ProcessActing {
950            name: name.to_owned(),
951            context: Some(context),
952            issued_at,
953            sig: Some(sig),
954            protocol: PROTOCOL,
955        };
956        let acted = self
957            .client
958            .control()
959            .await?
960            .call(None, request, |channel, r| async move {
961                ProcessServiceClient::new(channel).act(r).await
962            })
963            .await?;
964        Ok(acted.changed)
965    }
966
967    /// An app made of whole domains: [`AppHandle::run`] applies the service's membership (the
968    /// domains' aggregates as workers, their read models and reactors as listeners, those that
969    /// check requests as middlewares; live ones are not listed, and the metadata is `version`
970    /// and `description`, when given, then the app's other metadata; the domains' business
971    /// processes), then runs one worker for all the aggregates and every listener, live ones
972    /// too, all in the app's service, and registers the processes once the worker is ready
973    /// ([`Kernable::register_process`]; the key then needs the `process` grant for them).
974    ///
975    /// Example: `kernable.app(App::new().service("shop").version("1.0.0").domain(&shop_domain))?.run().await?`.
976    /// Every start applies the membership, so the key needs the `manage` grant for the service.
977    /// One service is one app: two processes with the same service would replace each other's
978    /// membership. [`Error::Config`] if neither the app nor the connection names a service.
979    pub fn app(&self, app: App) -> Result<AppHandle, Error> {
980        AppHandle::new(self, app)
981    }
982
983    /// Runs a command and returns its outcome: [`Outcome::Committed`] with the new events, or
984    /// [`Outcome::Rejected`] if a handler, a middleware or the kernel rejected it (a rejection
985    /// is `Ok`, not an error); the kernel rejects with `unknown_history` a command whose
986    /// aggregate holds events the serving deployment's worker does not know (after a
987    /// rollback, see [`Manifest::deployment`]). By default it waits until every listener that counts has processed the
988    /// events; see [`Submit::wait`]. [`Error::NotSettled`] if they did not in time (the
989    /// command is committed), [`Error::Status`] if the kernel refuses the call (no grant,
990    /// unknown aggregate type, timeout). Example: `kernable.submit(Submit::new("shop", "cart",
991    /// "c1", "AddItem").data(json!({ "sku": "apple", "qty": 2 }))).await?`.
992    ///
993    /// A scheduled command ([`Submit::at`]) has no outcome yet: enqueue it
994    /// ([`Kernable::enqueue`]); submitting it is [`Error::Config`]. Submitted again by its ID
995    /// without `at`, it waits for the scheduled command's outcome; [`Error::NotDue`] if the
996    /// kernel answers that it is not due yet.
997    pub async fn submit(&self, submit: Submit) -> Result<Outcome, Error> {
998        if submit.at.is_some() {
999            return Err(Error::Config(
1000                "a scheduled command (`at`) has no outcome yet: use `enqueue`".into(),
1001            ));
1002        }
1003        let wait = submit.wait;
1004        let res = self.send(submit, wait.wire()).await?;
1005        match res.outcome {
1006            Some(command_result::Outcome::Rejected(r)) => {
1007                Ok(Outcome::Rejected(Rejected::from_wire(r)))
1008            }
1009            Some(command_result::Outcome::Committed(c)) => {
1010                // Events come back with references only: the submitter is no vault reader.
1011                let events: Vec<StoredEvent> = c
1012                    .events
1013                    .into_iter()
1014                    .map(|e| StoredEvent::from_wire(e, &[]))
1015                    .collect();
1016                if wait == Wait::Settled && !c.settled {
1017                    return Err(Error::NotSettled(events));
1018                }
1019                Ok(Outcome::Committed(events))
1020            }
1021            Some(command_result::Outcome::Accepted(_)) => Err(Error::NotDue(res.command_id)),
1022            None => Err(Error::Status(tonic::Status::internal("no outcome"))),
1023        }
1024    }
1025
1026    /// Stores the command in the kernel's queue and returns its ID without waiting for it to
1027    /// run. Submit it again with the same `id` ([`Submit::id`]) to get the outcome; its `wait`
1028    /// is ignored. With [`Submit::at`], a scheduled command: it runs at that time, e.g. a
1029    /// reminder in 24 hours, `kernable.enqueue(Submit::command(Remind {}, "o1")
1030    /// .at(SystemTime::now() + Duration::from_secs(86_400))).await?`; cancel it with
1031    /// [`Kernable::cancel`].
1032    pub async fn enqueue(&self, submit: Submit) -> Result<String, Error> {
1033        Ok(self.send(submit, WireWait::Accepted).await?.command_id)
1034    }
1035
1036    /// Cancels a scheduled command ([`Submit::at`]) before it is due: it completes as rejected
1037    /// `cancelled`, which a submit of its ID answers from then on. Needs the `submit` grant for
1038    /// the command's type; middlewares check it as a cancel of that type ([`CheckKind::Cancel`]).
1039    /// Returns [`CancelOutcome::Cancelled`] (also when it was cancelled before), or
1040    /// [`CancelOutcome::Rejected`] with `too_late` (due, running or done already), `not_found`,
1041    /// or a middleware's code. Example: `kernable.cancel(Cancel::new(&id)).await?`.
1042    pub async fn cancel(&self, cancel: Cancel) -> Result<CancelOutcome, Error> {
1043        let mut request = CancelRequest {
1044            command_id: cancel.command_id,
1045            tenant_id: cancel.tenant.unwrap_or_else(|| self.tenant.clone()),
1046            context: Some(
1047                cancel
1048                    .context
1049                    .unwrap_or_else(|| self.context.clone())
1050                    .to_wire(),
1051            ),
1052            issued_at: issued_now(),
1053            client_sig: None,
1054            protocol: PROTOCOL,
1055        };
1056        request.client_sig = Some(self.client.sign(&signing::cancel_message(&request)));
1057        let tenant = request.tenant_id.clone();
1058        let timeout = cancel.timeout;
1059        let res = self
1060            .client
1061            .routed(&tenant, |client| {
1062                let request = request.clone();
1063                async move {
1064                    // Cancelling twice answers the same: safe to send again.
1065                    client
1066                        .call_with(timeout, request, true, |channel, r| async move {
1067                            CommandServiceClient::new(channel).cancel(r).await
1068                        })
1069                        .await
1070                }
1071            })
1072            .await?;
1073        match res.outcome {
1074            Some(cancel_result::Outcome::Cancelled(_)) => Ok(CancelOutcome::Cancelled),
1075            Some(cancel_result::Outcome::Rejected(r)) => {
1076                Ok(CancelOutcome::Rejected(Rejected::from_wire(r)))
1077            }
1078            None => Err(Error::Status(tonic::Status::internal("no outcome"))),
1079        }
1080    }
1081
1082    async fn send(&self, s: Submit, wait: WireWait) -> Result<proto::CommandResult, Error> {
1083        if s.until.is_some() && s.at.is_none() {
1084            return Err(Error::Config("`until` needs `at`".into()));
1085        }
1086        let command_id = s.id.unwrap_or_else(random_id);
1087        let vault = s.vault.clone().or_else(|| {
1088            self.domains
1089                .read()
1090                .unwrap()
1091                .get(&s.domain)
1092                .and_then(|d| d.command_vault(&s.command_type))
1093        });
1094        let sealed =
1095            vault::seal(&s.data, vault.as_ref(), &s.aggregate_id).map_err(Error::Config)?;
1096        let mut context = s.context.unwrap_or_else(|| self.context.clone());
1097        if context.correlation_id.is_empty() {
1098            context.correlation_id = command_id.clone();
1099        }
1100        let mut cmd = proto::Command {
1101            command_id,
1102            tenant_id: s.tenant.unwrap_or_else(|| self.tenant.clone()),
1103            domain: s.domain,
1104            aggregate_type: s.aggregate_type,
1105            aggregate_id: s.aggregate_id,
1106            command_type: s.command_type,
1107            payload: sealed.payload,
1108            client_sig: None,
1109            context: Some(context.to_wire()),
1110            vault_refs: sealed.refs,
1111            deliver_at: s.at.unwrap_or(0),
1112            deliver_until: s.until.unwrap_or(0),
1113        };
1114        cmd.client_sig = Some(self.client.sign(&signing::command_message(&cmd)));
1115        let request = SubmitRequest {
1116            command: Some(cmd),
1117            wait: wait.into(),
1118            protocol: PROTOCOL,
1119            vault: sealed.values,
1120            listener: handling(),
1121        };
1122        let tenant = request
1123            .command
1124            .as_ref()
1125            .map(|c| c.tenant_id.clone())
1126            .unwrap_or_default();
1127        let timeout = s.timeout;
1128        Ok(self
1129            .client
1130            .routed(&tenant, |client| {
1131                let request = request.clone();
1132                async move {
1133                    let result = client
1134                        .call_with(timeout, request, true, |channel, r| async move {
1135                            CommandServiceClient::new(channel).submit(r).await
1136                        })
1137                        .await?;
1138                    if let Some(command_result::Outcome::Committed(c)) = &result.outcome {
1139                        let last = c.events.last().map_or(0, |e| e.global_position);
1140                        client
1141                            .channels
1142                            .seen
1143                            .fetch_max(c.position.max(last), std::sync::atomic::Ordering::SeqCst);
1144                    }
1145                    Ok(result)
1146                }
1147            })
1148            .await?)
1149    }
1150
1151    /// Asks the read model that answers `domain.type` and returns its answer, deserialized as
1152    /// `T` (`serde_json::Value` for any). Queries always go through the kernel, also within one
1153    /// process. A refusal by the read model or a middleware is [`Error::Rejected`]; the
1154    /// kernel's own (no grant, no read model connected) is [`Error::Status`]; an answer that is
1155    /// not a `T` is [`Error::Json`]. Example: `let cart: Value =
1156    /// kernable.query(Query::new("shop", "GetCart").data(json!({ "id": "c1" }))).await?;`
1157    pub async fn query<T: DeserializeOwned>(&self, query: Query) -> Result<T, Error> {
1158        let declared = query.target.clone().or_else(|| {
1159            self.domains
1160                .read()
1161                .unwrap()
1162                .get(&query.domain)
1163                .and_then(|d| d.query_target(&query.query_type))
1164        });
1165        let target = declared.and_then(|t| t.wire(&query.domain, &query.data));
1166        let mut request = proto::QueryRequest {
1167            target,
1168            query_id: random_id(),
1169            tenant_id: query.tenant.unwrap_or_else(|| self.tenant.clone()),
1170            domain: query.domain,
1171            query_type: query.query_type,
1172            payload: encode(&query.data),
1173            context: Some(
1174                query
1175                    .context
1176                    .unwrap_or_else(|| self.context.clone())
1177                    .to_wire(),
1178            ),
1179            min_position: query.min_position,
1180            issued_at: issued_now(),
1181            client_sig: None,
1182            protocol: PROTOCOL,
1183            listener: String::new(),
1184            wait_only: false,
1185            deployment: self.client.deployment.clone(),
1186        };
1187        let timeout = query.timeout;
1188        if query.all_partitions {
1189            self.caught_up_everywhere(&request, timeout).await?;
1190            request.issued_at = issued_now();
1191        }
1192        let listener = handling();
1193        let tenant = request.tenant_id.clone();
1194        let res = self
1195            .client
1196            .routed(&tenant, |client| {
1197                let mut request = request.clone();
1198                // Read your writes, on whichever copy answers: the query waits for this client's
1199                // own newest command. Not from a handler, which must not wait behind its own
1200                // listener.
1201                if listener.is_empty() {
1202                    request.min_position = request.min_position.max(
1203                        client
1204                            .channels
1205                            .seen
1206                            .load(std::sync::atomic::Ordering::SeqCst),
1207                    );
1208                }
1209                request.client_sig = Some(client.sign(&signing::query_message(&request)));
1210                request.listener = listener.clone();
1211                async move {
1212                    client
1213                        .call_with(timeout, request, true, |channel, r| async move {
1214                            QueryServiceClient::new(channel).query(r).await
1215                        })
1216                        .await
1217                }
1218            })
1219            .await?;
1220        match res.outcome {
1221            Some(query_result::Outcome::Response(r)) => Ok(serde_json::from_value(decode(&r))?),
1222            Some(query_result::Outcome::Rejected(r)) => {
1223                Err(Error::Rejected(Rejected::from_wire(r)))
1224            }
1225            None => Err(Error::Status(tonic::Status::internal("no outcome"))),
1226        }
1227    }
1228
1229    /// Asks a query of a message type and returns its typed answer: `kernable.ask(GetOrder {
1230    /// id }, |q| q.tenant(t)).await?`; `options` sets what [`Query`]'s methods set.
1231    pub async fn ask<Q: QueryType>(
1232        &self,
1233        query: Q,
1234        options: impl FnOnce(Query) -> Query,
1235    ) -> Result<Q::Answer, Error> {
1236        self.query(options(Query::of(query))).await
1237    }
1238
1239    /// Returns once a read model that answers `query` has processed every partition's head, as
1240    /// of the call: a wait-only query to each partition, at the same time.
1241    async fn caught_up_everywhere(
1242        &self,
1243        query: &proto::QueryRequest,
1244        timeout: Option<Duration>,
1245    ) -> Result<(), Error> {
1246        let mut wait = proto::QueryRequest {
1247            wait_only: true,
1248            min_position: 0,
1249            payload: Vec::new(),
1250            ..query.clone()
1251        };
1252        wait.client_sig = Some(self.client.sign(&signing::query_message(&wait)));
1253        wait.listener = handling();
1254        let mut waits = tokio::task::JoinSet::new();
1255        for (_, client) in self.client.partitions().await? {
1256            let wait = wait.clone();
1257            waits.spawn(async move {
1258                client
1259                    .call_with(timeout, wait, true, |channel, r| async move {
1260                        QueryServiceClient::new(channel).query(r).await
1261                    })
1262                    .await
1263            });
1264        }
1265        while let Some(waited) = waits.join_next().await {
1266            waited.map_err(|e| Error::Status(tonic::Status::internal(e.to_string())))??;
1267        }
1268        Ok(())
1269    }
1270
1271    /// Streams committed events after `options.after` (backlog first, then live) to `handler`,
1272    /// one at a time. Reconnects and resumes after the last handled event; if the handler
1273    /// fails, that event is delivered again. Persist the position yourself to resume across
1274    /// restarts. Needs the `subscribe` grant for the types. Unlike a listener, a subscription is
1275    /// not registered with the kernel: nobody waits for it, and its events carry no vault values
1276    /// (vault fields are `null` and listed in `redacted`). It runs in a Tokio task from the
1277    /// call on; [`Subscription::stop`] ends it.
1278    pub fn subscribe<F, Fut>(&self, options: SubscribeOptions, handler: F) -> Subscription
1279    where
1280        F: Fn(StoredEvent) -> Fut + Send + Sync + 'static,
1281        Fut: Future<Output = Result<(), BoxError>> + Send + 'static,
1282    {
1283        Subscription::start(self.client.clone(), options, handler)
1284    }
1285}
1286
1287/// How long `submit` waits before it responds.
1288#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1289pub enum Wait {
1290    /// Until every listener has processed the events, so read models already show them
1291    /// (default); [`Error::NotSettled`] on timeout. From a listener's handler, only the
1292    /// listeners with a lower order count.
1293    #[default]
1294    Settled,
1295    /// Until the events are stored. To read them back, ask with [`Query::min_position`] set to
1296    /// the last event's position.
1297    Committed,
1298}
1299
1300impl Wait {
1301    fn wire(self) -> WireWait {
1302        match self {
1303            Wait::Settled => WireWait::Settled,
1304            Wait::Committed => WireWait::Committed,
1305        }
1306    }
1307}
1308
1309/// Mutual TLS from `KERNABLE_TLS_CA`, `KERNABLE_TLS_CERT` and `KERNABLE_TLS_KEY`: all or none.
1310fn tls_from_env() -> Result<Option<Tls>, Error> {
1311    let var = |name| std::env::var_os(name).map(PathBuf::from);
1312    match (
1313        var("KERNABLE_TLS_CA"),
1314        var("KERNABLE_TLS_CERT"),
1315        var("KERNABLE_TLS_KEY"),
1316    ) {
1317        (None, None, None) => Ok(None),
1318        (Some(ca), Some(cert), Some(key)) => Ok(Some(Tls { ca, cert, key })),
1319        _ => Err(Error::Config(
1320            "set all of KERNABLE_TLS_CA, KERNABLE_TLS_CERT and KERNABLE_TLS_KEY, or none".into(),
1321        )),
1322    }
1323}
1324
1325/// The membership `manifest` describes, for `service` and `deployment`.
1326fn membership(
1327    service: String,
1328    deployment: String,
1329    manifest: Manifest,
1330    issued_at: i64,
1331) -> Membership {
1332    Membership {
1333        service,
1334        workers: manifest.workers,
1335        listeners: manifest.listeners,
1336        middlewares: manifest.middlewares,
1337        metadata: manifest
1338            .metadata
1339            .into_iter()
1340            .map(|(key, value)| Attribute { key, value })
1341            .collect(),
1342        issued_at,
1343        processes: manifest.processes,
1344        deployment,
1345    }
1346}
1347
1348/// [`Error::Config`] unless `deployment` is empty or 1 to 128 letters, digits, `-`, `_` and `.`.
1349fn check_deployment(deployment: &str) -> Result<(), Error> {
1350    let valid = deployment.len() <= 128
1351        && deployment
1352            .chars()
1353            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'));
1354    if valid {
1355        Ok(())
1356    } else {
1357        Err(Error::Config(format!(
1358            "deployment {deployment:?}: use 1 to 128 letters, digits, `-`, `_` and `.`"
1359        )))
1360    }
1361}
1362
1363/// What a service consists of, for [`Kernable::apply`]; see `Membership` in kernable.proto.
1364/// Built with methods that each return the changed manifest:
1365/// `Manifest::new().service("shop").worker(&cart_aggregate).listener(&carts_readmodel).metadata("version", "1.0.0")`.
1366#[derive(Clone, Debug, Default, PartialEq, Eq)]
1367pub struct Manifest {
1368    service: Option<String>,
1369    workers: Vec<String>,
1370    listeners: Vec<String>,
1371    middlewares: Vec<String>,
1372    metadata: Vec<(String, String)>,
1373    processes: Vec<String>,
1374    deployment: Option<String>,
1375    switch: Switch,
1376}
1377
1378/// When a membership that names another deployment than the one serving its service switches
1379/// to it ([`Manifest::switch`], [`App::switch`]). See the how-to "Deployments and rollbacks".
1380#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1381pub enum Switch {
1382    /// Once the deployment has caught up (the default), and only to a deployment that never
1383    /// served before: its listed workers are connected and its read models within the kernel's
1384    /// `--deployment-switch-lag` of the newest event. Until then the kernel refuses it
1385    /// (`not_caught_up`); an app runs beside the serving deployment meanwhile and applies again
1386    /// until it switches. A deployment that served before (it wrote events) is never switched
1387    /// back to this way (`served_before`): its app runs beside, as with [`Switch::Never`],
1388    /// until an operator rolls back (`kernable apply --deployment`). So an older deployment's
1389    /// app that restarts during a rolling deploy does not take the service back.
1390    #[default]
1391    CaughtUp,
1392    /// At once, caught up or not (`kernable apply --force`).
1393    Now,
1394    /// Never by itself: the membership applies only while its deployment serves already (or
1395    /// the service has none yet); otherwise the kernel refuses it (`not_serving`). An app runs
1396    /// beside the serving deployment until an operator switches (`kernable apply --deployment`).
1397    Never,
1398}
1399
1400impl Switch {
1401    /// `KERNABLE_SWITCH`: `caught-up` (default), `now` or `never`.
1402    pub fn from_env() -> Result<Switch, Error> {
1403        match std::env::var("KERNABLE_SWITCH").as_deref() {
1404            Err(_) | Ok("" | "caught-up") => Ok(Switch::CaughtUp),
1405            Ok("now") => Ok(Switch::Now),
1406            Ok("never") => Ok(Switch::Never),
1407            Ok(other) => Err(Error::Config(format!(
1408                "KERNABLE_SWITCH={other}: caught-up, now or never"
1409            ))),
1410        }
1411    }
1412}
1413
1414impl Manifest {
1415    /// An empty manifest for the connection's service.
1416    pub fn new() -> Manifest {
1417        Manifest::default()
1418    }
1419
1420    /// The service it is for. Default: the connection's ([`Options::service`]).
1421    pub fn service(mut self, service: impl Into<String>) -> Manifest {
1422        self.service = Some(service.into());
1423        self
1424    }
1425
1426    /// An aggregate the service runs: the kernel waits for a worker of it and accepts its
1427    /// commands even before a worker registered it.
1428    pub fn worker<S: State>(mut self, aggregate: &Aggregate<S>) -> Manifest {
1429        self.workers.push(format!(
1430            "{}.{}",
1431            aggregate.domain().name(),
1432            aggregate.name()
1433        ));
1434        self
1435    }
1436
1437    /// A listener the kernel waits for; the service's other listeners count for nobody.
1438    pub fn listener(mut self, listener: &Listener) -> Manifest {
1439        self.listeners.push(listener.name().to_owned());
1440        self
1441    }
1442
1443    /// A listener of the service that may check requests; it counts like a listener.
1444    pub fn middleware(mut self, listener: &Listener) -> Manifest {
1445        self.middlewares.push(listener.name().to_owned());
1446        self
1447    }
1448
1449    /// A business process of the service ([`Domain::process`]): the kernel starts new cases of
1450    /// it while a membership lists it; one no longer listed starts none, its running cases
1451    /// finish. Register it too ([`Kernable::register_process`]); an app does both.
1452    pub fn process(mut self, process: &Process) -> Manifest {
1453        self.processes.push(process.name());
1454        self
1455    }
1456
1457    /// Free metadata, e.g. `("version", "1.0.0")`; kept in the order given.
1458    pub fn metadata(mut self, key: impl Into<String>, value: impl Into<String>) -> Manifest {
1459        self.metadata.push((key.into(), value.into()));
1460        self
1461    }
1462
1463    /// The deployment that serves the service: its workers run the commands, its listeners
1464    /// count and its read models answer queries first; the service's workers of other
1465    /// deployments get no commands, their read models keep catching up. A rollback applies a
1466    /// membership naming the earlier deployment. Default: the connection's
1467    /// ([`Options::deployment`]); empty: every deployment serves.
1468    pub fn deployment(mut self, deployment: impl Into<String>) -> Manifest {
1469        self.deployment = Some(deployment.into());
1470        self
1471    }
1472
1473    /// When it switches the service to its deployment if another one serves: see [`Switch`].
1474    /// Default [`Switch::CaughtUp`].
1475    pub fn switch(mut self, switch: Switch) -> Manifest {
1476        self.switch = switch;
1477        self
1478    }
1479}
1480
1481/// A command to submit with [`Kernable::submit`] or [`Kernable::enqueue`], built with methods
1482/// that each return the changed command:
1483/// `Submit::new("shop", "cart", "c1", "AddItem").data(json!({ "qty": 2 })).wait(Wait::Committed)`.
1484/// Without `data`, the payload is an empty object (`{}`).
1485#[derive(Clone, Debug)]
1486pub struct Submit {
1487    domain: String,
1488    aggregate_type: String,
1489    aggregate_id: String,
1490    command_type: String,
1491    data: Value,
1492    tenant: Option<String>,
1493    id: Option<String>,
1494    context: Option<RequestContext>,
1495    wait: Wait,
1496    timeout: Option<Duration>,
1497    /// A message type's vault fields, from its declaration.
1498    vault: Option<vault::VaultFields>,
1499    /// A scheduled command's delivery time and expiry, ms since epoch.
1500    at: Option<i64>,
1501    until: Option<i64>,
1502}
1503
1504impl Submit {
1505    /// A `command_type` command of `domain` for the aggregate `aggregate_type` with ID
1506    /// `aggregate_id`.
1507    pub fn new(
1508        domain: &str,
1509        aggregate_type: &str,
1510        aggregate_id: &str,
1511        command_type: &str,
1512    ) -> Submit {
1513        Submit {
1514            domain: domain.to_owned(),
1515            aggregate_type: aggregate_type.to_owned(),
1516            aggregate_id: aggregate_id.to_owned(),
1517            command_type: command_type.to_owned(),
1518            data: Value::Null,
1519            tenant: None,
1520            id: None,
1521            context: None,
1522            wait: Wait::Settled,
1523            timeout: None,
1524            vault: None,
1525            at: None,
1526            until: None,
1527        }
1528    }
1529
1530    /// A command of a message type (see [`command`]) for the aggregate with ID `aggregate_id`:
1531    /// its type says the domain, the aggregate type and the vault fields.
1532    /// `Submit::command(PlaceOrder { customer_id }, "o1").tenant(t)`.
1533    ///
1534    /// # Panics
1535    ///
1536    /// If `command` cannot be represented as JSON.
1537    pub fn command<C: CommandType>(command: C, aggregate_id: &str) -> Submit {
1538        let vault = messages::domain_of::<C>().command_vault(C::TYPE);
1539        Submit {
1540            vault,
1541            ..Submit::new(C::DOMAIN, C::AGGREGATE, aggregate_id, C::TYPE).data(command)
1542        }
1543    }
1544
1545    /// The command's data.
1546    ///
1547    /// # Panics
1548    ///
1549    /// If `data` cannot be represented as JSON.
1550    pub fn data(mut self, data: impl Serialize) -> Submit {
1551        self.data = serde_json::to_value(data).expect("command data is JSON");
1552        self
1553    }
1554
1555    /// The tenant to submit to. Default: the connection's ([`Options::tenant`]).
1556    pub fn tenant(mut self, tenant: impl Into<String>) -> Submit {
1557        self.tenant = Some(tenant.into());
1558        self
1559    }
1560
1561    /// Idempotency key (default: a new UUID); resubmitting the same ID returns the original
1562    /// outcome without running the command again.
1563    pub fn id(mut self, id: impl Into<String>) -> Submit {
1564        self.id = Some(id.into());
1565        self
1566    }
1567
1568    /// Replaces the client's default context; inside a listener, pass `ctx.follow()`.
1569    pub fn context(mut self, context: RequestContext) -> Submit {
1570        self.context = Some(context);
1571        self
1572    }
1573
1574    /// [`Kernable::enqueue`] only: a scheduled command, run at `time` and not before. The kernel
1575    /// stores it at once; the aggregate's other commands pass meanwhile, and middlewares check
1576    /// it now and again when it is due. At most the kernel's `--schedule-max-days` (default 366)
1577    /// ahead. Cancel it with [`Kernable::cancel`].
1578    pub fn at(mut self, time: SystemTime) -> Submit {
1579        self.at = Some(millis(time));
1580        self
1581    }
1582
1583    /// With [`Submit::at`]: if the command cannot run by `time` (after an outage, say), it is
1584    /// rejected `expired` instead of running late. Without `at`, submitting or enqueueing it is
1585    /// [`Error::Config`].
1586    pub fn until(mut self, time: SystemTime) -> Submit {
1587        self.until = Some(millis(time));
1588        self
1589    }
1590
1591    /// How long [`Kernable::submit`] waits: [`Wait::Settled`] (default) or [`Wait::Committed`].
1592    pub fn wait(mut self, wait: Wait) -> Submit {
1593        self.wait = wait;
1594        self
1595    }
1596
1597    /// How long to wait for the connection and the outcome; default [`Options::timeout`].
1598    pub fn timeout(mut self, timeout: Duration) -> Submit {
1599        self.timeout = Some(timeout);
1600        self
1601    }
1602}
1603
1604/// Milliseconds since the epoch; 0 before it.
1605fn millis(time: SystemTime) -> i64 {
1606    time.duration_since(UNIX_EPOCH)
1607        .map_or(0, |d| i64::try_from(d.as_millis()).unwrap_or(i64::MAX))
1608}
1609
1610/// A cancel of a scheduled command for [`Kernable::cancel`], built with methods that each
1611/// return the changed cancel: `Cancel::new(&id).tenant("t1")`.
1612#[derive(Clone, Debug)]
1613pub struct Cancel {
1614    command_id: String,
1615    tenant: Option<String>,
1616    context: Option<RequestContext>,
1617    timeout: Option<Duration>,
1618}
1619
1620impl Cancel {
1621    /// A cancel of the scheduled command `command_id` (the ID [`Kernable::enqueue`] returned).
1622    pub fn new(command_id: &str) -> Cancel {
1623        Cancel {
1624            command_id: command_id.to_owned(),
1625            tenant: None,
1626            context: None,
1627            timeout: None,
1628        }
1629    }
1630
1631    /// The command's tenant. Default: the connection's ([`Options::tenant`]).
1632    pub fn tenant(mut self, tenant: impl Into<String>) -> Cancel {
1633        self.tenant = Some(tenant.into());
1634        self
1635    }
1636
1637    /// Replaces the client's default context: who cancels, for the middlewares.
1638    pub fn context(mut self, context: RequestContext) -> Cancel {
1639        self.context = Some(context);
1640        self
1641    }
1642
1643    /// How long to wait for the connection and the answer; default [`Options::timeout`].
1644    pub fn timeout(mut self, timeout: Duration) -> Cancel {
1645        self.timeout = Some(timeout);
1646        self
1647    }
1648}
1649
1650/// What became of a cancel, returned by [`Kernable::cancel`].
1651#[derive(Clone, Debug, PartialEq)]
1652pub enum CancelOutcome {
1653    /// The scheduled command will not run: it completed as rejected `cancelled`.
1654    Cancelled,
1655    /// Not cancelled: `too_late` (due, running or done already), `not_found`, or a
1656    /// middleware's rejection.
1657    Rejected(Rejected),
1658}
1659
1660impl CancelOutcome {
1661    /// Whether the command was cancelled.
1662    pub fn is_cancelled(&self) -> bool {
1663        matches!(self, CancelOutcome::Cancelled)
1664    }
1665}
1666
1667/// A query to ask with [`Kernable::query`], built with methods that each return the changed
1668/// query: `Query::new("shop", "GetCart").data(json!({ "id": "c1" }))`. Without `data`, the
1669/// query's data is an empty object (`{}`).
1670#[derive(Clone, Debug)]
1671pub struct Query {
1672    domain: String,
1673    query_type: String,
1674    data: Value,
1675    tenant: Option<String>,
1676    context: Option<RequestContext>,
1677    min_position: u64,
1678    timeout: Option<Duration>,
1679    all_partitions: bool,
1680    /// A message type's target, from its declaration.
1681    target: Option<QueryTarget>,
1682}
1683
1684impl Query {
1685    /// A `query_type` query of `domain`.
1686    pub fn new(domain: &str, query_type: &str) -> Query {
1687        Query {
1688            domain: domain.to_owned(),
1689            query_type: query_type.to_owned(),
1690            data: Value::Null,
1691            tenant: None,
1692            context: None,
1693            min_position: 0,
1694            timeout: None,
1695            all_partitions: false,
1696            target: None,
1697        }
1698    }
1699
1700    /// A query of a message type (see [`query`]); its type says the domain and the aggregate it
1701    /// is about. Ask it with [`Kernable::ask`] for its typed answer.
1702    ///
1703    /// # Panics
1704    ///
1705    /// If `query` cannot be represented as JSON.
1706    pub fn of<Q: QueryType>(query: Q) -> Query {
1707        let target = messages::domain_of::<Q>().query_target(Q::TYPE);
1708        Query {
1709            target,
1710            ..Query::new(Q::DOMAIN, Q::TYPE).data(query)
1711        }
1712    }
1713
1714    /// The query's data.
1715    ///
1716    /// # Panics
1717    ///
1718    /// If `data` cannot be represented as JSON.
1719    pub fn data(mut self, data: impl Serialize) -> Query {
1720        self.data = serde_json::to_value(data).expect("query data is JSON");
1721        self
1722    }
1723
1724    /// The tenant to ask in. Default: the connection's ([`Options::tenant`]).
1725    pub fn tenant(mut self, tenant: impl Into<String>) -> Query {
1726        self.tenant = Some(tenant.into());
1727        self
1728    }
1729
1730    /// Replaces the client's default context.
1731    pub fn context(mut self, context: RequestContext) -> Query {
1732        self.context = Some(context);
1733        self
1734    }
1735
1736    /// Answer only after the read model has processed this global position (e.g. of a
1737    /// committed submit).
1738    pub fn min_position(mut self, position: u64) -> Query {
1739        self.min_position = position;
1740        self
1741    }
1742
1743    /// How long to wait for the connection and the answer; default [`Options::timeout`].
1744    pub fn timeout(mut self, timeout: Duration) -> Query {
1745        self.timeout = Some(timeout);
1746        self
1747    }
1748
1749    /// For a read model across tenants with partitions: answer only once the read model has
1750    /// processed every partition's events up to the query, not only those of the tenant's
1751    /// partition. Costs a wait-only query to each partition first.
1752    pub fn all_partitions(mut self) -> Query {
1753        self.all_partitions = true;
1754        self
1755    }
1756}
1757
1758/// What became of a command, returned by [`Kernable::submit`].
1759#[derive(Clone, Debug, PartialEq)]
1760pub enum Outcome {
1761    /// The command's events are stored, in order. Vault fields in them are `null` (see
1762    /// [`StoredEvent::redacted`]).
1763    Committed(Vec<StoredEvent>),
1764    /// A handler, a middleware or the kernel rejected the command; nothing was stored but the
1765    /// rejection.
1766    Rejected(Rejected),
1767}
1768
1769impl Outcome {
1770    /// Whether the command was committed.
1771    pub fn is_committed(&self) -> bool {
1772        matches!(self, Outcome::Committed(_))
1773    }
1774
1775    /// The committed events; none if the command was rejected.
1776    pub fn events(&self) -> &[StoredEvent] {
1777        match self {
1778            Outcome::Committed(events) => events,
1779            Outcome::Rejected(_) => &[],
1780        }
1781    }
1782}
1783
1784/// What became of a query, as a middleware that runs after requests gets it
1785/// ([`CheckOutcome::Query`]): its response data or why it was rejected.
1786#[derive(Clone, Debug, PartialEq)]
1787pub enum QueryOutcome {
1788    /// The read model's answer.
1789    Answered(Value),
1790    /// The read model or a middleware rejected the query.
1791    Rejected(Rejected),
1792}
1793
1794impl QueryOutcome {
1795    /// Whether the read model answered.
1796    pub fn is_answered(&self) -> bool {
1797        matches!(self, QueryOutcome::Answered(_))
1798    }
1799}
1800
1801/// An event as stored by the kernel: in an [`Outcome`] and in a [`Kernable::subscribe`]
1802/// handler.
1803#[derive(Clone, Debug, PartialEq)]
1804pub struct StoredEvent {
1805    /// Global position of the event in the kernel's log.
1806    pub position: u64,
1807    pub tenant: String,
1808    /// Always the domain of the command that caused the event.
1809    pub domain: String,
1810    pub aggregate_type: String,
1811    pub aggregate_id: String,
1812    /// The aggregate's version after this event: 1 for its first event.
1813    pub version: u64,
1814    /// The event type within the domain, e.g. `ItemAdded`.
1815    pub event_type: String,
1816    /// Version of the payload format. Listeners get `data` upcast to the version they know
1817    /// (see [`Domain::event`]), unless the handler is raw.
1818    pub schema: u32,
1819    /// The payload; [`StoredEvent::parse`] deserializes it.
1820    pub data: Value,
1821    /// Fields kept in the vault whose value is not here (`null` in `data`): erased, or not
1822    /// readable with this key (granted `vault_read`).
1823    pub redacted: Vec<String>,
1824    /// The command that caused the event.
1825    pub command_id: String,
1826    /// When the kernel committed the event.
1827    pub created_at: Timestamp,
1828    /// The request context of the command that caused the event.
1829    pub request: RequestContext,
1830    /// The code version of the worker that wrote it ([`Options::deployment`]); empty if none.
1831    pub deployment: String,
1832}
1833
1834impl StoredEvent {
1835    /// `data` as a `D`, e.g. `let item: ItemAdded = event.parse()?;`.
1836    pub fn parse<D: DeserializeOwned>(&self) -> Result<D, serde_json::Error> {
1837        serde_json::from_value(self.data.clone())
1838    }
1839
1840    pub(crate) fn from_wire(e: proto::Event, vault: &[proto::VaultValue]) -> StoredEvent {
1841        let (data, redacted) = vault::unseal(decode(&e.payload), vault);
1842        StoredEvent {
1843            position: e.global_position,
1844            tenant: e.tenant_id,
1845            domain: e.domain,
1846            aggregate_type: e.aggregate_type,
1847            aggregate_id: e.aggregate_id,
1848            version: e.version,
1849            event_type: e.event_type,
1850            schema: e.schema,
1851            data,
1852            redacted,
1853            command_id: e.command_id,
1854            created_at: Timestamp(e.created_at),
1855            request: RequestContext::from_wire(e.context.as_ref()),
1856            deployment: e.deployment,
1857        }
1858    }
1859}
1860
1861/// Whether `status` says the connection could not be made: the request was not sent.
1862/// Whether the connection dropped with the request under way (a kernel that stopped or handed
1863/// its stores over, a proxy that closed): unknown whether it ran.
1864fn dropped(status: &tonic::Status) -> bool {
1865    use std::io::ErrorKind::{BrokenPipe, ConnectionAborted, ConnectionReset, UnexpectedEof};
1866    // tonic says Cancelled for a stream the connection's end reset under way (h2), with
1867    // the connection's error in the message; a call the caller cancelled names none.
1868    if !matches!(
1869        status.code(),
1870        tonic::Code::Unknown
1871            | tonic::Code::Unavailable
1872            | tonic::Code::Internal
1873            | tonic::Code::Cancelled
1874    ) {
1875        return false;
1876    }
1877    let mut source = std::error::Error::source(status);
1878    while let Some(e) = source {
1879        if let Some(io) = e.downcast_ref::<std::io::Error>()
1880            && matches!(
1881                io.kind(),
1882                ConnectionReset | ConnectionAborted | BrokenPipe | UnexpectedEof
1883            )
1884        {
1885            return true;
1886        }
1887        source = e.source();
1888    }
1889    let message = status.message();
1890    message.contains("transport error")
1891        || message.contains("connection closed")
1892        || message.contains("error reading a body from connection")
1893        || message.contains("h2 protocol error")
1894        // hyper: the request never went out, its connection had closed (net-reset in the soak).
1895        || message.contains("operation was canceled")
1896}
1897
1898/// Whether `status` is a refusal a damaged connection can cause, which then repeats for every
1899/// request on it: HTTP/2 keeps headers it saw in a table both sides share, so the grant, the
1900/// same in every request, damaged on the way stays wrong there. The credentials refused
1901/// (UNAUTHENTICATED, or the grant unreadable or for another key); a right refusal of this kind
1902/// costs only a new connection. (UNIMPLEMENTED, a damaged method path, is left out: an older
1903/// kernel answers it for good.)
1904pub(crate) fn stale_connection(status: &tonic::Status) -> bool {
1905    match status.code() {
1906        tonic::Code::Unauthenticated => true,
1907        tonic::Code::InvalidArgument | tonic::Code::PermissionDenied => {
1908            status.message().contains("grant")
1909        }
1910        _ => false,
1911    }
1912}
1913
1914fn not_connected(status: &tonic::Status) -> bool {
1915    use std::io::ErrorKind::{AddrNotAvailable, ConnectionRefused, NotFound, TimedOut};
1916    let mut source = std::error::Error::source(status);
1917    while let Some(e) = source {
1918        if let Some(io) = e.downcast_ref::<std::io::Error>() {
1919            return matches!(
1920                io.kind(),
1921                ConnectionRefused | NotFound | AddrNotAvailable | TimedOut
1922            );
1923        }
1924        if e.to_string().contains("error trying to connect") {
1925            return true;
1926        }
1927        source = e.source();
1928    }
1929    false
1930}
1931
1932/// Whether `url` (every address of a comma-separated list) is a Unix socket or a loopback
1933/// address: plain text never leaves the machine.
1934fn local(url: &str) -> bool {
1935    if url.contains(',') {
1936        return url.split(',').all(|u| local(u.trim()));
1937    }
1938    if url.starts_with("unix:") {
1939        return true;
1940    }
1941    let host = transport::tcp_addr(url);
1942    let host = host.rsplit_once(':').map_or(host, |(host, port)| {
1943        if port.chars().all(|c| c.is_ascii_digit()) {
1944            host
1945        } else {
1946            url
1947        }
1948    });
1949    let host = host.trim_start_matches('[').trim_end_matches(']');
1950    host == "localhost"
1951        || host == "::1"
1952        || host.strip_prefix("127.").is_some_and(|rest| {
1953            rest.split('.').count() == 3 && rest.split('.').all(|p| p.parse::<u8>().is_ok())
1954        })
1955}
1956
1957/// The longest pause between tries of a call while the kernel is away: a pair's switchover or a
1958/// kernel update takes a few hundred milliseconds, and the client finds the kernel serving again
1959/// within this much of it.
1960const MAX_PAUSE: Duration = Duration::from_millis(200);
1961
1962/// How long a submit whose connection dropped under way is tried again: long enough for a
1963/// kernel handing its stores to a new binary or its role to a standby (a few hundred
1964/// milliseconds), short enough that a crash reaches the caller.
1965const DROPPED_RETRY: Duration = Duration::from_secs(5);
1966
1967#[cfg(test)]
1968mod dropped_tests {
1969    use super::*;
1970
1971    #[test]
1972    fn a_connection_that_dropped_under_way_counts_as_dropped_and_nothing_else_does() {
1973        assert!(dropped(&tonic::Status::unknown("transport error")));
1974        assert!(dropped(&tonic::Status::unavailable(
1975            "h2 protocol error: error reading a body from connection"
1976        )));
1977        // As a kernel killed under a call left it (soak, a primary's kernel killed).
1978        assert!(dropped(&tonic::Status::cancelled(
1979            "h2 protocol error: error reading a body from connection"
1980        )));
1981        assert!(dropped(&tonic::Status::cancelled("operation was canceled")));
1982        assert!(!dropped(&tonic::Status::cancelled("Timeout expired")));
1983        assert!(!dropped(&tonic::Status::unknown("a worker's error")));
1984        assert!(!dropped(&tonic::Status::invalid_argument(
1985            "transport error"
1986        )));
1987        assert!(!dropped(&tonic::Status::deadline_exceeded(
1988            "transport error"
1989        )));
1990    }
1991}
1992
1993#[cfg(test)]
1994mod deployment_tests {
1995    use serde_json::Value;
1996
1997    use super::*;
1998
1999    /// A membership with a deployment is signed as the shared test vector
2000    /// `membership_deployment` says.
2001    #[test]
2002    fn a_membership_with_a_deployment_is_signed_as_the_test_vectors_say() {
2003        let path = concat!(
2004            env!("CARGO_MANIFEST_DIR"),
2005            "/../../proto/test-vectors/signing.json"
2006        );
2007        let vectors: Value = serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap();
2008        let vector = &vectors["membership_deployment"];
2009        let input = &vector["input"];
2010        let texts = |v: &Value| -> Vec<String> {
2011            v.as_array()
2012                .unwrap()
2013                .iter()
2014                .map(|s| s.as_str().unwrap().to_owned())
2015                .collect()
2016        };
2017        let manifest = Manifest {
2018            service: None,
2019            workers: texts(&input["workers"]),
2020            listeners: texts(&input["listeners"]),
2021            middlewares: texts(&input["middlewares"]),
2022            metadata: input["metadata"]
2023                .as_array()
2024                .unwrap()
2025                .iter()
2026                .map(|a| {
2027                    let text = |k: &str| a[k].as_str().unwrap().to_owned();
2028                    (text("key"), text("value"))
2029                })
2030                .collect(),
2031            processes: texts(&input["processes"]),
2032            deployment: None,
2033            switch: Switch::default(),
2034        };
2035        let membership = membership(
2036            input["service"].as_str().unwrap().to_owned(),
2037            input["deployment"].as_str().unwrap().to_owned(),
2038            manifest,
2039            input["issued_at"].as_i64().unwrap(),
2040        );
2041        let message = signing::membership_message(&membership);
2042        assert_eq!(hex::encode(&message), vector["message"].as_str().unwrap());
2043        let key = signing::signing_key_from_hex(vectors["key"]["seed"].as_str().unwrap()).unwrap();
2044        assert_eq!(
2045            hex::encode(signing::sign(&key, &message).sig),
2046            vector["signature"].as_str().unwrap()
2047        );
2048    }
2049
2050    #[test]
2051    fn a_deployment_is_letters_digits_dashes_underscores_and_dots() {
2052        for valid in ["", "v1", "2026-11-11.1", "a_b", &"x".repeat(128)] {
2053            assert!(check_deployment(valid).is_ok(), "{valid}");
2054        }
2055        for invalid in ["v 1", "v1@x", "ΓΌ", "a/b", &"x".repeat(129)] {
2056            assert!(
2057                matches!(check_deployment(invalid), Err(Error::Config(m)) if m.contains("1 to 128")),
2058                "{invalid}"
2059            );
2060        }
2061    }
2062
2063    /// An app keeps applying (it runs beside) while its deployment has not caught up, may not
2064    /// switch, or served before; other refusals end it.
2065    #[test]
2066    fn an_app_waits_beside_while_its_deployment_has_not_caught_up_or_served_before() {
2067        let refused = Error::Status;
2068        for details in [
2069            "not_caught_up: deployment v2 has not caught up",
2070            "not_serving: shop is served by v1",
2071            "served_before: deployment v1 served shop before and v2 serves it now",
2072        ] {
2073            assert!(
2074                refused(tonic::Status::failed_precondition(details)).waits_for_switch(),
2075                "{details}"
2076            );
2077        }
2078        assert!(
2079            !refused(tonic::Status::failed_precondition(
2080                "key may not manage shop"
2081            ))
2082            .waits_for_switch()
2083        );
2084        assert!(!refused(tonic::Status::unavailable("served_before")).waits_for_switch());
2085    }
2086}