1mod 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
89extern crate self as kernable;
91pub use worker::Worker;
92
93use context::{issued_now, random_id};
94use domain::{decode, encode};
95
96tokio::task_local! {
97 static HANDLING: String;
99}
100
101fn handling() -> String {
103 HANDLING.try_with(Clone::clone).unwrap_or_default()
104}
105
106#[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
132pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(60);
135
136impl 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 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 pub fn url(mut self, url: impl Into<String>) -> Options {
173 self.url = Some(url.into());
174 self
175 }
176
177 pub fn grant(mut self, path: impl AsRef<Path>) -> Options {
180 self.grant = Some(path.as_ref().to_owned());
181 self
182 }
183
184 pub fn tenant(mut self, tenant: impl Into<String>) -> Options {
186 self.tenant = tenant.into();
187 self
188 }
189
190 pub fn service(mut self, service: impl Into<String>) -> Options {
196 self.service = Some(service.into());
197 self
198 }
199
200 pub fn deployment(mut self, deployment: impl Into<String>) -> Options {
209 self.deployment = Some(deployment.into());
210 self
211 }
212
213 pub fn context(mut self, context: RequestContext) -> Options {
215 self.context = context;
216 self
217 }
218
219 pub fn tls(mut self, tls: Tls) -> Options {
224 self.tls = Some(tls);
225 self
226 }
227
228 pub fn insecure(mut self) -> Options {
232 self.insecure = Some(true);
233 self
234 }
235
236 pub fn timeout(mut self, timeout: Duration) -> Options {
245 self.timeout = timeout;
246 self
247 }
248}
249
250impl 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
275pub(crate) struct Channels {
279 all: Vec<std::sync::Mutex<Channel>>,
280 addresses: Vec<String>,
282 tls: Option<Tls>,
283 current: std::sync::atomic::AtomicUsize,
284 seen: std::sync::atomic::AtomicU64,
287}
288
289pub(crate) struct Partitions {
292 map: tokio::sync::Mutex<Option<Option<proto::PartitionMap>>>,
294 channels: std::sync::Mutex<HashMap<String, Arc<Channels>>>,
295 tls: Option<Tls>,
296}
297
298pub(crate) async fn partitions_of(
301 client: &Client,
302 what: &str,
303 base: Duration,
304 stopped: &mut tokio::sync::watch::Receiver<bool>,
305) -> Option<Vec<(String, Client)>> {
306 let mut attempt = 0;
307 loop {
308 let read = tokio::select! {
309 read = client.partitions() => read,
310 _ = stopped.wait_for(|s| *s) => return None,
311 };
312 match read {
313 Ok(parts) => return Some(parts),
314 Err(status) => {
315 attempt += 1;
316 let error: BoxError = status.into();
317 let delay = log::reconnecting(&client.log, what, Some(&error), base, attempt);
318 tokio::select! {
319 () = tokio::time::sleep(delay) => {}
320 _ = stopped.wait_for(|s| *s) => return None,
321 }
322 }
323 }
324 }
325}
326
327pub(crate) fn partition_of<'a>(map: &'a proto::PartitionMap, tenant: &str) -> &'a str {
329 map.tenants
330 .iter()
331 .find(|t| t.tenant == tenant)
332 .map_or(map.default.as_str(), |t| t.partition.as_str())
333}
334
335pub(crate) fn moving(status: &tonic::Status) -> bool {
337 status.code() == tonic::Code::Unavailable && status.message().starts_with("moving")
338}
339
340const MOVE_WAIT: Duration = Duration::from_secs(30);
342
343pub(crate) fn wrong_partition(status: &tonic::Status) -> bool {
345 status.code() == tonic::Code::FailedPrecondition
346 && status.message().starts_with("wrong_partition")
347}
348
349#[derive(Clone)]
351pub(crate) struct Client {
352 channels: Arc<Channels>,
353 parts: Arc<Partitions>,
354 key: Arc<SigningKey>,
355 key_id: String,
356 grant: Option<MetadataValue<tonic::metadata::Ascii>>,
357 log: log::Log,
358 timeout: Duration,
359 deployment: String,
361}
362
363impl Client {
364 pub(crate) async fn partition_map(
367 &self,
368 refresh: bool,
369 ) -> Result<Option<proto::PartitionMap>, tonic::Status> {
370 let mut held = self.parts.map.lock().await;
371 if refresh {
372 *held = None;
373 }
374 if let Some(map) = held.as_ref() {
375 return Ok(map.clone());
376 }
377 let request = proto::MapRequest { protocol: PROTOCOL };
378 let map = match self
379 .call_with(None, request, true, |channel, r| async move {
380 PartitionServiceClient::new(channel).map(r).await
381 })
382 .await
383 {
384 Ok(map) => Some(map),
385 Err(s) if matches!(s.code(), tonic::Code::NotFound | tonic::Code::Unimplemented) => {
386 None
387 }
388 Err(s) => return Err(s),
389 };
390 *held = Some(map.clone());
391 Ok(map)
392 }
393
394 fn on_partition(&self, map: &proto::PartitionMap, name: &str) -> Result<Client, tonic::Status> {
396 let partition = map
397 .partitions
398 .iter()
399 .find(|p| p.name == name)
400 .ok_or_else(|| {
401 tonic::Status::internal(format!("the partition map names no partition {name}"))
402 })?;
403 let own: Vec<&String> = partition
405 .addresses
406 .iter()
407 .filter(|a| !a.starts_with("relay:"))
408 .collect();
409 if own.is_empty() {
410 return Err(tonic::Status::unavailable(format!(
411 "partition {name} is reached only through a relay: a client needs one of its own addresses"
412 )));
413 }
414 let addresses = own.iter().map(|a| a.as_str()).collect::<Vec<_>>().join(",");
415 let mut cached = self.parts.channels.lock().unwrap();
416 let channels = match cached.get(&addresses) {
417 Some(channels) => Arc::clone(channels),
418 None => {
419 let all = own
420 .iter()
421 .map(|a| {
422 transport::connect_lazy_among(a, self.parts.tls.as_ref(), own.len() > 1)
423 .map(std::sync::Mutex::new)
424 .map_err(|e| {
425 tonic::Status::internal(format!("partition {name}, {a}: {e}"))
426 })
427 })
428 .collect::<Result<Vec<_>, _>>()?;
429 let channels = Arc::new(Channels {
430 all,
431 addresses: own.iter().map(|a| a.to_string()).collect(),
432 tls: self.parts.tls.clone(),
433 current: Default::default(),
434 seen: Default::default(),
435 });
436 cached.insert(addresses, Arc::clone(&channels));
437 channels
438 }
439 };
440 Ok(Client {
441 channels,
442 ..self.clone()
443 })
444 }
445
446 pub(crate) async fn for_tenant(&self, tenant: &str) -> Result<Client, tonic::Status> {
448 match self.partition_map(false).await? {
449 None => Ok(self.clone()),
450 Some(map) => {
451 let name = partition_of(&map, tenant).to_owned();
452 self.on_partition(&map, &name)
453 }
454 }
455 }
456
457 pub(crate) async fn control(&self) -> Result<Client, tonic::Status> {
459 match self.partition_map(false).await? {
460 None => Ok(self.clone()),
461 Some(map) => self.on_partition(&map, &map.control),
462 }
463 }
464
465 pub(crate) async fn partitions(&self) -> Result<Vec<(String, Client)>, tonic::Status> {
467 match self.partition_map(false).await? {
468 None => Ok(vec![(String::new(), self.clone())]),
469 Some(map) => map
470 .partitions
471 .iter()
472 .map(|p| Ok((p.name.clone(), self.on_partition(&map, &p.name)?)))
473 .collect(),
474 }
475 }
476
477 pub(crate) async fn routed<R, Fut>(
481 &self,
482 tenant: &str,
483 mut call: impl FnMut(Client) -> Fut,
484 ) -> Result<R, tonic::Status>
485 where
486 Fut: Future<Output = Result<R, tonic::Status>>,
487 {
488 let mut attempt = 0;
489 let deadline = Instant::now() + MOVE_WAIT;
490 let mut pause = Duration::from_millis(50);
491 loop {
492 let client = self.for_tenant(tenant).await?;
493 match call(client).await {
494 Err(status) if moving(&status) && Instant::now() + pause < deadline => {
495 tokio::time::sleep(pause).await;
496 pause = (pause * 2).min(Duration::from_secs(1));
497 }
498 Err(status) if attempt < 3 && wrong_partition(&status) => {
499 attempt += 1;
500 self.partition_map(true).await?;
501 }
502 result => return result,
503 }
504 }
505 }
506
507 pub(crate) fn channel(&self) -> (usize, Channel) {
509 let at = self
510 .channels
511 .current
512 .load(std::sync::atomic::Ordering::SeqCst);
513 (at, self.channels.all[at].lock().unwrap().clone())
514 }
515
516 pub(crate) fn ended(&self, at: usize, status: &tonic::Status) -> bool {
521 if stale_connection(status)
522 && let Ok(fresh) = transport::connect_lazy_among(
523 &self.channels.addresses[at],
524 self.channels.tls.as_ref(),
525 self.channels.all.len() > 1,
526 )
527 {
528 *self.channels.all[at].lock().unwrap() = fresh;
529 }
530 let n = self.channels.all.len();
531 let away = status.code() == tonic::Code::Unavailable || not_connected(status);
532 if n > 1 && away {
533 let _ = self.channels.current.compare_exchange(
534 at,
535 (at + 1) % n,
536 std::sync::atomic::Ordering::SeqCst,
537 std::sync::atomic::Ordering::SeqCst,
538 );
539 }
540 n > 1 && away
541 }
542
543 async fn call<T: Clone, R, Fut>(
550 &self,
551 timeout: Option<Duration>,
552 message: T,
553 call: impl FnMut(Channel, tonic::Request<T>) -> Fut,
554 ) -> Result<R, tonic::Status>
555 where
556 Fut: Future<Output = Result<tonic::Response<R>, tonic::Status>>,
557 {
558 self.call_with(timeout, message, false, call).await
559 }
560
561 async fn call_with<T: Clone, R, Fut>(
567 &self,
568 timeout: Option<Duration>,
569 message: T,
570 idempotent: bool,
571 mut call: impl FnMut(Channel, tonic::Request<T>) -> Fut,
572 ) -> Result<R, tonic::Status>
573 where
574 Fut: Future<Output = Result<tonic::Response<R>, tonic::Status>>,
575 {
576 let timeout = timeout.unwrap_or(self.timeout);
577 let deadline = Instant::now() + timeout;
578 let mut pause = Duration::from_millis(50);
579 let mut dropped_at: Option<Instant> = None;
583 loop {
584 let left = deadline.saturating_duration_since(Instant::now());
585 let mut request = self.request(message.clone());
586 request.set_timeout(left);
587 let (at, channel) = self.channel();
588 let result = match tokio::time::timeout(left, call(channel, request)).await {
589 Ok(result) => result,
590 Err(_) => Err(tonic::Status::deadline_exceeded(format!(
591 "no answer from the kernel within {} ms",
592 timeout.as_millis()
593 ))),
594 };
595 match result {
596 Ok(response) => return Ok(response.into_inner()),
597 Err(status) if Instant::now() + pause < deadline && self.ended(at, &status) => {
598 tokio::time::sleep(pause).await;
599 pause = (pause * 2).min(MAX_PAUSE);
600 }
601 Err(status)
607 if idempotent
608 && status.code() == tonic::Code::Unavailable
609 && !moving(&status)
610 && !dropped(&status)
611 && !not_connected(&status)
612 && Instant::now() + pause < deadline =>
613 {
614 tokio::time::sleep(pause).await;
615 pause = (pause * 2).min(MAX_PAUSE);
616 }
617 Err(status)
618 if (not_connected(&status) || (idempotent && dropped(&status)))
619 && Instant::now() + pause < deadline
620 && dropped_at.is_none_or(|at| at.elapsed() < DROPPED_RETRY) =>
621 {
622 if dropped(&status) {
623 dropped_at.get_or_insert_with(Instant::now);
624 }
625 tokio::time::sleep(pause).await;
626 pause = (pause * 2).min(MAX_PAUSE);
627 }
628 Err(status) if not_connected(&status) => {
629 return Err(tonic::Status::deadline_exceeded(format!(
630 "no connection to the kernel within {} ms: {}",
631 timeout.as_millis(),
632 status.message()
633 )));
634 }
635 Err(status) => return Err(status),
636 }
637 }
638 }
639
640 fn request<T>(&self, message: T) -> tonic::Request<T> {
642 let mut request = tonic::Request::new(message);
643 if let Some(grant) = &self.grant {
644 request
645 .metadata_mut()
646 .insert("kernable-grant", grant.clone());
647 }
648 request
649 }
650
651 fn sign(&self, message: &[u8]) -> proto::Signature {
652 signing::sign(&self.key, message)
653 }
654}
655
656#[derive(Clone)]
666pub struct Kernable {
667 client: Client,
668 tenant: String,
669 context: RequestContext,
670 domains: Arc<RwLock<HashMap<String, Domain>>>,
671 service: String,
673}
674
675impl Kernable {
676 pub fn new(options: impl Into<Options>) -> Result<Kernable, Error> {
682 let options = options.into();
683 let url = options
684 .url
685 .or_else(|| std::env::var("KERNABLE_URL").ok())
686 .unwrap_or_else(|| "http://127.0.0.1:7233".into());
687 let key_file = options
688 .key
689 .or_else(|| std::env::var_os("KERNABLE_KEY").map(PathBuf::from))
690 .unwrap_or_else(|| PathBuf::from("app.key"));
691 let key = signing::read_signing_key(&key_file)
692 .map_err(|e| Error::Config(format!("key {}: {e}", key_file.display())))?;
693 let explicit = options
694 .grant
695 .clone()
696 .or_else(|| std::env::var_os("KERNABLE_GRANT").map(PathBuf::from));
697 let grant_file = explicit
698 .clone()
699 .unwrap_or_else(|| key_file.with_extension("grant"));
700 let grant = if explicit.is_some() || grant_file.exists() {
701 let hex = std::fs::read_to_string(&grant_file)
702 .map_err(|e| Error::Config(format!("grant {}: {e}", grant_file.display())))?;
703 let mut grant: MetadataValue<tonic::metadata::Ascii> = hex
704 .trim()
705 .parse()
706 .map_err(|_| Error::Config(format!("grant {} is not hex", grant_file.display())))?;
707 grant.set_sensitive(true);
711 Some(grant)
712 } else {
713 None
714 };
715 let tls = match options.tls {
716 Some(tls) => Some(tls),
717 None => tls_from_env()?,
718 };
719 let insecure = options
720 .insecure
721 .unwrap_or_else(|| std::env::var("KERNABLE_INSECURE").is_ok_and(|v| v == "1"));
722 if tls.is_none() && !insecure && !local(&url) {
723 return Err(Error::Config(format!(
724 "{url} is not on this machine: connect with TLS (Options::tls), or allow plain \
725 text with Options::insecure"
726 )));
727 }
728 let urls: Vec<&str> = url
732 .split(',')
733 .map(str::trim)
734 .filter(|u| !u.is_empty())
735 .collect();
736 let several = urls.len() > 1;
737 let all = urls
738 .iter()
739 .map(|u| {
740 transport::connect_lazy_among(u, tls.as_ref(), several)
741 .map(std::sync::Mutex::new)
742 .map_err(|e| Error::Config(format!("kernel {u}: {e}")))
743 })
744 .collect::<Result<Vec<_>, _>>()?;
745 if all.is_empty() {
746 return Err(Error::Config("no kernel address".into()));
747 }
748 let channels = Arc::new(Channels {
749 all,
750 addresses: urls.iter().map(|u| u.to_string()).collect(),
751 tls: tls.clone(),
752 current: Default::default(),
753 seen: Default::default(),
754 });
755 let service = options
756 .service
757 .or_else(|| std::env::var("KERNABLE_SERVICE").ok())
758 .unwrap_or_default();
759 let deployment = options
760 .deployment
761 .or_else(|| std::env::var("KERNABLE_DEPLOYMENT").ok())
762 .unwrap_or_default();
763 check_deployment(&deployment)?;
764 let key_id = signing::key_id(&key.verifying_key());
765 let log = log::Log::new(&url, &key_file, &key_id);
766 #[cfg(unix)]
768 if let Ok(meta) = std::fs::metadata(&key_file) {
769 let mode = std::os::unix::fs::PermissionsExt::mode(&meta.permissions()) & 0o777;
770 if mode & 0o077 != 0 {
771 let path = key_file.display();
772 log.warn("key", || {
773 format!("{path} can be read by other users (mode {mode:o}): chmod 600 {path}")
774 });
775 }
776 }
777 Ok(Kernable {
778 client: Client {
779 channels,
780 parts: Arc::new(Partitions {
781 map: tokio::sync::Mutex::default(),
782 channels: Default::default(),
783 tls: tls.clone(),
784 }),
785 key_id,
786 key: Arc::new(key),
787 grant,
788 log,
789 timeout: options.timeout,
790 deployment,
791 },
792 tenant: options.tenant,
793 context: options.context,
794 domains: Arc::default(),
795 service,
796 })
797 }
798
799 pub fn with_domain(&self, domain: &Domain) -> Kernable {
804 self.domains
805 .write()
806 .unwrap()
807 .insert(domain.name().to_owned(), domain.clone());
808 self.clone()
809 }
810
811 pub fn worker<S: State>(&self, aggregate: &Aggregate<S>) -> Worker {
815 Worker::new(self.client.clone(), self.service.clone()).aggregate(aggregate)
816 }
817
818 pub fn listener(&self, listener: &Listener) -> ListenerHandle {
823 ListenerHandle::new(self, listener, self.service.clone())
824 }
825
826 pub fn data(&self) -> Files {
830 Files::new(
831 self.client.clone(),
832 self.tenant.clone(),
833 self.context.clone(),
834 )
835 }
836
837 pub fn cache(&self) -> Cache {
841 Cache::new(
842 self.client.clone(),
843 self.tenant.clone(),
844 self.context.clone(),
845 )
846 }
847
848 pub async fn apply(&self, manifest: Manifest) -> Result<(), Error> {
863 let service = manifest
864 .service
865 .clone()
866 .unwrap_or_else(|| self.service.clone());
867 if service.is_empty() {
868 return Err(Error::Config(
869 "apply needs a service: set it with Manifest::service or Options::service".into(),
870 ));
871 }
872 let deployment = manifest
873 .deployment
874 .clone()
875 .unwrap_or_else(|| self.client.deployment.clone());
876 check_deployment(&deployment)?;
877 let manifest_switch = manifest.switch;
878 let membership = membership(service, deployment, manifest, issued_now());
879 let sig = self.client.sign(&signing::membership_message(&membership));
880 let request = ApplyRequest {
881 membership: Some(membership),
882 sig: Some(sig),
883 protocol: PROTOCOL,
884 force: manifest_switch == Switch::Now,
885 no_switch: manifest_switch == Switch::Never,
886 no_rollback: manifest_switch == Switch::CaughtUp,
887 };
888 self.client
891 .control()
892 .await?
893 .call_with(None, request, true, |channel, r| async move {
894 MembershipServiceClient::new(channel).apply(r).await
895 })
896 .await?;
897 Ok(())
898 }
899
900 pub async fn register_process(&self, process: &Process) -> Result<process::Registered, Error> {
909 let model = serde_json::to_vec(&process.model()?)?;
910 let issued_at = issued_now();
911 let sig = self
912 .client
913 .sign(&signing::process_message(&model, issued_at));
914 let request = ProcessRegistration {
915 model,
916 issued_at,
917 sig: Some(sig),
918 protocol: PROTOCOL,
919 };
920 let registered = self
921 .client
922 .control()
923 .await?
924 .call(None, request, |channel, r| async move {
925 ProcessServiceClient::new(channel).register(r).await
926 })
927 .await?;
928 Ok(process::Registered {
929 name: registered.name,
930 version: registered.version,
931 new: registered.new,
932 })
933 }
934
935 pub async fn process_act(&self, name: &str, context: RequestContext) -> Result<bool, Error> {
942 let context = context.to_wire();
943 let issued_at = issued_now();
944 let sig = self.client.sign(&signing::process_act_message(
945 name,
946 Some(&context),
947 issued_at,
948 ));
949 let request = ProcessActing {
950 name: name.to_owned(),
951 context: Some(context),
952 issued_at,
953 sig: Some(sig),
954 protocol: PROTOCOL,
955 };
956 let acted = self
957 .client
958 .control()
959 .await?
960 .call(None, request, |channel, r| async move {
961 ProcessServiceClient::new(channel).act(r).await
962 })
963 .await?;
964 Ok(acted.changed)
965 }
966
967 pub fn app(&self, app: App) -> Result<AppHandle, Error> {
980 AppHandle::new(self, app)
981 }
982
983 pub async fn submit(&self, submit: Submit) -> Result<Outcome, Error> {
998 if submit.at.is_some() {
999 return Err(Error::Config(
1000 "a scheduled command (`at`) has no outcome yet: use `enqueue`".into(),
1001 ));
1002 }
1003 let wait = submit.wait;
1004 let res = self.send(submit, wait.wire()).await?;
1005 match res.outcome {
1006 Some(command_result::Outcome::Rejected(r)) => {
1007 Ok(Outcome::Rejected(Rejected::from_wire(r)))
1008 }
1009 Some(command_result::Outcome::Committed(c)) => {
1010 let events: Vec<StoredEvent> = c
1012 .events
1013 .into_iter()
1014 .map(|e| StoredEvent::from_wire(e, &[]))
1015 .collect();
1016 if wait == Wait::Settled && !c.settled {
1017 return Err(Error::NotSettled(events));
1018 }
1019 Ok(Outcome::Committed(events))
1020 }
1021 Some(command_result::Outcome::Accepted(_)) => Err(Error::NotDue(res.command_id)),
1022 None => Err(Error::Status(tonic::Status::internal("no outcome"))),
1023 }
1024 }
1025
1026 pub async fn enqueue(&self, submit: Submit) -> Result<String, Error> {
1033 Ok(self.send(submit, WireWait::Accepted).await?.command_id)
1034 }
1035
1036 pub async fn cancel(&self, cancel: Cancel) -> Result<CancelOutcome, Error> {
1043 let mut request = CancelRequest {
1044 command_id: cancel.command_id,
1045 tenant_id: cancel.tenant.unwrap_or_else(|| self.tenant.clone()),
1046 context: Some(
1047 cancel
1048 .context
1049 .unwrap_or_else(|| self.context.clone())
1050 .to_wire(),
1051 ),
1052 issued_at: issued_now(),
1053 client_sig: None,
1054 protocol: PROTOCOL,
1055 };
1056 request.client_sig = Some(self.client.sign(&signing::cancel_message(&request)));
1057 let tenant = request.tenant_id.clone();
1058 let timeout = cancel.timeout;
1059 let res = self
1060 .client
1061 .routed(&tenant, |client| {
1062 let request = request.clone();
1063 async move {
1064 client
1066 .call_with(timeout, request, true, |channel, r| async move {
1067 CommandServiceClient::new(channel).cancel(r).await
1068 })
1069 .await
1070 }
1071 })
1072 .await?;
1073 match res.outcome {
1074 Some(cancel_result::Outcome::Cancelled(_)) => Ok(CancelOutcome::Cancelled),
1075 Some(cancel_result::Outcome::Rejected(r)) => {
1076 Ok(CancelOutcome::Rejected(Rejected::from_wire(r)))
1077 }
1078 None => Err(Error::Status(tonic::Status::internal("no outcome"))),
1079 }
1080 }
1081
1082 async fn send(&self, s: Submit, wait: WireWait) -> Result<proto::CommandResult, Error> {
1083 if s.until.is_some() && s.at.is_none() {
1084 return Err(Error::Config("`until` needs `at`".into()));
1085 }
1086 let command_id = s.id.unwrap_or_else(random_id);
1087 let vault = s.vault.clone().or_else(|| {
1088 self.domains
1089 .read()
1090 .unwrap()
1091 .get(&s.domain)
1092 .and_then(|d| d.command_vault(&s.command_type))
1093 });
1094 let sealed =
1095 vault::seal(&s.data, vault.as_ref(), &s.aggregate_id).map_err(Error::Config)?;
1096 let mut context = s.context.unwrap_or_else(|| self.context.clone());
1097 if context.correlation_id.is_empty() {
1098 context.correlation_id = command_id.clone();
1099 }
1100 let mut cmd = proto::Command {
1101 command_id,
1102 tenant_id: s.tenant.unwrap_or_else(|| self.tenant.clone()),
1103 domain: s.domain,
1104 aggregate_type: s.aggregate_type,
1105 aggregate_id: s.aggregate_id,
1106 command_type: s.command_type,
1107 payload: sealed.payload,
1108 client_sig: None,
1109 context: Some(context.to_wire()),
1110 vault_refs: sealed.refs,
1111 deliver_at: s.at.unwrap_or(0),
1112 deliver_until: s.until.unwrap_or(0),
1113 };
1114 cmd.client_sig = Some(self.client.sign(&signing::command_message(&cmd)));
1115 let request = SubmitRequest {
1116 command: Some(cmd),
1117 wait: wait.into(),
1118 protocol: PROTOCOL,
1119 vault: sealed.values,
1120 listener: handling(),
1121 };
1122 let tenant = request
1123 .command
1124 .as_ref()
1125 .map(|c| c.tenant_id.clone())
1126 .unwrap_or_default();
1127 let timeout = s.timeout;
1128 Ok(self
1129 .client
1130 .routed(&tenant, |client| {
1131 let request = request.clone();
1132 async move {
1133 let result = client
1134 .call_with(timeout, request, true, |channel, r| async move {
1135 CommandServiceClient::new(channel).submit(r).await
1136 })
1137 .await?;
1138 if let Some(command_result::Outcome::Committed(c)) = &result.outcome {
1139 let last = c.events.last().map_or(0, |e| e.global_position);
1140 client
1141 .channels
1142 .seen
1143 .fetch_max(c.position.max(last), std::sync::atomic::Ordering::SeqCst);
1144 }
1145 Ok(result)
1146 }
1147 })
1148 .await?)
1149 }
1150
1151 pub async fn query<T: DeserializeOwned>(&self, query: Query) -> Result<T, Error> {
1158 let declared = query.target.clone().or_else(|| {
1159 self.domains
1160 .read()
1161 .unwrap()
1162 .get(&query.domain)
1163 .and_then(|d| d.query_target(&query.query_type))
1164 });
1165 let target = declared.and_then(|t| t.wire(&query.domain, &query.data));
1166 let mut request = proto::QueryRequest {
1167 target,
1168 query_id: random_id(),
1169 tenant_id: query.tenant.unwrap_or_else(|| self.tenant.clone()),
1170 domain: query.domain,
1171 query_type: query.query_type,
1172 payload: encode(&query.data),
1173 context: Some(
1174 query
1175 .context
1176 .unwrap_or_else(|| self.context.clone())
1177 .to_wire(),
1178 ),
1179 min_position: query.min_position,
1180 issued_at: issued_now(),
1181 client_sig: None,
1182 protocol: PROTOCOL,
1183 listener: String::new(),
1184 wait_only: false,
1185 deployment: self.client.deployment.clone(),
1186 };
1187 let timeout = query.timeout;
1188 if query.all_partitions {
1189 self.caught_up_everywhere(&request, timeout).await?;
1190 request.issued_at = issued_now();
1191 }
1192 let listener = handling();
1193 let tenant = request.tenant_id.clone();
1194 let res = self
1195 .client
1196 .routed(&tenant, |client| {
1197 let mut request = request.clone();
1198 if listener.is_empty() {
1202 request.min_position = request.min_position.max(
1203 client
1204 .channels
1205 .seen
1206 .load(std::sync::atomic::Ordering::SeqCst),
1207 );
1208 }
1209 request.client_sig = Some(client.sign(&signing::query_message(&request)));
1210 request.listener = listener.clone();
1211 async move {
1212 client
1213 .call_with(timeout, request, true, |channel, r| async move {
1214 QueryServiceClient::new(channel).query(r).await
1215 })
1216 .await
1217 }
1218 })
1219 .await?;
1220 match res.outcome {
1221 Some(query_result::Outcome::Response(r)) => Ok(serde_json::from_value(decode(&r))?),
1222 Some(query_result::Outcome::Rejected(r)) => {
1223 Err(Error::Rejected(Rejected::from_wire(r)))
1224 }
1225 None => Err(Error::Status(tonic::Status::internal("no outcome"))),
1226 }
1227 }
1228
1229 pub async fn ask<Q: QueryType>(
1232 &self,
1233 query: Q,
1234 options: impl FnOnce(Query) -> Query,
1235 ) -> Result<Q::Answer, Error> {
1236 self.query(options(Query::of(query))).await
1237 }
1238
1239 async fn caught_up_everywhere(
1242 &self,
1243 query: &proto::QueryRequest,
1244 timeout: Option<Duration>,
1245 ) -> Result<(), Error> {
1246 let mut wait = proto::QueryRequest {
1247 wait_only: true,
1248 min_position: 0,
1249 payload: Vec::new(),
1250 ..query.clone()
1251 };
1252 wait.client_sig = Some(self.client.sign(&signing::query_message(&wait)));
1253 wait.listener = handling();
1254 let mut waits = tokio::task::JoinSet::new();
1255 for (_, client) in self.client.partitions().await? {
1256 let wait = wait.clone();
1257 waits.spawn(async move {
1258 client
1259 .call_with(timeout, wait, true, |channel, r| async move {
1260 QueryServiceClient::new(channel).query(r).await
1261 })
1262 .await
1263 });
1264 }
1265 while let Some(waited) = waits.join_next().await {
1266 waited.map_err(|e| Error::Status(tonic::Status::internal(e.to_string())))??;
1267 }
1268 Ok(())
1269 }
1270
1271 pub fn subscribe<F, Fut>(&self, options: SubscribeOptions, handler: F) -> Subscription
1279 where
1280 F: Fn(StoredEvent) -> Fut + Send + Sync + 'static,
1281 Fut: Future<Output = Result<(), BoxError>> + Send + 'static,
1282 {
1283 Subscription::start(self.client.clone(), options, handler)
1284 }
1285}
1286
1287#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1289pub enum Wait {
1290 #[default]
1294 Settled,
1295 Committed,
1298}
1299
1300impl Wait {
1301 fn wire(self) -> WireWait {
1302 match self {
1303 Wait::Settled => WireWait::Settled,
1304 Wait::Committed => WireWait::Committed,
1305 }
1306 }
1307}
1308
1309fn tls_from_env() -> Result<Option<Tls>, Error> {
1311 let var = |name| std::env::var_os(name).map(PathBuf::from);
1312 match (
1313 var("KERNABLE_TLS_CA"),
1314 var("KERNABLE_TLS_CERT"),
1315 var("KERNABLE_TLS_KEY"),
1316 ) {
1317 (None, None, None) => Ok(None),
1318 (Some(ca), Some(cert), Some(key)) => Ok(Some(Tls { ca, cert, key })),
1319 _ => Err(Error::Config(
1320 "set all of KERNABLE_TLS_CA, KERNABLE_TLS_CERT and KERNABLE_TLS_KEY, or none".into(),
1321 )),
1322 }
1323}
1324
1325fn membership(
1327 service: String,
1328 deployment: String,
1329 manifest: Manifest,
1330 issued_at: i64,
1331) -> Membership {
1332 Membership {
1333 service,
1334 workers: manifest.workers,
1335 listeners: manifest.listeners,
1336 middlewares: manifest.middlewares,
1337 metadata: manifest
1338 .metadata
1339 .into_iter()
1340 .map(|(key, value)| Attribute { key, value })
1341 .collect(),
1342 issued_at,
1343 processes: manifest.processes,
1344 deployment,
1345 }
1346}
1347
1348fn check_deployment(deployment: &str) -> Result<(), Error> {
1350 let valid = deployment.len() <= 128
1351 && deployment
1352 .chars()
1353 .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'));
1354 if valid {
1355 Ok(())
1356 } else {
1357 Err(Error::Config(format!(
1358 "deployment {deployment:?}: use 1 to 128 letters, digits, `-`, `_` and `.`"
1359 )))
1360 }
1361}
1362
1363#[derive(Clone, Debug, Default, PartialEq, Eq)]
1367pub struct Manifest {
1368 service: Option<String>,
1369 workers: Vec<String>,
1370 listeners: Vec<String>,
1371 middlewares: Vec<String>,
1372 metadata: Vec<(String, String)>,
1373 processes: Vec<String>,
1374 deployment: Option<String>,
1375 switch: Switch,
1376}
1377
1378#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1381pub enum Switch {
1382 #[default]
1391 CaughtUp,
1392 Now,
1394 Never,
1398}
1399
1400impl Switch {
1401 pub fn from_env() -> Result<Switch, Error> {
1403 match std::env::var("KERNABLE_SWITCH").as_deref() {
1404 Err(_) | Ok("" | "caught-up") => Ok(Switch::CaughtUp),
1405 Ok("now") => Ok(Switch::Now),
1406 Ok("never") => Ok(Switch::Never),
1407 Ok(other) => Err(Error::Config(format!(
1408 "KERNABLE_SWITCH={other}: caught-up, now or never"
1409 ))),
1410 }
1411 }
1412}
1413
1414impl Manifest {
1415 pub fn new() -> Manifest {
1417 Manifest::default()
1418 }
1419
1420 pub fn service(mut self, service: impl Into<String>) -> Manifest {
1422 self.service = Some(service.into());
1423 self
1424 }
1425
1426 pub fn worker<S: State>(mut self, aggregate: &Aggregate<S>) -> Manifest {
1429 self.workers.push(format!(
1430 "{}.{}",
1431 aggregate.domain().name(),
1432 aggregate.name()
1433 ));
1434 self
1435 }
1436
1437 pub fn listener(mut self, listener: &Listener) -> Manifest {
1439 self.listeners.push(listener.name().to_owned());
1440 self
1441 }
1442
1443 pub fn middleware(mut self, listener: &Listener) -> Manifest {
1445 self.middlewares.push(listener.name().to_owned());
1446 self
1447 }
1448
1449 pub fn process(mut self, process: &Process) -> Manifest {
1453 self.processes.push(process.name());
1454 self
1455 }
1456
1457 pub fn metadata(mut self, key: impl Into<String>, value: impl Into<String>) -> Manifest {
1459 self.metadata.push((key.into(), value.into()));
1460 self
1461 }
1462
1463 pub fn deployment(mut self, deployment: impl Into<String>) -> Manifest {
1469 self.deployment = Some(deployment.into());
1470 self
1471 }
1472
1473 pub fn switch(mut self, switch: Switch) -> Manifest {
1476 self.switch = switch;
1477 self
1478 }
1479}
1480
1481#[derive(Clone, Debug)]
1486pub struct Submit {
1487 domain: String,
1488 aggregate_type: String,
1489 aggregate_id: String,
1490 command_type: String,
1491 data: Value,
1492 tenant: Option<String>,
1493 id: Option<String>,
1494 context: Option<RequestContext>,
1495 wait: Wait,
1496 timeout: Option<Duration>,
1497 vault: Option<vault::VaultFields>,
1499 at: Option<i64>,
1501 until: Option<i64>,
1502}
1503
1504impl Submit {
1505 pub fn new(
1508 domain: &str,
1509 aggregate_type: &str,
1510 aggregate_id: &str,
1511 command_type: &str,
1512 ) -> Submit {
1513 Submit {
1514 domain: domain.to_owned(),
1515 aggregate_type: aggregate_type.to_owned(),
1516 aggregate_id: aggregate_id.to_owned(),
1517 command_type: command_type.to_owned(),
1518 data: Value::Null,
1519 tenant: None,
1520 id: None,
1521 context: None,
1522 wait: Wait::Settled,
1523 timeout: None,
1524 vault: None,
1525 at: None,
1526 until: None,
1527 }
1528 }
1529
1530 pub fn command<C: CommandType>(command: C, aggregate_id: &str) -> Submit {
1538 let vault = messages::domain_of::<C>().command_vault(C::TYPE);
1539 Submit {
1540 vault,
1541 ..Submit::new(C::DOMAIN, C::AGGREGATE, aggregate_id, C::TYPE).data(command)
1542 }
1543 }
1544
1545 pub fn data(mut self, data: impl Serialize) -> Submit {
1551 self.data = serde_json::to_value(data).expect("command data is JSON");
1552 self
1553 }
1554
1555 pub fn tenant(mut self, tenant: impl Into<String>) -> Submit {
1557 self.tenant = Some(tenant.into());
1558 self
1559 }
1560
1561 pub fn id(mut self, id: impl Into<String>) -> Submit {
1564 self.id = Some(id.into());
1565 self
1566 }
1567
1568 pub fn context(mut self, context: RequestContext) -> Submit {
1570 self.context = Some(context);
1571 self
1572 }
1573
1574 pub fn at(mut self, time: SystemTime) -> Submit {
1579 self.at = Some(millis(time));
1580 self
1581 }
1582
1583 pub fn until(mut self, time: SystemTime) -> Submit {
1587 self.until = Some(millis(time));
1588 self
1589 }
1590
1591 pub fn wait(mut self, wait: Wait) -> Submit {
1593 self.wait = wait;
1594 self
1595 }
1596
1597 pub fn timeout(mut self, timeout: Duration) -> Submit {
1599 self.timeout = Some(timeout);
1600 self
1601 }
1602}
1603
1604fn millis(time: SystemTime) -> i64 {
1606 time.duration_since(UNIX_EPOCH)
1607 .map_or(0, |d| i64::try_from(d.as_millis()).unwrap_or(i64::MAX))
1608}
1609
1610#[derive(Clone, Debug)]
1613pub struct Cancel {
1614 command_id: String,
1615 tenant: Option<String>,
1616 context: Option<RequestContext>,
1617 timeout: Option<Duration>,
1618}
1619
1620impl Cancel {
1621 pub fn new(command_id: &str) -> Cancel {
1623 Cancel {
1624 command_id: command_id.to_owned(),
1625 tenant: None,
1626 context: None,
1627 timeout: None,
1628 }
1629 }
1630
1631 pub fn tenant(mut self, tenant: impl Into<String>) -> Cancel {
1633 self.tenant = Some(tenant.into());
1634 self
1635 }
1636
1637 pub fn context(mut self, context: RequestContext) -> Cancel {
1639 self.context = Some(context);
1640 self
1641 }
1642
1643 pub fn timeout(mut self, timeout: Duration) -> Cancel {
1645 self.timeout = Some(timeout);
1646 self
1647 }
1648}
1649
1650#[derive(Clone, Debug, PartialEq)]
1652pub enum CancelOutcome {
1653 Cancelled,
1655 Rejected(Rejected),
1658}
1659
1660impl CancelOutcome {
1661 pub fn is_cancelled(&self) -> bool {
1663 matches!(self, CancelOutcome::Cancelled)
1664 }
1665}
1666
1667#[derive(Clone, Debug)]
1671pub struct Query {
1672 domain: String,
1673 query_type: String,
1674 data: Value,
1675 tenant: Option<String>,
1676 context: Option<RequestContext>,
1677 min_position: u64,
1678 timeout: Option<Duration>,
1679 all_partitions: bool,
1680 target: Option<QueryTarget>,
1682}
1683
1684impl Query {
1685 pub fn new(domain: &str, query_type: &str) -> Query {
1687 Query {
1688 domain: domain.to_owned(),
1689 query_type: query_type.to_owned(),
1690 data: Value::Null,
1691 tenant: None,
1692 context: None,
1693 min_position: 0,
1694 timeout: None,
1695 all_partitions: false,
1696 target: None,
1697 }
1698 }
1699
1700 pub fn of<Q: QueryType>(query: Q) -> Query {
1707 let target = messages::domain_of::<Q>().query_target(Q::TYPE);
1708 Query {
1709 target,
1710 ..Query::new(Q::DOMAIN, Q::TYPE).data(query)
1711 }
1712 }
1713
1714 pub fn data(mut self, data: impl Serialize) -> Query {
1720 self.data = serde_json::to_value(data).expect("query data is JSON");
1721 self
1722 }
1723
1724 pub fn tenant(mut self, tenant: impl Into<String>) -> Query {
1726 self.tenant = Some(tenant.into());
1727 self
1728 }
1729
1730 pub fn context(mut self, context: RequestContext) -> Query {
1732 self.context = Some(context);
1733 self
1734 }
1735
1736 pub fn min_position(mut self, position: u64) -> Query {
1739 self.min_position = position;
1740 self
1741 }
1742
1743 pub fn timeout(mut self, timeout: Duration) -> Query {
1745 self.timeout = Some(timeout);
1746 self
1747 }
1748
1749 pub fn all_partitions(mut self) -> Query {
1753 self.all_partitions = true;
1754 self
1755 }
1756}
1757
1758#[derive(Clone, Debug, PartialEq)]
1760pub enum Outcome {
1761 Committed(Vec<StoredEvent>),
1764 Rejected(Rejected),
1767}
1768
1769impl Outcome {
1770 pub fn is_committed(&self) -> bool {
1772 matches!(self, Outcome::Committed(_))
1773 }
1774
1775 pub fn events(&self) -> &[StoredEvent] {
1777 match self {
1778 Outcome::Committed(events) => events,
1779 Outcome::Rejected(_) => &[],
1780 }
1781 }
1782}
1783
1784#[derive(Clone, Debug, PartialEq)]
1787pub enum QueryOutcome {
1788 Answered(Value),
1790 Rejected(Rejected),
1792}
1793
1794impl QueryOutcome {
1795 pub fn is_answered(&self) -> bool {
1797 matches!(self, QueryOutcome::Answered(_))
1798 }
1799}
1800
1801#[derive(Clone, Debug, PartialEq)]
1804pub struct StoredEvent {
1805 pub position: u64,
1807 pub tenant: String,
1808 pub domain: String,
1810 pub aggregate_type: String,
1811 pub aggregate_id: String,
1812 pub version: u64,
1814 pub event_type: String,
1816 pub schema: u32,
1819 pub data: Value,
1821 pub redacted: Vec<String>,
1824 pub command_id: String,
1826 pub created_at: Timestamp,
1828 pub request: RequestContext,
1830 pub deployment: String,
1832}
1833
1834impl StoredEvent {
1835 pub fn parse<D: DeserializeOwned>(&self) -> Result<D, serde_json::Error> {
1837 serde_json::from_value(self.data.clone())
1838 }
1839
1840 pub(crate) fn from_wire(e: proto::Event, vault: &[proto::VaultValue]) -> StoredEvent {
1841 let (data, redacted) = vault::unseal(decode(&e.payload), vault);
1842 StoredEvent {
1843 position: e.global_position,
1844 tenant: e.tenant_id,
1845 domain: e.domain,
1846 aggregate_type: e.aggregate_type,
1847 aggregate_id: e.aggregate_id,
1848 version: e.version,
1849 event_type: e.event_type,
1850 schema: e.schema,
1851 data,
1852 redacted,
1853 command_id: e.command_id,
1854 created_at: Timestamp(e.created_at),
1855 request: RequestContext::from_wire(e.context.as_ref()),
1856 deployment: e.deployment,
1857 }
1858 }
1859}
1860
1861fn dropped(status: &tonic::Status) -> bool {
1865 use std::io::ErrorKind::{BrokenPipe, ConnectionAborted, ConnectionReset, UnexpectedEof};
1866 if !matches!(
1869 status.code(),
1870 tonic::Code::Unknown
1871 | tonic::Code::Unavailable
1872 | tonic::Code::Internal
1873 | tonic::Code::Cancelled
1874 ) {
1875 return false;
1876 }
1877 let mut source = std::error::Error::source(status);
1878 while let Some(e) = source {
1879 if let Some(io) = e.downcast_ref::<std::io::Error>()
1880 && matches!(
1881 io.kind(),
1882 ConnectionReset | ConnectionAborted | BrokenPipe | UnexpectedEof
1883 )
1884 {
1885 return true;
1886 }
1887 source = e.source();
1888 }
1889 let message = status.message();
1890 message.contains("transport error")
1891 || message.contains("connection closed")
1892 || message.contains("error reading a body from connection")
1893 || message.contains("h2 protocol error")
1894 || message.contains("operation was canceled")
1896}
1897
1898pub(crate) fn stale_connection(status: &tonic::Status) -> bool {
1905 match status.code() {
1906 tonic::Code::Unauthenticated => true,
1907 tonic::Code::InvalidArgument | tonic::Code::PermissionDenied => {
1908 status.message().contains("grant")
1909 }
1910 _ => false,
1911 }
1912}
1913
1914fn not_connected(status: &tonic::Status) -> bool {
1915 use std::io::ErrorKind::{AddrNotAvailable, ConnectionRefused, NotFound, TimedOut};
1916 let mut source = std::error::Error::source(status);
1917 while let Some(e) = source {
1918 if let Some(io) = e.downcast_ref::<std::io::Error>() {
1919 return matches!(
1920 io.kind(),
1921 ConnectionRefused | NotFound | AddrNotAvailable | TimedOut
1922 );
1923 }
1924 if e.to_string().contains("error trying to connect") {
1925 return true;
1926 }
1927 source = e.source();
1928 }
1929 false
1930}
1931
1932fn local(url: &str) -> bool {
1935 if url.contains(',') {
1936 return url.split(',').all(|u| local(u.trim()));
1937 }
1938 if url.starts_with("unix:") {
1939 return true;
1940 }
1941 let host = transport::tcp_addr(url);
1942 let host = host.rsplit_once(':').map_or(host, |(host, port)| {
1943 if port.chars().all(|c| c.is_ascii_digit()) {
1944 host
1945 } else {
1946 url
1947 }
1948 });
1949 let host = host.trim_start_matches('[').trim_end_matches(']');
1950 host == "localhost"
1951 || host == "::1"
1952 || host.strip_prefix("127.").is_some_and(|rest| {
1953 rest.split('.').count() == 3 && rest.split('.').all(|p| p.parse::<u8>().is_ok())
1954 })
1955}
1956
1957const MAX_PAUSE: Duration = Duration::from_millis(200);
1961
1962const DROPPED_RETRY: Duration = Duration::from_secs(5);
1966
1967#[cfg(test)]
1968mod dropped_tests {
1969 use super::*;
1970
1971 #[test]
1972 fn a_connection_that_dropped_under_way_counts_as_dropped_and_nothing_else_does() {
1973 assert!(dropped(&tonic::Status::unknown("transport error")));
1974 assert!(dropped(&tonic::Status::unavailable(
1975 "h2 protocol error: error reading a body from connection"
1976 )));
1977 assert!(dropped(&tonic::Status::cancelled(
1979 "h2 protocol error: error reading a body from connection"
1980 )));
1981 assert!(dropped(&tonic::Status::cancelled("operation was canceled")));
1982 assert!(!dropped(&tonic::Status::cancelled("Timeout expired")));
1983 assert!(!dropped(&tonic::Status::unknown("a worker's error")));
1984 assert!(!dropped(&tonic::Status::invalid_argument(
1985 "transport error"
1986 )));
1987 assert!(!dropped(&tonic::Status::deadline_exceeded(
1988 "transport error"
1989 )));
1990 }
1991}
1992
1993#[cfg(test)]
1994mod deployment_tests {
1995 use serde_json::Value;
1996
1997 use super::*;
1998
1999 #[test]
2002 fn a_membership_with_a_deployment_is_signed_as_the_test_vectors_say() {
2003 let path = concat!(
2004 env!("CARGO_MANIFEST_DIR"),
2005 "/../../proto/test-vectors/signing.json"
2006 );
2007 let vectors: Value = serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap();
2008 let vector = &vectors["membership_deployment"];
2009 let input = &vector["input"];
2010 let texts = |v: &Value| -> Vec<String> {
2011 v.as_array()
2012 .unwrap()
2013 .iter()
2014 .map(|s| s.as_str().unwrap().to_owned())
2015 .collect()
2016 };
2017 let manifest = Manifest {
2018 service: None,
2019 workers: texts(&input["workers"]),
2020 listeners: texts(&input["listeners"]),
2021 middlewares: texts(&input["middlewares"]),
2022 metadata: input["metadata"]
2023 .as_array()
2024 .unwrap()
2025 .iter()
2026 .map(|a| {
2027 let text = |k: &str| a[k].as_str().unwrap().to_owned();
2028 (text("key"), text("value"))
2029 })
2030 .collect(),
2031 processes: texts(&input["processes"]),
2032 deployment: None,
2033 switch: Switch::default(),
2034 };
2035 let membership = membership(
2036 input["service"].as_str().unwrap().to_owned(),
2037 input["deployment"].as_str().unwrap().to_owned(),
2038 manifest,
2039 input["issued_at"].as_i64().unwrap(),
2040 );
2041 let message = signing::membership_message(&membership);
2042 assert_eq!(hex::encode(&message), vector["message"].as_str().unwrap());
2043 let key = signing::signing_key_from_hex(vectors["key"]["seed"].as_str().unwrap()).unwrap();
2044 assert_eq!(
2045 hex::encode(signing::sign(&key, &message).sig),
2046 vector["signature"].as_str().unwrap()
2047 );
2048 }
2049
2050 #[test]
2051 fn a_deployment_is_letters_digits_dashes_underscores_and_dots() {
2052 for valid in ["", "v1", "2026-11-11.1", "a_b", &"x".repeat(128)] {
2053 assert!(check_deployment(valid).is_ok(), "{valid}");
2054 }
2055 for invalid in ["v 1", "v1@x", "ΓΌ", "a/b", &"x".repeat(129)] {
2056 assert!(
2057 matches!(check_deployment(invalid), Err(Error::Config(m)) if m.contains("1 to 128")),
2058 "{invalid}"
2059 );
2060 }
2061 }
2062
2063 #[test]
2066 fn an_app_waits_beside_while_its_deployment_has_not_caught_up_or_served_before() {
2067 let refused = Error::Status;
2068 for details in [
2069 "not_caught_up: deployment v2 has not caught up",
2070 "not_serving: shop is served by v1",
2071 "served_before: deployment v1 served shop before and v2 serves it now",
2072 ] {
2073 assert!(
2074 refused(tonic::Status::failed_precondition(details)).waits_for_switch(),
2075 "{details}"
2076 );
2077 }
2078 assert!(
2079 !refused(tonic::Status::failed_precondition(
2080 "key may not manage shop"
2081 ))
2082 .waits_for_switch()
2083 );
2084 assert!(!refused(tonic::Status::unavailable("served_before")).waits_for_switch());
2085 }
2086}