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