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<Channel>,
280 current: std::sync::atomic::AtomicUsize,
281 seen: std::sync::atomic::AtomicU64,
284}
285
286pub(crate) struct Partitions {
289 map: tokio::sync::Mutex<Option<Option<proto::PartitionMap>>>,
291 channels: std::sync::Mutex<HashMap<String, Arc<Channels>>>,
292 tls: Option<Tls>,
293}
294
295pub(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
324pub(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
332pub(crate) fn moving(status: &tonic::Status) -> bool {
334 status.code() == tonic::Code::Unavailable && status.message().starts_with("moving")
335}
336
337const MOVE_WAIT: Duration = Duration::from_secs(30);
339
340pub(crate) fn wrong_partition(status: &tonic::Status) -> bool {
342 status.code() == tonic::Code::FailedPrecondition
343 && status.message().starts_with("wrong_partition")
344}
345
346#[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 deployment: String,
358}
359
360impl Client {
361 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 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 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 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 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 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 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 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 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 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 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 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 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 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#[derive(Clone)]
649pub struct Kernable {
650 client: Client,
651 tenant: String,
652 context: RequestContext,
653 domains: Arc<RwLock<HashMap<String, Domain>>>,
654 service: String,
656}
657
658impl Kernable {
659 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 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 #[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 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 pub fn worker<S: State>(&self, aggregate: &Aggregate<S>) -> Worker {
790 Worker::new(self.client.clone(), self.service.clone()).aggregate(aggregate)
791 }
792
793 pub fn listener(&self, listener: &Listener) -> ListenerHandle {
798 ListenerHandle::new(self, listener, self.service.clone())
799 }
800
801 pub fn data(&self) -> Files {
805 Files::new(
806 self.client.clone(),
807 self.tenant.clone(),
808 self.context.clone(),
809 )
810 }
811
812 pub fn cache(&self) -> Cache {
816 Cache::new(
817 self.client.clone(),
818 self.tenant.clone(),
819 self.context.clone(),
820 )
821 }
822
823 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 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 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 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 pub fn app(&self, app: App) -> Result<AppHandle, Error> {
955 AppHandle::new(self, app)
956 }
957
958 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 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 pub async fn enqueue(&self, submit: Submit) -> Result<String, Error> {
1008 Ok(self.send(submit, WireWait::Accepted).await?.command_id)
1009 }
1010
1011 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 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 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 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 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 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 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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1264pub enum Wait {
1265 #[default]
1269 Settled,
1270 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
1284fn 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
1300fn 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
1323fn 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#[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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1356pub enum Switch {
1357 #[default]
1366 CaughtUp,
1367 Now,
1369 Never,
1373}
1374
1375impl Switch {
1376 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 pub fn new() -> Manifest {
1392 Manifest::default()
1393 }
1394
1395 pub fn service(mut self, service: impl Into<String>) -> Manifest {
1397 self.service = Some(service.into());
1398 self
1399 }
1400
1401 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 pub fn listener(mut self, listener: &Listener) -> Manifest {
1414 self.listeners.push(listener.name().to_owned());
1415 self
1416 }
1417
1418 pub fn middleware(mut self, listener: &Listener) -> Manifest {
1420 self.middlewares.push(listener.name().to_owned());
1421 self
1422 }
1423
1424 pub fn process(mut self, process: &Process) -> Manifest {
1428 self.processes.push(process.name());
1429 self
1430 }
1431
1432 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 pub fn deployment(mut self, deployment: impl Into<String>) -> Manifest {
1444 self.deployment = Some(deployment.into());
1445 self
1446 }
1447
1448 pub fn switch(mut self, switch: Switch) -> Manifest {
1451 self.switch = switch;
1452 self
1453 }
1454}
1455
1456#[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 vault: Option<vault::VaultFields>,
1474 at: Option<i64>,
1476 until: Option<i64>,
1477}
1478
1479impl Submit {
1480 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 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 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 pub fn tenant(mut self, tenant: impl Into<String>) -> Submit {
1532 self.tenant = Some(tenant.into());
1533 self
1534 }
1535
1536 pub fn id(mut self, id: impl Into<String>) -> Submit {
1539 self.id = Some(id.into());
1540 self
1541 }
1542
1543 pub fn context(mut self, context: RequestContext) -> Submit {
1545 self.context = Some(context);
1546 self
1547 }
1548
1549 pub fn at(mut self, time: SystemTime) -> Submit {
1554 self.at = Some(millis(time));
1555 self
1556 }
1557
1558 pub fn until(mut self, time: SystemTime) -> Submit {
1562 self.until = Some(millis(time));
1563 self
1564 }
1565
1566 pub fn wait(mut self, wait: Wait) -> Submit {
1568 self.wait = wait;
1569 self
1570 }
1571
1572 pub fn timeout(mut self, timeout: Duration) -> Submit {
1574 self.timeout = Some(timeout);
1575 self
1576 }
1577}
1578
1579fn 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#[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 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 pub fn tenant(mut self, tenant: impl Into<String>) -> Cancel {
1608 self.tenant = Some(tenant.into());
1609 self
1610 }
1611
1612 pub fn context(mut self, context: RequestContext) -> Cancel {
1614 self.context = Some(context);
1615 self
1616 }
1617
1618 pub fn timeout(mut self, timeout: Duration) -> Cancel {
1620 self.timeout = Some(timeout);
1621 self
1622 }
1623}
1624
1625#[derive(Clone, Debug, PartialEq)]
1627pub enum CancelOutcome {
1628 Cancelled,
1630 Rejected(Rejected),
1633}
1634
1635impl CancelOutcome {
1636 pub fn is_cancelled(&self) -> bool {
1638 matches!(self, CancelOutcome::Cancelled)
1639 }
1640}
1641
1642#[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 target: Option<QueryTarget>,
1657}
1658
1659impl Query {
1660 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 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 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 pub fn tenant(mut self, tenant: impl Into<String>) -> Query {
1701 self.tenant = Some(tenant.into());
1702 self
1703 }
1704
1705 pub fn context(mut self, context: RequestContext) -> Query {
1707 self.context = Some(context);
1708 self
1709 }
1710
1711 pub fn min_position(mut self, position: u64) -> Query {
1714 self.min_position = position;
1715 self
1716 }
1717
1718 pub fn timeout(mut self, timeout: Duration) -> Query {
1720 self.timeout = Some(timeout);
1721 self
1722 }
1723
1724 pub fn all_partitions(mut self) -> Query {
1728 self.all_partitions = true;
1729 self
1730 }
1731}
1732
1733#[derive(Clone, Debug, PartialEq)]
1735pub enum Outcome {
1736 Committed(Vec<StoredEvent>),
1739 Rejected(Rejected),
1742}
1743
1744impl Outcome {
1745 pub fn is_committed(&self) -> bool {
1747 matches!(self, Outcome::Committed(_))
1748 }
1749
1750 pub fn events(&self) -> &[StoredEvent] {
1752 match self {
1753 Outcome::Committed(events) => events,
1754 Outcome::Rejected(_) => &[],
1755 }
1756 }
1757}
1758
1759#[derive(Clone, Debug, PartialEq)]
1762pub enum QueryOutcome {
1763 Answered(Value),
1765 Rejected(Rejected),
1767}
1768
1769impl QueryOutcome {
1770 pub fn is_answered(&self) -> bool {
1772 matches!(self, QueryOutcome::Answered(_))
1773 }
1774}
1775
1776#[derive(Clone, Debug, PartialEq)]
1779pub struct StoredEvent {
1780 pub position: u64,
1782 pub tenant: String,
1783 pub domain: String,
1785 pub aggregate_type: String,
1786 pub aggregate_id: String,
1787 pub version: u64,
1789 pub event_type: String,
1791 pub schema: u32,
1794 pub data: Value,
1796 pub redacted: Vec<String>,
1799 pub command_id: String,
1801 pub created_at: Timestamp,
1803 pub request: RequestContext,
1805 pub deployment: String,
1807}
1808
1809impl StoredEvent {
1810 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
1836fn dropped(status: &tonic::Status) -> bool {
1840 use std::io::ErrorKind::{BrokenPipe, ConnectionAborted, ConnectionReset, UnexpectedEof};
1841 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 || 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
1891fn 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
1916const MAX_PAUSE: Duration = Duration::from_millis(200);
1920
1921const 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 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 #[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 #[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}