mod app;
mod context;
mod data;
mod domain;
mod error;
mod index;
mod listener;
mod log;
mod messages;
pub mod process;
mod store;
mod vault;
mod worker;
use std::{
collections::HashMap,
future::Future,
path::{Path, PathBuf},
sync::{Arc, RwLock},
time::{Duration, Instant, SystemTime, UNIX_EPOCH},
};
use ed25519_dalek::SigningKey;
use kernable_core::{
PROTOCOL,
proto::{
self, ApplyRequest, Attribute, CancelRequest, Membership, ProcessActing,
ProcessRegistration, SubmitRequest, Wait as WireWait, cancel_result, command_result,
command_service_client::CommandServiceClient,
membership_service_client::MembershipServiceClient,
partition_service_client::PartitionServiceClient,
process_service_client::ProcessServiceClient, query_result,
query_service_client::QueryServiceClient,
},
signing, transport,
};
use serde::{Serialize, de::DeserializeOwned};
use serde_json::Value;
use tonic::{metadata::MetadataValue, transport::Channel};
pub use app::{App, AppHandle};
pub use context::{RequestContext, Timestamp};
pub use data::{Cache, Data, Files, Listed, Listing};
pub use domain::{
Aggregate, ApplyContext, CommandContext, CommandMeta, CommandSchema, Domain, EventMeta,
EventSchema, FoldEvent, NewEvent, QuerySchema, QueryTarget, State, domain,
};
pub use error::{BoxError, Error, Rejected};
pub use index::{Index, Reindex, Requirement, Unique, UniqueKey, reindex_type};
pub use kernable_core::transport::Tls;
pub use kernable_sdk_macros::{command, event, query};
pub use listener::{
Check, CheckKind, CheckOutcome, Listener, ListenerContext, ListenerHandle, MiddlewareOptions,
QueryContext, QueryMeta, StoredEventMeta, SubscribeOptions, Subscription, Target, When,
};
#[doc(hidden)]
pub use messages::__private;
pub use messages::{CommandType, EventType, Message, Of, QueryType, TypeKey};
pub use process::Process;
pub use store::Store;
extern crate self as kernable;
pub use worker::Worker;
use context::{issued_now, random_id};
use domain::{decode, encode};
tokio::task_local! {
static HANDLING: String;
}
fn handling() -> String {
HANDLING.try_with(Clone::clone).unwrap_or_default()
}
#[derive(Clone, Debug)]
pub struct Options {
url: Option<String>,
key: Option<PathBuf>,
grant: Option<PathBuf>,
tenant: String,
service: Option<String>,
deployment: Option<String>,
context: RequestContext,
tls: Option<Tls>,
insecure: Option<bool>,
timeout: Duration,
}
pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(60);
impl Default for Options {
fn default() -> Options {
Options {
url: None,
key: None,
grant: None,
tenant: "default".into(),
service: None,
deployment: None,
context: RequestContext::default(),
tls: None,
insecure: None,
timeout: DEFAULT_TIMEOUT,
}
}
}
impl Options {
pub fn new(key: impl AsRef<Path>) -> Options {
Options {
key: Some(key.as_ref().to_owned()),
..Options::default()
}
}
pub fn url(mut self, url: impl Into<String>) -> Options {
self.url = Some(url.into());
self
}
pub fn grant(mut self, path: impl AsRef<Path>) -> Options {
self.grant = Some(path.as_ref().to_owned());
self
}
pub fn tenant(mut self, tenant: impl Into<String>) -> Options {
self.tenant = tenant.into();
self
}
pub fn service(mut self, service: impl Into<String>) -> Options {
self.service = Some(service.into());
self
}
pub fn deployment(mut self, deployment: impl Into<String>) -> Options {
self.deployment = Some(deployment.into());
self
}
pub fn context(mut self, context: RequestContext) -> Options {
self.context = context;
self
}
pub fn tls(mut self, tls: Tls) -> Options {
self.tls = Some(tls);
self
}
pub fn insecure(mut self) -> Options {
self.insecure = Some(true);
self
}
pub fn timeout(mut self, timeout: Duration) -> Options {
self.timeout = timeout;
self
}
}
impl From<&str> for Options {
fn from(key: &str) -> Options {
Options::new(key)
}
}
impl From<String> for Options {
fn from(key: String) -> Options {
Options::new(key)
}
}
impl From<&Path> for Options {
fn from(key: &Path) -> Options {
Options::new(key)
}
}
impl From<PathBuf> for Options {
fn from(key: PathBuf) -> Options {
Options::new(key)
}
}
pub(crate) struct Channels {
all: Vec<Channel>,
current: std::sync::atomic::AtomicUsize,
seen: std::sync::atomic::AtomicU64,
}
pub(crate) struct Partitions {
map: tokio::sync::Mutex<Option<Option<proto::PartitionMap>>>,
channels: std::sync::Mutex<HashMap<String, Arc<Channels>>>,
tls: Option<Tls>,
}
pub(crate) async fn partitions_of(
client: &Client,
what: &str,
base: Duration,
stopped: &mut tokio::sync::watch::Receiver<bool>,
) -> Option<Vec<(String, Client)>> {
let mut attempt = 0;
loop {
let read = tokio::select! {
read = client.partitions() => read,
_ = stopped.wait_for(|s| *s) => return None,
};
match read {
Ok(parts) => return Some(parts),
Err(status) => {
attempt += 1;
let error: BoxError = status.into();
let delay = log::reconnecting(&client.log, what, Some(&error), base, attempt);
tokio::select! {
() = tokio::time::sleep(delay) => {}
_ = stopped.wait_for(|s| *s) => return None,
}
}
}
}
}
pub(crate) fn partition_of<'a>(map: &'a proto::PartitionMap, tenant: &str) -> &'a str {
map.tenants
.iter()
.find(|t| t.tenant == tenant)
.map_or(map.default.as_str(), |t| t.partition.as_str())
}
pub(crate) fn moving(status: &tonic::Status) -> bool {
status.code() == tonic::Code::Unavailable && status.message().starts_with("moving")
}
const MOVE_WAIT: Duration = Duration::from_secs(30);
pub(crate) fn wrong_partition(status: &tonic::Status) -> bool {
status.code() == tonic::Code::FailedPrecondition
&& status.message().starts_with("wrong_partition")
}
#[derive(Clone)]
pub(crate) struct Client {
channels: Arc<Channels>,
parts: Arc<Partitions>,
key: Arc<SigningKey>,
key_id: String,
grant: Option<MetadataValue<tonic::metadata::Ascii>>,
log: log::Log,
timeout: Duration,
deployment: String,
}
impl Client {
pub(crate) async fn partition_map(
&self,
refresh: bool,
) -> Result<Option<proto::PartitionMap>, tonic::Status> {
let mut held = self.parts.map.lock().await;
if refresh {
*held = None;
}
if let Some(map) = held.as_ref() {
return Ok(map.clone());
}
let request = proto::MapRequest { protocol: PROTOCOL };
let map = match self
.call_with(None, request, true, |channel, r| async move {
PartitionServiceClient::new(channel).map(r).await
})
.await
{
Ok(map) => Some(map),
Err(s) if matches!(s.code(), tonic::Code::NotFound | tonic::Code::Unimplemented) => {
None
}
Err(s) => return Err(s),
};
*held = Some(map.clone());
Ok(map)
}
fn on_partition(&self, map: &proto::PartitionMap, name: &str) -> Result<Client, tonic::Status> {
let partition = map
.partitions
.iter()
.find(|p| p.name == name)
.ok_or_else(|| {
tonic::Status::internal(format!("the partition map names no partition {name}"))
})?;
let own: Vec<&String> = partition
.addresses
.iter()
.filter(|a| !a.starts_with("relay:"))
.collect();
if own.is_empty() {
return Err(tonic::Status::unavailable(format!(
"partition {name} is reached only through a relay: a client needs one of its own addresses"
)));
}
let addresses = own.iter().map(|a| a.as_str()).collect::<Vec<_>>().join(",");
let mut cached = self.parts.channels.lock().unwrap();
let channels = match cached.get(&addresses) {
Some(channels) => Arc::clone(channels),
None => {
let all = own
.iter()
.map(|a| {
transport::connect_lazy_among(a, self.parts.tls.as_ref(), own.len() > 1)
.map_err(|e| {
tonic::Status::internal(format!("partition {name}, {a}: {e}"))
})
})
.collect::<Result<Vec<_>, _>>()?;
let channels = Arc::new(Channels {
all,
current: Default::default(),
seen: Default::default(),
});
cached.insert(addresses, Arc::clone(&channels));
channels
}
};
Ok(Client {
channels,
..self.clone()
})
}
pub(crate) async fn for_tenant(&self, tenant: &str) -> Result<Client, tonic::Status> {
match self.partition_map(false).await? {
None => Ok(self.clone()),
Some(map) => {
let name = partition_of(&map, tenant).to_owned();
self.on_partition(&map, &name)
}
}
}
pub(crate) async fn control(&self) -> Result<Client, tonic::Status> {
match self.partition_map(false).await? {
None => Ok(self.clone()),
Some(map) => self.on_partition(&map, &map.control),
}
}
pub(crate) async fn partitions(&self) -> Result<Vec<(String, Client)>, tonic::Status> {
match self.partition_map(false).await? {
None => Ok(vec![(String::new(), self.clone())]),
Some(map) => map
.partitions
.iter()
.map(|p| Ok((p.name.clone(), self.on_partition(&map, &p.name)?)))
.collect(),
}
}
pub(crate) async fn routed<R, Fut>(
&self,
tenant: &str,
mut call: impl FnMut(Client) -> Fut,
) -> Result<R, tonic::Status>
where
Fut: Future<Output = Result<R, tonic::Status>>,
{
let mut attempt = 0;
let deadline = Instant::now() + MOVE_WAIT;
let mut pause = Duration::from_millis(50);
loop {
let client = self.for_tenant(tenant).await?;
match call(client).await {
Err(status) if moving(&status) && Instant::now() + pause < deadline => {
tokio::time::sleep(pause).await;
pause = (pause * 2).min(Duration::from_secs(1));
}
Err(status) if attempt < 3 && wrong_partition(&status) => {
attempt += 1;
self.partition_map(true).await?;
}
result => return result,
}
}
}
pub(crate) fn channel(&self) -> (usize, Channel) {
let at = self
.channels
.current
.load(std::sync::atomic::Ordering::SeqCst);
(at, self.channels.all[at].clone())
}
pub(crate) fn ended(&self, at: usize, status: &tonic::Status) -> bool {
let n = self.channels.all.len();
let away = status.code() == tonic::Code::Unavailable || not_connected(status);
if n > 1 && away {
let _ = self.channels.current.compare_exchange(
at,
(at + 1) % n,
std::sync::atomic::Ordering::SeqCst,
std::sync::atomic::Ordering::SeqCst,
);
}
n > 1 && away
}
async fn call<T: Clone, R, Fut>(
&self,
timeout: Option<Duration>,
message: T,
call: impl FnMut(Channel, tonic::Request<T>) -> Fut,
) -> Result<R, tonic::Status>
where
Fut: Future<Output = Result<tonic::Response<R>, tonic::Status>>,
{
self.call_with(timeout, message, false, call).await
}
async fn call_with<T: Clone, R, Fut>(
&self,
timeout: Option<Duration>,
message: T,
idempotent: bool,
mut call: impl FnMut(Channel, tonic::Request<T>) -> Fut,
) -> Result<R, tonic::Status>
where
Fut: Future<Output = Result<tonic::Response<R>, tonic::Status>>,
{
let timeout = timeout.unwrap_or(self.timeout);
let deadline = Instant::now() + timeout;
let mut pause = Duration::from_millis(50);
let mut dropped_at: Option<Instant> = None;
loop {
let left = deadline.saturating_duration_since(Instant::now());
let mut request = self.request(message.clone());
request.set_timeout(left);
let (at, channel) = self.channel();
let result = match tokio::time::timeout(left, call(channel, request)).await {
Ok(result) => result,
Err(_) => Err(tonic::Status::deadline_exceeded(format!(
"no answer from the kernel within {} ms",
timeout.as_millis()
))),
};
match result {
Ok(response) => return Ok(response.into_inner()),
Err(status) if Instant::now() + pause < deadline && self.ended(at, &status) => {
tokio::time::sleep(pause).await;
pause = (pause * 2).min(MAX_PAUSE);
}
Err(status)
if idempotent
&& status.code() == tonic::Code::Unavailable
&& !moving(&status)
&& !dropped(&status)
&& !not_connected(&status)
&& Instant::now() + pause < deadline =>
{
tokio::time::sleep(pause).await;
pause = (pause * 2).min(MAX_PAUSE);
}
Err(status)
if (not_connected(&status) || (idempotent && dropped(&status)))
&& Instant::now() + pause < deadline
&& dropped_at.is_none_or(|at| at.elapsed() < DROPPED_RETRY) =>
{
if dropped(&status) {
dropped_at.get_or_insert_with(Instant::now);
}
tokio::time::sleep(pause).await;
pause = (pause * 2).min(MAX_PAUSE);
}
Err(status) if not_connected(&status) => {
return Err(tonic::Status::deadline_exceeded(format!(
"no connection to the kernel within {} ms: {}",
timeout.as_millis(),
status.message()
)));
}
Err(status) => return Err(status),
}
}
}
fn request<T>(&self, message: T) -> tonic::Request<T> {
let mut request = tonic::Request::new(message);
if let Some(grant) = &self.grant {
request
.metadata_mut()
.insert("kernable-grant", grant.clone());
}
request
}
fn sign(&self, message: &[u8]) -> proto::Signature {
signing::sign(&self.key, message)
}
}
#[derive(Clone)]
pub struct Kernable {
client: Client,
tenant: String,
context: RequestContext,
domains: Arc<RwLock<HashMap<String, Domain>>>,
service: String,
}
impl Kernable {
pub fn new(options: impl Into<Options>) -> Result<Kernable, Error> {
let options = options.into();
let url = options
.url
.or_else(|| std::env::var("KERNABLE_URL").ok())
.unwrap_or_else(|| "http://127.0.0.1:7233".into());
let key_file = options
.key
.or_else(|| std::env::var_os("KERNABLE_KEY").map(PathBuf::from))
.unwrap_or_else(|| PathBuf::from("app.key"));
let key = signing::read_signing_key(&key_file)
.map_err(|e| Error::Config(format!("key {}: {e}", key_file.display())))?;
let explicit = options
.grant
.clone()
.or_else(|| std::env::var_os("KERNABLE_GRANT").map(PathBuf::from));
let grant_file = explicit
.clone()
.unwrap_or_else(|| key_file.with_extension("grant"));
let grant =
if explicit.is_some() || grant_file.exists() {
let hex = std::fs::read_to_string(&grant_file)
.map_err(|e| Error::Config(format!("grant {}: {e}", grant_file.display())))?;
Some(hex.trim().parse().map_err(|_| {
Error::Config(format!("grant {} is not hex", grant_file.display()))
})?)
} else {
None
};
let tls = match options.tls {
Some(tls) => Some(tls),
None => tls_from_env()?,
};
let insecure = options
.insecure
.unwrap_or_else(|| std::env::var("KERNABLE_INSECURE").is_ok_and(|v| v == "1"));
if tls.is_none() && !insecure && !local(&url) {
return Err(Error::Config(format!(
"{url} is not on this machine: connect with TLS (Options::tls), or allow plain \
text with Options::insecure"
)));
}
let urls: Vec<&str> = url
.split(',')
.map(str::trim)
.filter(|u| !u.is_empty())
.collect();
let several = urls.len() > 1;
let all = urls
.iter()
.map(|u| {
transport::connect_lazy_among(u, tls.as_ref(), several)
.map_err(|e| Error::Config(format!("kernel {u}: {e}")))
})
.collect::<Result<Vec<_>, _>>()?;
if all.is_empty() {
return Err(Error::Config("no kernel address".into()));
}
let channels = Arc::new(Channels {
all,
current: Default::default(),
seen: Default::default(),
});
let service = options
.service
.or_else(|| std::env::var("KERNABLE_SERVICE").ok())
.unwrap_or_default();
let deployment = options
.deployment
.or_else(|| std::env::var("KERNABLE_DEPLOYMENT").ok())
.unwrap_or_default();
check_deployment(&deployment)?;
let key_id = signing::key_id(&key.verifying_key());
let log = log::Log::new(&url, &key_file, &key_id);
#[cfg(unix)]
if let Ok(meta) = std::fs::metadata(&key_file) {
let mode = std::os::unix::fs::PermissionsExt::mode(&meta.permissions()) & 0o777;
if mode & 0o077 != 0 {
let path = key_file.display();
log.warn("key", || {
format!("{path} can be read by other users (mode {mode:o}): chmod 600 {path}")
});
}
}
Ok(Kernable {
client: Client {
channels,
parts: Arc::new(Partitions {
map: tokio::sync::Mutex::default(),
channels: Default::default(),
tls: tls.clone(),
}),
key_id,
key: Arc::new(key),
grant,
log,
timeout: options.timeout,
deployment,
},
tenant: options.tenant,
context: options.context,
domains: Arc::default(),
service,
})
}
pub fn with_domain(&self, domain: &Domain) -> Kernable {
self.domains
.write()
.unwrap()
.insert(domain.name().to_owned(), domain.clone());
self.clone()
}
pub fn worker<S: State>(&self, aggregate: &Aggregate<S>) -> Worker {
Worker::new(self.client.clone(), self.service.clone()).aggregate(aggregate)
}
pub fn listener(&self, listener: &Listener) -> ListenerHandle {
ListenerHandle::new(self, listener, self.service.clone())
}
pub fn data(&self) -> Files {
Files::new(
self.client.clone(),
self.tenant.clone(),
self.context.clone(),
)
}
pub fn cache(&self) -> Cache {
Cache::new(
self.client.clone(),
self.tenant.clone(),
self.context.clone(),
)
}
pub async fn apply(&self, manifest: Manifest) -> Result<(), Error> {
let service = manifest
.service
.clone()
.unwrap_or_else(|| self.service.clone());
if service.is_empty() {
return Err(Error::Config(
"apply needs a service: set it with Manifest::service or Options::service".into(),
));
}
let deployment = manifest
.deployment
.clone()
.unwrap_or_else(|| self.client.deployment.clone());
check_deployment(&deployment)?;
let manifest_switch = manifest.switch;
let membership = membership(service, deployment, manifest, issued_now());
let sig = self.client.sign(&signing::membership_message(&membership));
let request = ApplyRequest {
membership: Some(membership),
sig: Some(sig),
protocol: PROTOCOL,
force: manifest_switch == Switch::Now,
no_switch: manifest_switch == Switch::Never,
no_rollback: manifest_switch == Switch::CaughtUp,
};
self.client
.control()
.await?
.call_with(None, request, true, |channel, r| async move {
MembershipServiceClient::new(channel).apply(r).await
})
.await?;
Ok(())
}
pub async fn register_process(&self, process: &Process) -> Result<process::Registered, Error> {
let model = serde_json::to_vec(&process.model()?)?;
let issued_at = issued_now();
let sig = self
.client
.sign(&signing::process_message(&model, issued_at));
let request = ProcessRegistration {
model,
issued_at,
sig: Some(sig),
protocol: PROTOCOL,
};
let registered = self
.client
.control()
.await?
.call(None, request, |channel, r| async move {
ProcessServiceClient::new(channel).register(r).await
})
.await?;
Ok(process::Registered {
name: registered.name,
version: registered.version,
new: registered.new,
})
}
pub async fn process_act(&self, name: &str, context: RequestContext) -> Result<bool, Error> {
let context = context.to_wire();
let issued_at = issued_now();
let sig = self.client.sign(&signing::process_act_message(
name,
Some(&context),
issued_at,
));
let request = ProcessActing {
name: name.to_owned(),
context: Some(context),
issued_at,
sig: Some(sig),
protocol: PROTOCOL,
};
let acted = self
.client
.control()
.await?
.call(None, request, |channel, r| async move {
ProcessServiceClient::new(channel).act(r).await
})
.await?;
Ok(acted.changed)
}
pub fn app(&self, app: App) -> Result<AppHandle, Error> {
AppHandle::new(self, app)
}
pub async fn submit(&self, submit: Submit) -> Result<Outcome, Error> {
if submit.at.is_some() {
return Err(Error::Config(
"a scheduled command (`at`) has no outcome yet: use `enqueue`".into(),
));
}
let wait = submit.wait;
let res = self.send(submit, wait.wire()).await?;
match res.outcome {
Some(command_result::Outcome::Rejected(r)) => {
Ok(Outcome::Rejected(Rejected::from_wire(r)))
}
Some(command_result::Outcome::Committed(c)) => {
let events: Vec<StoredEvent> = c
.events
.into_iter()
.map(|e| StoredEvent::from_wire(e, &[]))
.collect();
if wait == Wait::Settled && !c.settled {
return Err(Error::NotSettled(events));
}
Ok(Outcome::Committed(events))
}
Some(command_result::Outcome::Accepted(_)) => Err(Error::NotDue(res.command_id)),
None => Err(Error::Status(tonic::Status::internal("no outcome"))),
}
}
pub async fn enqueue(&self, submit: Submit) -> Result<String, Error> {
Ok(self.send(submit, WireWait::Accepted).await?.command_id)
}
pub async fn cancel(&self, cancel: Cancel) -> Result<CancelOutcome, Error> {
let mut request = CancelRequest {
command_id: cancel.command_id,
tenant_id: cancel.tenant.unwrap_or_else(|| self.tenant.clone()),
context: Some(
cancel
.context
.unwrap_or_else(|| self.context.clone())
.to_wire(),
),
issued_at: issued_now(),
client_sig: None,
protocol: PROTOCOL,
};
request.client_sig = Some(self.client.sign(&signing::cancel_message(&request)));
let tenant = request.tenant_id.clone();
let timeout = cancel.timeout;
let res = self
.client
.routed(&tenant, |client| {
let request = request.clone();
async move {
client
.call_with(timeout, request, true, |channel, r| async move {
CommandServiceClient::new(channel).cancel(r).await
})
.await
}
})
.await?;
match res.outcome {
Some(cancel_result::Outcome::Cancelled(_)) => Ok(CancelOutcome::Cancelled),
Some(cancel_result::Outcome::Rejected(r)) => {
Ok(CancelOutcome::Rejected(Rejected::from_wire(r)))
}
None => Err(Error::Status(tonic::Status::internal("no outcome"))),
}
}
async fn send(&self, s: Submit, wait: WireWait) -> Result<proto::CommandResult, Error> {
if s.until.is_some() && s.at.is_none() {
return Err(Error::Config("`until` needs `at`".into()));
}
let command_id = s.id.unwrap_or_else(random_id);
let vault = s.vault.clone().or_else(|| {
self.domains
.read()
.unwrap()
.get(&s.domain)
.and_then(|d| d.command_vault(&s.command_type))
});
let sealed =
vault::seal(&s.data, vault.as_ref(), &s.aggregate_id).map_err(Error::Config)?;
let mut context = s.context.unwrap_or_else(|| self.context.clone());
if context.correlation_id.is_empty() {
context.correlation_id = command_id.clone();
}
let mut cmd = proto::Command {
command_id,
tenant_id: s.tenant.unwrap_or_else(|| self.tenant.clone()),
domain: s.domain,
aggregate_type: s.aggregate_type,
aggregate_id: s.aggregate_id,
command_type: s.command_type,
payload: sealed.payload,
client_sig: None,
context: Some(context.to_wire()),
vault_refs: sealed.refs,
deliver_at: s.at.unwrap_or(0),
deliver_until: s.until.unwrap_or(0),
};
cmd.client_sig = Some(self.client.sign(&signing::command_message(&cmd)));
let request = SubmitRequest {
command: Some(cmd),
wait: wait.into(),
protocol: PROTOCOL,
vault: sealed.values,
listener: handling(),
};
let tenant = request
.command
.as_ref()
.map(|c| c.tenant_id.clone())
.unwrap_or_default();
let timeout = s.timeout;
Ok(self
.client
.routed(&tenant, |client| {
let request = request.clone();
async move {
let result = client
.call_with(timeout, request, true, |channel, r| async move {
CommandServiceClient::new(channel).submit(r).await
})
.await?;
if let Some(command_result::Outcome::Committed(c)) = &result.outcome {
let last = c.events.last().map_or(0, |e| e.global_position);
client
.channels
.seen
.fetch_max(c.position.max(last), std::sync::atomic::Ordering::SeqCst);
}
Ok(result)
}
})
.await?)
}
pub async fn query<T: DeserializeOwned>(&self, query: Query) -> Result<T, Error> {
let declared = query.target.clone().or_else(|| {
self.domains
.read()
.unwrap()
.get(&query.domain)
.and_then(|d| d.query_target(&query.query_type))
});
let target = declared.and_then(|t| t.wire(&query.domain, &query.data));
let mut request = proto::QueryRequest {
target,
query_id: random_id(),
tenant_id: query.tenant.unwrap_or_else(|| self.tenant.clone()),
domain: query.domain,
query_type: query.query_type,
payload: encode(&query.data),
context: Some(
query
.context
.unwrap_or_else(|| self.context.clone())
.to_wire(),
),
min_position: query.min_position,
issued_at: issued_now(),
client_sig: None,
protocol: PROTOCOL,
listener: String::new(),
wait_only: false,
deployment: self.client.deployment.clone(),
};
let timeout = query.timeout;
if query.all_partitions {
self.caught_up_everywhere(&request, timeout).await?;
request.issued_at = issued_now();
}
let listener = handling();
let tenant = request.tenant_id.clone();
let res = self
.client
.routed(&tenant, |client| {
let mut request = request.clone();
if listener.is_empty() {
request.min_position = request.min_position.max(
client
.channels
.seen
.load(std::sync::atomic::Ordering::SeqCst),
);
}
request.client_sig = Some(client.sign(&signing::query_message(&request)));
request.listener = listener.clone();
async move {
client
.call_with(timeout, request, true, |channel, r| async move {
QueryServiceClient::new(channel).query(r).await
})
.await
}
})
.await?;
match res.outcome {
Some(query_result::Outcome::Response(r)) => Ok(serde_json::from_value(decode(&r))?),
Some(query_result::Outcome::Rejected(r)) => {
Err(Error::Rejected(Rejected::from_wire(r)))
}
None => Err(Error::Status(tonic::Status::internal("no outcome"))),
}
}
pub async fn ask<Q: QueryType>(
&self,
query: Q,
options: impl FnOnce(Query) -> Query,
) -> Result<Q::Answer, Error> {
self.query(options(Query::of(query))).await
}
async fn caught_up_everywhere(
&self,
query: &proto::QueryRequest,
timeout: Option<Duration>,
) -> Result<(), Error> {
let mut wait = proto::QueryRequest {
wait_only: true,
min_position: 0,
payload: Vec::new(),
..query.clone()
};
wait.client_sig = Some(self.client.sign(&signing::query_message(&wait)));
wait.listener = handling();
let mut waits = tokio::task::JoinSet::new();
for (_, client) in self.client.partitions().await? {
let wait = wait.clone();
waits.spawn(async move {
client
.call_with(timeout, wait, true, |channel, r| async move {
QueryServiceClient::new(channel).query(r).await
})
.await
});
}
while let Some(waited) = waits.join_next().await {
waited.map_err(|e| Error::Status(tonic::Status::internal(e.to_string())))??;
}
Ok(())
}
pub fn subscribe<F, Fut>(&self, options: SubscribeOptions, handler: F) -> Subscription
where
F: Fn(StoredEvent) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<(), BoxError>> + Send + 'static,
{
Subscription::start(self.client.clone(), options, handler)
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Wait {
#[default]
Settled,
Committed,
}
impl Wait {
fn wire(self) -> WireWait {
match self {
Wait::Settled => WireWait::Settled,
Wait::Committed => WireWait::Committed,
}
}
}
fn tls_from_env() -> Result<Option<Tls>, Error> {
let var = |name| std::env::var_os(name).map(PathBuf::from);
match (
var("KERNABLE_TLS_CA"),
var("KERNABLE_TLS_CERT"),
var("KERNABLE_TLS_KEY"),
) {
(None, None, None) => Ok(None),
(Some(ca), Some(cert), Some(key)) => Ok(Some(Tls { ca, cert, key })),
_ => Err(Error::Config(
"set all of KERNABLE_TLS_CA, KERNABLE_TLS_CERT and KERNABLE_TLS_KEY, or none".into(),
)),
}
}
fn membership(
service: String,
deployment: String,
manifest: Manifest,
issued_at: i64,
) -> Membership {
Membership {
service,
workers: manifest.workers,
listeners: manifest.listeners,
middlewares: manifest.middlewares,
metadata: manifest
.metadata
.into_iter()
.map(|(key, value)| Attribute { key, value })
.collect(),
issued_at,
processes: manifest.processes,
deployment,
}
}
fn check_deployment(deployment: &str) -> Result<(), Error> {
let valid = deployment.len() <= 128
&& deployment
.chars()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'));
if valid {
Ok(())
} else {
Err(Error::Config(format!(
"deployment {deployment:?}: use 1 to 128 letters, digits, `-`, `_` and `.`"
)))
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Manifest {
service: Option<String>,
workers: Vec<String>,
listeners: Vec<String>,
middlewares: Vec<String>,
metadata: Vec<(String, String)>,
processes: Vec<String>,
deployment: Option<String>,
switch: Switch,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Switch {
#[default]
CaughtUp,
Now,
Never,
}
impl Switch {
pub fn from_env() -> Result<Switch, Error> {
match std::env::var("KERNABLE_SWITCH").as_deref() {
Err(_) | Ok("" | "caught-up") => Ok(Switch::CaughtUp),
Ok("now") => Ok(Switch::Now),
Ok("never") => Ok(Switch::Never),
Ok(other) => Err(Error::Config(format!(
"KERNABLE_SWITCH={other}: caught-up, now or never"
))),
}
}
}
impl Manifest {
pub fn new() -> Manifest {
Manifest::default()
}
pub fn service(mut self, service: impl Into<String>) -> Manifest {
self.service = Some(service.into());
self
}
pub fn worker<S: State>(mut self, aggregate: &Aggregate<S>) -> Manifest {
self.workers.push(format!(
"{}.{}",
aggregate.domain().name(),
aggregate.name()
));
self
}
pub fn listener(mut self, listener: &Listener) -> Manifest {
self.listeners.push(listener.name().to_owned());
self
}
pub fn middleware(mut self, listener: &Listener) -> Manifest {
self.middlewares.push(listener.name().to_owned());
self
}
pub fn process(mut self, process: &Process) -> Manifest {
self.processes.push(process.name());
self
}
pub fn metadata(mut self, key: impl Into<String>, value: impl Into<String>) -> Manifest {
self.metadata.push((key.into(), value.into()));
self
}
pub fn deployment(mut self, deployment: impl Into<String>) -> Manifest {
self.deployment = Some(deployment.into());
self
}
pub fn switch(mut self, switch: Switch) -> Manifest {
self.switch = switch;
self
}
}
#[derive(Clone, Debug)]
pub struct Submit {
domain: String,
aggregate_type: String,
aggregate_id: String,
command_type: String,
data: Value,
tenant: Option<String>,
id: Option<String>,
context: Option<RequestContext>,
wait: Wait,
timeout: Option<Duration>,
vault: Option<vault::VaultFields>,
at: Option<i64>,
until: Option<i64>,
}
impl Submit {
pub fn new(
domain: &str,
aggregate_type: &str,
aggregate_id: &str,
command_type: &str,
) -> Submit {
Submit {
domain: domain.to_owned(),
aggregate_type: aggregate_type.to_owned(),
aggregate_id: aggregate_id.to_owned(),
command_type: command_type.to_owned(),
data: Value::Null,
tenant: None,
id: None,
context: None,
wait: Wait::Settled,
timeout: None,
vault: None,
at: None,
until: None,
}
}
pub fn command<C: CommandType>(command: C, aggregate_id: &str) -> Submit {
let vault = messages::domain_of::<C>().command_vault(C::TYPE);
Submit {
vault,
..Submit::new(C::DOMAIN, C::AGGREGATE, aggregate_id, C::TYPE).data(command)
}
}
pub fn data(mut self, data: impl Serialize) -> Submit {
self.data = serde_json::to_value(data).expect("command data is JSON");
self
}
pub fn tenant(mut self, tenant: impl Into<String>) -> Submit {
self.tenant = Some(tenant.into());
self
}
pub fn id(mut self, id: impl Into<String>) -> Submit {
self.id = Some(id.into());
self
}
pub fn context(mut self, context: RequestContext) -> Submit {
self.context = Some(context);
self
}
pub fn at(mut self, time: SystemTime) -> Submit {
self.at = Some(millis(time));
self
}
pub fn until(mut self, time: SystemTime) -> Submit {
self.until = Some(millis(time));
self
}
pub fn wait(mut self, wait: Wait) -> Submit {
self.wait = wait;
self
}
pub fn timeout(mut self, timeout: Duration) -> Submit {
self.timeout = Some(timeout);
self
}
}
fn millis(time: SystemTime) -> i64 {
time.duration_since(UNIX_EPOCH)
.map_or(0, |d| i64::try_from(d.as_millis()).unwrap_or(i64::MAX))
}
#[derive(Clone, Debug)]
pub struct Cancel {
command_id: String,
tenant: Option<String>,
context: Option<RequestContext>,
timeout: Option<Duration>,
}
impl Cancel {
pub fn new(command_id: &str) -> Cancel {
Cancel {
command_id: command_id.to_owned(),
tenant: None,
context: None,
timeout: None,
}
}
pub fn tenant(mut self, tenant: impl Into<String>) -> Cancel {
self.tenant = Some(tenant.into());
self
}
pub fn context(mut self, context: RequestContext) -> Cancel {
self.context = Some(context);
self
}
pub fn timeout(mut self, timeout: Duration) -> Cancel {
self.timeout = Some(timeout);
self
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum CancelOutcome {
Cancelled,
Rejected(Rejected),
}
impl CancelOutcome {
pub fn is_cancelled(&self) -> bool {
matches!(self, CancelOutcome::Cancelled)
}
}
#[derive(Clone, Debug)]
pub struct Query {
domain: String,
query_type: String,
data: Value,
tenant: Option<String>,
context: Option<RequestContext>,
min_position: u64,
timeout: Option<Duration>,
all_partitions: bool,
target: Option<QueryTarget>,
}
impl Query {
pub fn new(domain: &str, query_type: &str) -> Query {
Query {
domain: domain.to_owned(),
query_type: query_type.to_owned(),
data: Value::Null,
tenant: None,
context: None,
min_position: 0,
timeout: None,
all_partitions: false,
target: None,
}
}
pub fn of<Q: QueryType>(query: Q) -> Query {
let target = messages::domain_of::<Q>().query_target(Q::TYPE);
Query {
target,
..Query::new(Q::DOMAIN, Q::TYPE).data(query)
}
}
pub fn data(mut self, data: impl Serialize) -> Query {
self.data = serde_json::to_value(data).expect("query data is JSON");
self
}
pub fn tenant(mut self, tenant: impl Into<String>) -> Query {
self.tenant = Some(tenant.into());
self
}
pub fn context(mut self, context: RequestContext) -> Query {
self.context = Some(context);
self
}
pub fn min_position(mut self, position: u64) -> Query {
self.min_position = position;
self
}
pub fn timeout(mut self, timeout: Duration) -> Query {
self.timeout = Some(timeout);
self
}
pub fn all_partitions(mut self) -> Query {
self.all_partitions = true;
self
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum Outcome {
Committed(Vec<StoredEvent>),
Rejected(Rejected),
}
impl Outcome {
pub fn is_committed(&self) -> bool {
matches!(self, Outcome::Committed(_))
}
pub fn events(&self) -> &[StoredEvent] {
match self {
Outcome::Committed(events) => events,
Outcome::Rejected(_) => &[],
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum QueryOutcome {
Answered(Value),
Rejected(Rejected),
}
impl QueryOutcome {
pub fn is_answered(&self) -> bool {
matches!(self, QueryOutcome::Answered(_))
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct StoredEvent {
pub position: u64,
pub tenant: String,
pub domain: String,
pub aggregate_type: String,
pub aggregate_id: String,
pub version: u64,
pub event_type: String,
pub schema: u32,
pub data: Value,
pub redacted: Vec<String>,
pub command_id: String,
pub created_at: Timestamp,
pub request: RequestContext,
pub deployment: String,
}
impl StoredEvent {
pub fn parse<D: DeserializeOwned>(&self) -> Result<D, serde_json::Error> {
serde_json::from_value(self.data.clone())
}
pub(crate) fn from_wire(e: proto::Event, vault: &[proto::VaultValue]) -> StoredEvent {
let (data, redacted) = vault::unseal(decode(&e.payload), vault);
StoredEvent {
position: e.global_position,
tenant: e.tenant_id,
domain: e.domain,
aggregate_type: e.aggregate_type,
aggregate_id: e.aggregate_id,
version: e.version,
event_type: e.event_type,
schema: e.schema,
data,
redacted,
command_id: e.command_id,
created_at: Timestamp(e.created_at),
request: RequestContext::from_wire(e.context.as_ref()),
deployment: e.deployment,
}
}
}
fn dropped(status: &tonic::Status) -> bool {
use std::io::ErrorKind::{BrokenPipe, ConnectionAborted, ConnectionReset, UnexpectedEof};
if !matches!(
status.code(),
tonic::Code::Unknown
| tonic::Code::Unavailable
| tonic::Code::Internal
| tonic::Code::Cancelled
) {
return false;
}
let mut source = std::error::Error::source(status);
while let Some(e) = source {
if let Some(io) = e.downcast_ref::<std::io::Error>()
&& matches!(
io.kind(),
ConnectionReset | ConnectionAborted | BrokenPipe | UnexpectedEof
)
{
return true;
}
source = e.source();
}
let message = status.message();
message.contains("transport error")
|| message.contains("connection closed")
|| message.contains("error reading a body from connection")
|| message.contains("h2 protocol error")
|| message.contains("operation was canceled")
}
fn not_connected(status: &tonic::Status) -> bool {
use std::io::ErrorKind::{AddrNotAvailable, ConnectionRefused, NotFound, TimedOut};
let mut source = std::error::Error::source(status);
while let Some(e) = source {
if let Some(io) = e.downcast_ref::<std::io::Error>() {
return matches!(
io.kind(),
ConnectionRefused | NotFound | AddrNotAvailable | TimedOut
);
}
if e.to_string().contains("error trying to connect") {
return true;
}
source = e.source();
}
false
}
fn local(url: &str) -> bool {
if url.contains(',') {
return url.split(',').all(|u| local(u.trim()));
}
if url.starts_with("unix:") {
return true;
}
let host = transport::tcp_addr(url);
let host = host.rsplit_once(':').map_or(host, |(host, port)| {
if port.chars().all(|c| c.is_ascii_digit()) {
host
} else {
url
}
});
let host = host.trim_start_matches('[').trim_end_matches(']');
host == "localhost"
|| host == "::1"
|| host.strip_prefix("127.").is_some_and(|rest| {
rest.split('.').count() == 3 && rest.split('.').all(|p| p.parse::<u8>().is_ok())
})
}
const MAX_PAUSE: Duration = Duration::from_millis(200);
const DROPPED_RETRY: Duration = Duration::from_secs(5);
#[cfg(test)]
mod dropped_tests {
use super::*;
#[test]
fn a_connection_that_dropped_under_way_counts_as_dropped_and_nothing_else_does() {
assert!(dropped(&tonic::Status::unknown("transport error")));
assert!(dropped(&tonic::Status::unavailable(
"h2 protocol error: error reading a body from connection"
)));
assert!(dropped(&tonic::Status::cancelled(
"h2 protocol error: error reading a body from connection"
)));
assert!(dropped(&tonic::Status::cancelled("operation was canceled")));
assert!(!dropped(&tonic::Status::cancelled("Timeout expired")));
assert!(!dropped(&tonic::Status::unknown("a worker's error")));
assert!(!dropped(&tonic::Status::invalid_argument(
"transport error"
)));
assert!(!dropped(&tonic::Status::deadline_exceeded(
"transport error"
)));
}
}
#[cfg(test)]
mod deployment_tests {
use serde_json::Value;
use super::*;
#[test]
fn a_membership_with_a_deployment_is_signed_as_the_test_vectors_say() {
let path = concat!(
env!("CARGO_MANIFEST_DIR"),
"/../../proto/test-vectors/signing.json"
);
let vectors: Value = serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap();
let vector = &vectors["membership_deployment"];
let input = &vector["input"];
let texts = |v: &Value| -> Vec<String> {
v.as_array()
.unwrap()
.iter()
.map(|s| s.as_str().unwrap().to_owned())
.collect()
};
let manifest = Manifest {
service: None,
workers: texts(&input["workers"]),
listeners: texts(&input["listeners"]),
middlewares: texts(&input["middlewares"]),
metadata: input["metadata"]
.as_array()
.unwrap()
.iter()
.map(|a| {
let text = |k: &str| a[k].as_str().unwrap().to_owned();
(text("key"), text("value"))
})
.collect(),
processes: texts(&input["processes"]),
deployment: None,
switch: Switch::default(),
};
let membership = membership(
input["service"].as_str().unwrap().to_owned(),
input["deployment"].as_str().unwrap().to_owned(),
manifest,
input["issued_at"].as_i64().unwrap(),
);
let message = signing::membership_message(&membership);
assert_eq!(hex::encode(&message), vector["message"].as_str().unwrap());
let key = signing::signing_key_from_hex(vectors["key"]["seed"].as_str().unwrap()).unwrap();
assert_eq!(
hex::encode(signing::sign(&key, &message).sig),
vector["signature"].as_str().unwrap()
);
}
#[test]
fn a_deployment_is_letters_digits_dashes_underscores_and_dots() {
for valid in ["", "v1", "2026-11-11.1", "a_b", &"x".repeat(128)] {
assert!(check_deployment(valid).is_ok(), "{valid}");
}
for invalid in ["v 1", "v1@x", "ΓΌ", "a/b", &"x".repeat(129)] {
assert!(
matches!(check_deployment(invalid), Err(Error::Config(m)) if m.contains("1 to 128")),
"{invalid}"
);
}
}
#[test]
fn an_app_waits_beside_while_its_deployment_has_not_caught_up_or_served_before() {
let refused = Error::Status;
for details in [
"not_caught_up: deployment v2 has not caught up",
"not_serving: shop is served by v1",
"served_before: deployment v1 served shop before and v2 serves it now",
] {
assert!(
refused(tonic::Status::failed_precondition(details)).waits_for_switch(),
"{details}"
);
}
assert!(
!refused(tonic::Status::failed_precondition(
"key may not manage shop"
))
.waits_for_switch()
);
assert!(!refused(tonic::Status::unavailable("served_before")).waits_for_switch());
}
}