1use std::collections::BTreeMap;
13use std::collections::btree_map::Entry;
14use std::fmt::{Debug, Formatter};
15use std::net::SocketAddr;
16use std::pin::Pin;
17use std::str::FromStr;
18use std::sync::atomic::{AtomicUsize, Ordering};
19use std::sync::{Arc, Mutex, RwLock, Weak};
20use std::time::{Duration, Instant, SystemTime};
21
22use anyhow::{Error, anyhow};
23use async_trait::async_trait;
24use bytes::Bytes;
25use futures::Stream;
26use futures_util::StreamExt;
27use mz_dyncfg::{Config, ParameterScope};
28use mz_ore::cast::CastFrom;
29use mz_ore::collections::{HashMap, HashSet};
30use mz_ore::metrics::MetricsRegistry;
31use mz_ore::retry::RetryResult;
32use mz_ore::task::JoinHandle;
33use mz_persist::location::VersionedData;
34use mz_proto::{ProtoType, RustType};
35use prost::Message;
36use tokio::sync::mpsc::Sender;
37use tokio::sync::mpsc::error::TrySendError;
38use tokio_stream::wrappers::errors::BroadcastStreamRecvError;
39use tokio_stream::wrappers::{BroadcastStream, ReceiverStream};
40use tonic::metadata::{AsciiMetadataKey, AsciiMetadataValue, MetadataMap};
41use tonic::transport::Endpoint;
42use tonic::{Extensions, Request, Response, Status, Streaming};
43use tracing::{Instrument, debug, error, info, info_span, warn};
44
45use crate::ShardId;
46use crate::cache::{DynState, StateCache};
47use crate::cfg::PersistConfig;
48use crate::internal::metrics::{PubSubClientCallMetrics, PubSubServerMetrics};
49use crate::internal::service::proto_persist_pub_sub_client::ProtoPersistPubSubClient;
50use crate::internal::service::proto_persist_pub_sub_server::ProtoPersistPubSubServer;
51use crate::internal::service::{
52 ProtoPubSubMessage, ProtoPushDiff, ProtoSubscribe, ProtoUnsubscribe,
53 proto_persist_pub_sub_server, proto_pub_sub_message,
54};
55use crate::metrics::Metrics;
56
57pub(crate) const PUBSUB_CLIENT_ENABLED: Config<bool> = Config::new(
59 "persist_pubsub_client_enabled",
60 true,
61 "Whether to connect to the Persist PubSub service.",
62 ParameterScope::Environment,
63);
64
65pub(crate) const PUBSUB_PUSH_DIFF_ENABLED: Config<bool> = Config::new(
69 "persist_pubsub_push_diff_enabled",
70 true,
71 "Whether to push state diffs to Persist PubSub.",
72 ParameterScope::Environment,
73);
74
75pub(crate) const PUBSUB_SAME_PROCESS_DELEGATE_ENABLED: Config<bool> = Config::new(
79 "persist_pubsub_same_process_delegate_enabled",
80 true,
81 "Whether to push state diffs to Persist PubSub on the same process.",
82 ParameterScope::Environment,
83);
84
85pub(crate) const PUBSUB_CONNECT_ATTEMPT_TIMEOUT: Config<Duration> = Config::new(
87 "persist_pubsub_connect_attempt_timeout",
88 Duration::from_secs(5),
89 "Timeout per connection attempt to Persist PubSub service.",
90 ParameterScope::Environment,
91);
92
93pub(crate) const PUBSUB_REQUEST_TIMEOUT: Config<Duration> = Config::new(
95 "persist_pubsub_request_timeout",
96 Duration::from_secs(5),
97 "Timeout per request attempt to Persist PubSub service.",
98 ParameterScope::Environment,
99);
100
101pub(crate) const PUBSUB_CONNECT_MAX_BACKOFF: Config<Duration> = Config::new(
103 "persist_pubsub_connect_max_backoff",
104 Duration::from_secs(60),
105 "Maximum backoff when retrying connection establishment to Persist PubSub service.",
106 ParameterScope::Environment,
107);
108
109pub(crate) const PUBSUB_CLIENT_SENDER_CHANNEL_SIZE: Config<usize> = Config::new(
119 "persist_pubsub_client_sender_channel_size",
120 1024,
121 "Size of channel used to buffer send messages to PubSub service.",
122 ParameterScope::Environment,
123);
124
125pub(crate) const PUBSUB_CLIENT_RECEIVER_CHANNEL_SIZE: Config<usize> = Config::new(
131 "persist_pubsub_client_receiver_channel_size",
132 1024,
133 "Size of channel used to buffer received messages from PubSub service.",
134 ParameterScope::Environment,
135);
136
137pub(crate) const PUBSUB_SERVER_CONNECTION_CHANNEL_SIZE: Config<usize> = Config::new(
142 "persist_pubsub_server_connection_channel_size",
143 1024,
144 "Size of channel used per connection to buffer broadcasted messages from PubSub server.",
145 ParameterScope::Environment,
146);
147
148pub(crate) const PUBSUB_STATE_CACHE_SHARD_REF_CHANNEL_SIZE: Config<usize> = Config::new(
150 "persist_pubsub_state_cache_shard_ref_channel_size",
151 25,
152 "Size of channel used by the state cache to broadcast shard state references.",
153 ParameterScope::Environment,
154);
155
156pub(crate) const PUBSUB_RECONNECT_BACKOFF: Config<Duration> = Config::new(
158 "persist_pubsub_reconnect_backoff",
159 Duration::from_secs(5),
160 "Backoff after an established connection to Persist PubSub service fails.",
161 ParameterScope::Environment,
162);
163
164const MAX_GRPC_MESSAGE_SIZE: usize = usize::MAX;
169
170pub trait PersistPubSubClient {
175 fn connect(
177 pubsub_config: PersistPubSubClientConfig,
178 metrics: Arc<Metrics>,
179 ) -> PubSubClientConnection;
180}
181
182#[derive(Debug)]
184pub struct PubSubClientConnection {
185 pub sender: Arc<dyn PubSubSender>,
187 pub receiver: Box<dyn PubSubReceiver>,
189}
190
191impl PubSubClientConnection {
192 pub fn new(sender: Arc<dyn PubSubSender>, receiver: Box<dyn PubSubReceiver>) -> Self {
194 Self { sender, receiver }
195 }
196
197 pub fn noop() -> Self {
199 Self {
200 sender: Arc::new(NoopPubSubSender),
201 receiver: Box::new(futures::stream::empty()),
202 }
203 }
204}
205
206pub trait PubSubSender: std::fmt::Debug + Send + Sync {
208 fn push_diff(&self, shard_id: &ShardId, diff: &VersionedData);
210
211 fn subscribe(self: Arc<Self>, shard_id: &ShardId) -> Arc<ShardSubscriptionToken>;
219}
220
221trait PubSubSenderInternal: Debug + Send + Sync {
226 fn push_diff(&self, shard_id: &ShardId, diff: &VersionedData);
228
229 fn subscribe(&self, shard_id: &ShardId);
233
234 fn unsubscribe(&self, shard_id: &ShardId);
238}
239
240pub trait PubSubReceiver:
245 Stream<Item = ProtoPubSubMessage> + Send + Unpin + std::fmt::Debug
246{
247}
248
249impl<T> PubSubReceiver for T where
250 T: Stream<Item = ProtoPubSubMessage> + Send + Unpin + std::fmt::Debug
251{
252}
253
254pub struct ShardSubscriptionToken {
259 pub(crate) shard_id: ShardId,
260 sender: Arc<dyn PubSubSenderInternal>,
261}
262
263impl Debug for ShardSubscriptionToken {
264 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
265 let ShardSubscriptionToken {
266 shard_id,
267 sender: _sender,
268 } = self;
269 write!(f, "ShardSubscriptionToken({})", shard_id)
270 }
271}
272
273impl Drop for ShardSubscriptionToken {
274 fn drop(&mut self) {
275 self.sender.unsubscribe(&self.shard_id);
276 }
277}
278
279pub const PERSIST_PUBSUB_CALLER_KEY: &str = "persist-pubsub-caller-id";
281
282#[derive(Debug)]
284pub struct PersistPubSubClientConfig {
285 pub url: String,
287 pub caller_id: String,
289 pub persist_cfg: PersistConfig,
291}
292
293#[derive(Debug)]
299pub struct GrpcPubSubClient;
300
301impl GrpcPubSubClient {
302 async fn reconnect_to_server_forever(
303 send_requests: tokio::sync::broadcast::Sender<ProtoPubSubMessage>,
304 receiver_input: &tokio::sync::mpsc::Sender<ProtoPubSubMessage>,
305 sender: Arc<SubscriptionTrackingSender>,
306 metadata: MetadataMap,
307 config: PersistPubSubClientConfig,
308 metrics: Arc<Metrics>,
309 ) {
310 config.persist_cfg.configs_synced_once().await;
315
316 let mut is_first_connection_attempt = true;
317 loop {
318 let sender = Arc::clone(&sender);
319 metrics.pubsub_client.grpc_connection.connected.set(0);
320
321 if !PUBSUB_CLIENT_ENABLED.get(&config.persist_cfg) {
322 tokio::time::sleep(Duration::from_secs(5)).await;
323 continue;
324 }
325
326 if is_first_connection_attempt {
328 is_first_connection_attempt = false;
329 } else {
330 tokio::time::sleep(PUBSUB_RECONNECT_BACKOFF.get(&config.persist_cfg)).await;
331 }
332
333 info!("Connecting to Persist PubSub: {}", config.url);
334 let client = mz_ore::retry::Retry::default()
335 .clamp_backoff(PUBSUB_CONNECT_MAX_BACKOFF.get(&config.persist_cfg))
336 .retry_async(|_| async {
337 metrics
338 .pubsub_client
339 .grpc_connection
340 .connect_call_attempt_count
341 .inc();
342 let endpoint = match Endpoint::from_str(&config.url) {
343 Ok(endpoint) => endpoint,
344 Err(err) => return RetryResult::FatalErr(err),
345 };
346 ProtoPersistPubSubClient::connect(
347 endpoint
348 .connect_timeout(
349 PUBSUB_CONNECT_ATTEMPT_TIMEOUT.get(&config.persist_cfg),
350 )
351 .timeout(PUBSUB_REQUEST_TIMEOUT.get(&config.persist_cfg)),
352 )
353 .await
354 .into()
355 })
356 .await;
357
358 let mut client = match client {
359 Ok(client) => client.max_decoding_message_size(MAX_GRPC_MESSAGE_SIZE),
360 Err(err) => {
361 error!("fatal error connecting to persist pubsub: {:?}", err);
362 return;
363 }
364 };
365
366 metrics
367 .pubsub_client
368 .grpc_connection
369 .connection_established_count
370 .inc();
371 metrics.pubsub_client.grpc_connection.connected.set(1);
372
373 info!("Connected to Persist PubSub: {}", config.url);
374
375 let mut broadcast = BroadcastStream::new(send_requests.subscribe());
376 let broadcast_errors = metrics
377 .pubsub_client
378 .grpc_connection
379 .broadcast_recv_lagged_count
380 .clone();
381
382 let (cancel_tx, cancel_rx) = tokio::sync::oneshot::channel::<()>();
388
389 let broadcast_messages = async_stream::stream! {
393 let mut cancel_rx = std::pin::pin!(cancel_rx);
394 'reconnect: loop {
395 for id in sender.subscriptions() {
397 debug!("re-subscribing to shard: {id}");
398 let msg = proto_pub_sub_message::Message::Subscribe(
399 ProtoSubscribe {
400 shard_id: id.into_proto(),
401 },
402 );
403 yield create_request(msg);
404 }
405
406 loop {
408 tokio::select! {
409 message = broadcast.next() => {
410 debug!("sending pubsub message: {:?}", message);
411 match message {
412 Some(Ok(message)) => yield message,
413 Some(Err(BroadcastStreamRecvError::Lagged(i))) => {
414 broadcast_errors.inc_by(i);
415 continue 'reconnect;
416 }
417 None => {
418 debug!("exhausted pubsub broadcast stream; shutting down");
419 return;
420 }
421 }
422 }
423 _ = &mut cancel_rx => {
424 debug!("pubsub broadcast stream cancelled; shutting down");
425 return;
426 }
427 }
428 }
429 }
430 };
431 let pubsub_request =
432 Request::from_parts(metadata.clone(), Extensions::default(), broadcast_messages);
433
434 let responses = match client.pub_sub(pubsub_request).await {
435 Ok(response) => response.into_inner(),
436 Err(err) => {
437 warn!("pub_sub rpc error: {:?}", err);
438 continue;
439 }
440 };
441
442 let stream_completed = GrpcPubSubClient::consume_grpc_stream(
443 responses,
444 receiver_input,
445 &config,
446 metrics.as_ref(),
447 )
448 .await;
449
450 drop(cancel_tx);
451
452 match stream_completed {
453 Ok(_) => continue,
455 Err(err) => {
458 warn!("shutting down connection loop to Persist PubSub: {}", err);
459 return;
460 }
461 }
462 }
463 }
464
465 async fn consume_grpc_stream(
466 mut responses: Streaming<ProtoPubSubMessage>,
467 receiver_input: &Sender<ProtoPubSubMessage>,
468 config: &PersistPubSubClientConfig,
469 metrics: &Metrics,
470 ) -> Result<(), Error> {
471 loop {
472 if !PUBSUB_CLIENT_ENABLED.get(&config.persist_cfg) {
473 return Ok(());
474 }
475
476 debug!("awaiting next pubsub response");
477 match responses.next().await {
478 Some(Ok(message)) => {
479 debug!("received pubsub message: {:?}", message);
480 match receiver_input.send(message).await {
481 Ok(_) => {}
482 Err(err) => {
485 return Err(anyhow!("closing pubsub grpc client connection: {}", err));
486 }
487 }
488 }
489 Some(Err(err)) => {
490 metrics.pubsub_client.grpc_connection.grpc_error_count.inc();
491 warn!("pubsub client error: {:?}", err);
492 return Ok(());
493 }
494 None => return Ok(()),
495 }
496 }
497 }
498}
499
500impl PersistPubSubClient for GrpcPubSubClient {
501 fn connect(config: PersistPubSubClientConfig, metrics: Arc<Metrics>) -> PubSubClientConnection {
502 let (send_requests, _) = tokio::sync::broadcast::channel(
507 PUBSUB_CLIENT_SENDER_CHANNEL_SIZE.get(&config.persist_cfg),
508 );
509 let (receiver_input, receiver_output) = tokio::sync::mpsc::channel(
513 PUBSUB_CLIENT_RECEIVER_CHANNEL_SIZE.get(&config.persist_cfg),
514 );
515
516 let sender = Arc::new(SubscriptionTrackingSender::new(Arc::new(
517 GrpcPubSubSender {
518 metrics: Arc::clone(&metrics),
519 requests: send_requests.clone(),
520 },
521 )));
522 let pubsub_sender = Arc::clone(&sender);
523 mz_ore::task::spawn(
524 || "persist::rpc::client::connection".to_string(),
525 async move {
526 let mut metadata = MetadataMap::new();
527 metadata.insert(
528 AsciiMetadataKey::from_static(PERSIST_PUBSUB_CALLER_KEY),
529 AsciiMetadataValue::try_from(&config.caller_id)
530 .unwrap_or_else(|_| AsciiMetadataValue::from_static("unknown")),
531 );
532
533 GrpcPubSubClient::reconnect_to_server_forever(
534 send_requests,
535 &receiver_input,
536 pubsub_sender,
537 metadata,
538 config,
539 metrics,
540 )
541 .await;
542 },
543 );
544
545 PubSubClientConnection {
546 sender,
547 receiver: Box::new(ReceiverStream::new(receiver_output)),
548 }
549 }
550}
551
552struct GrpcPubSubSender {
554 metrics: Arc<Metrics>,
555 requests: tokio::sync::broadcast::Sender<ProtoPubSubMessage>,
556}
557
558impl Debug for GrpcPubSubSender {
559 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
560 let GrpcPubSubSender {
561 metrics: _metrics,
562 requests: _requests,
563 } = self;
564
565 write!(f, "GrpcPubSubSender")
566 }
567}
568
569fn create_request(message: proto_pub_sub_message::Message) -> ProtoPubSubMessage {
570 let now = SystemTime::now()
571 .duration_since(SystemTime::UNIX_EPOCH)
572 .expect("failed to get millis since epoch");
573
574 ProtoPubSubMessage {
575 timestamp: Some(now.into_proto()),
576 message: Some(message),
577 }
578}
579
580impl GrpcPubSubSender {
581 fn send(&self, message: proto_pub_sub_message::Message, metrics: &PubSubClientCallMetrics) {
582 let size = message.encoded_len();
583
584 match self.requests.send(create_request(message)) {
585 Ok(_) => {
586 metrics.succeeded.inc();
587 metrics.bytes_sent.inc_by(u64::cast_from(size));
588 }
589 Err(err) => {
590 metrics.failed.inc();
591 debug!("error sending client message: {}", err);
592 }
593 }
594 }
595}
596
597impl PubSubSenderInternal for GrpcPubSubSender {
598 fn push_diff(&self, shard_id: &ShardId, diff: &VersionedData) {
599 self.send(
600 proto_pub_sub_message::Message::PushDiff(ProtoPushDiff {
601 shard_id: shard_id.into_proto(),
602 seqno: diff.seqno.into_proto(),
603 diff: diff.data.clone(),
604 }),
605 &self.metrics.pubsub_client.sender.push,
606 )
607 }
608
609 fn subscribe(&self, shard_id: &ShardId) {
610 self.send(
611 proto_pub_sub_message::Message::Subscribe(ProtoSubscribe {
612 shard_id: shard_id.into_proto(),
613 }),
614 &self.metrics.pubsub_client.sender.subscribe,
615 )
616 }
617
618 fn unsubscribe(&self, shard_id: &ShardId) {
619 self.send(
620 proto_pub_sub_message::Message::Unsubscribe(ProtoUnsubscribe {
621 shard_id: shard_id.into_proto(),
622 }),
623 &self.metrics.pubsub_client.sender.unsubscribe,
624 )
625 }
626}
627
628#[derive(Debug)]
631struct SubscriptionTrackingSender {
632 delegate: Arc<dyn PubSubSenderInternal>,
633 subscribes: Arc<Mutex<BTreeMap<ShardId, Weak<ShardSubscriptionToken>>>>,
634}
635
636impl SubscriptionTrackingSender {
637 fn new(sender: Arc<dyn PubSubSenderInternal>) -> Self {
638 Self {
639 delegate: sender,
640 subscribes: Default::default(),
641 }
642 }
643
644 fn subscriptions(&self) -> Vec<ShardId> {
645 let mut subscribes = self.subscribes.lock().expect("lock");
646 let mut out = Vec::with_capacity(subscribes.len());
647 subscribes.retain(|shard_id, token| {
648 if token.upgrade().is_none() {
649 false
650 } else {
651 debug!("reconnecting to: {}", shard_id);
652 out.push(*shard_id);
653 true
654 }
655 });
656 out
657 }
658}
659
660impl PubSubSender for SubscriptionTrackingSender {
661 fn push_diff(&self, shard_id: &ShardId, diff: &VersionedData) {
662 self.delegate.push_diff(shard_id, diff)
663 }
664
665 fn subscribe(self: Arc<Self>, shard_id: &ShardId) -> Arc<ShardSubscriptionToken> {
666 let mut subscribes = self.subscribes.lock().expect("lock");
667 if let Some(token) = subscribes.get(shard_id) {
668 match token.upgrade() {
669 None => assert!(subscribes.remove(shard_id).is_some()),
670 Some(token) => {
671 return Arc::clone(&token);
672 }
673 }
674 }
675
676 let pubsub_sender = Arc::clone(&self.delegate);
677 let token = Arc::new(ShardSubscriptionToken {
678 shard_id: *shard_id,
679 sender: pubsub_sender,
680 });
681
682 assert!(
683 subscribes
684 .insert(*shard_id, Arc::downgrade(&token))
685 .is_none()
686 );
687
688 self.delegate.subscribe(shard_id);
689
690 token
691 }
692}
693
694#[derive(Debug)]
698pub struct MetricsSameProcessPubSubSender {
699 delegate_subscribe: bool,
700 metrics: Arc<Metrics>,
701 delegate: Arc<dyn PubSubSender>,
702}
703
704impl MetricsSameProcessPubSubSender {
705 pub fn new(
708 cfg: &PersistConfig,
709 pubsub_sender: Arc<dyn PubSubSender>,
710 metrics: Arc<Metrics>,
711 ) -> Self {
712 Self {
713 delegate_subscribe: PUBSUB_SAME_PROCESS_DELEGATE_ENABLED.get(cfg),
714 delegate: pubsub_sender,
715 metrics,
716 }
717 }
718}
719
720impl PubSubSender for MetricsSameProcessPubSubSender {
721 fn push_diff(&self, shard_id: &ShardId, diff: &VersionedData) {
722 self.delegate.push_diff(shard_id, diff);
723 self.metrics.pubsub_client.sender.push.succeeded.inc();
724 }
725
726 fn subscribe(self: Arc<Self>, shard_id: &ShardId) -> Arc<ShardSubscriptionToken> {
727 if self.delegate_subscribe {
728 let delegate = Arc::clone(&self.delegate);
729 delegate.subscribe(shard_id)
730 } else {
731 Arc::new(ShardSubscriptionToken {
737 shard_id: *shard_id,
738 sender: Arc::new(NoopPubSubSender),
739 })
740 }
741 }
742}
743
744#[derive(Debug)]
745pub(crate) struct NoopPubSubSender;
746
747impl PubSubSenderInternal for NoopPubSubSender {
748 fn push_diff(&self, _shard_id: &ShardId, _diff: &VersionedData) {}
749 fn subscribe(&self, _shard_id: &ShardId) {}
750 fn unsubscribe(&self, _shard_id: &ShardId) {}
751}
752
753impl PubSubSender for NoopPubSubSender {
754 fn push_diff(&self, _shard_id: &ShardId, _diff: &VersionedData) {}
755
756 fn subscribe(self: Arc<Self>, shard_id: &ShardId) -> Arc<ShardSubscriptionToken> {
757 Arc::new(ShardSubscriptionToken {
758 shard_id: *shard_id,
759 sender: self,
760 })
761 }
762}
763
764pub(crate) fn subscribe_state_cache_to_pubsub(
766 cache: Arc<StateCache>,
767 mut pubsub_receiver: Box<dyn PubSubReceiver>,
768) -> JoinHandle<()> {
769 let mut state_refs: HashMap<ShardId, Weak<dyn DynState>> = HashMap::new();
770 let receiver_metrics = cache.metrics.pubsub_client.receiver.clone();
771
772 mz_ore::task::spawn(
773 || "persist::rpc::client::state_cache_diff_apply",
774 async move {
775 while let Some(msg) = pubsub_receiver.next().await {
776 match msg.message {
777 Some(proto_pub_sub_message::Message::PushDiff(diff)) => {
778 receiver_metrics.push_received.inc();
779 let shard_id = diff.shard_id.into_rust().expect("valid shard id");
780 let diff = VersionedData {
781 seqno: diff.seqno.into_rust().expect("valid SeqNo"),
782 data: diff.diff,
783 };
784 debug!(
785 "applying pubsub diff {} {} {}",
786 shard_id,
787 diff.seqno,
788 diff.data.len()
789 );
790
791 let mut pushed_diff = false;
792 if let Some(state_ref) = state_refs.get(&shard_id) {
793 if let Some(state) = state_ref.upgrade() {
796 state.push_diff(diff.clone());
797 pushed_diff = true;
798 receiver_metrics.state_pushed_diff_fast_path.inc();
799 }
800 }
801
802 if !pushed_diff {
803 let state_ref = cache.get_state_weak(&shard_id);
808 match state_ref {
809 None => {
810 state_refs.remove(&shard_id);
811 }
812 Some(state_ref) => {
813 if let Some(state) = state_ref.upgrade() {
814 state.push_diff(diff);
815 pushed_diff = true;
816 state_refs.insert(shard_id, state_ref);
817 } else {
818 state_refs.remove(&shard_id);
819 }
820 }
821 }
822
823 if pushed_diff {
824 receiver_metrics.state_pushed_diff_slow_path_succeeded.inc();
825 } else {
826 receiver_metrics.state_pushed_diff_slow_path_failed.inc();
827 }
828 }
829
830 if let Some(send_timestamp) = msg.timestamp {
831 let send_timestamp =
832 send_timestamp.into_rust().expect("valid timestamp");
833 let now = SystemTime::now()
834 .duration_since(SystemTime::UNIX_EPOCH)
835 .expect("failed to get millis since epoch");
836 receiver_metrics
837 .approx_diff_latency_seconds
838 .observe((now.saturating_sub(send_timestamp)).as_secs_f64());
839 }
840 }
841 ref msg @ None | ref msg @ Some(_) => {
842 warn!("pubsub client received unexpected message: {:?}", msg);
843 receiver_metrics.unknown_message_received.inc();
844 }
845 }
846 }
847 },
848 )
849}
850
851#[derive(Debug)]
853pub(crate) struct PubSubState {
854 connection_id_counter: AtomicUsize,
856 shard_subscribers:
858 Arc<RwLock<BTreeMap<ShardId, BTreeMap<usize, Sender<Result<ProtoPubSubMessage, Status>>>>>>,
859 connections: Arc<RwLock<HashSet<usize>>>,
861 metrics: Arc<PubSubServerMetrics>,
863}
864
865impl PubSubState {
866 fn new_connection(
867 self: Arc<Self>,
868 notifier: Sender<Result<ProtoPubSubMessage, Status>>,
869 ) -> PubSubConnection {
870 let connection_id = self.connection_id_counter.fetch_add(1, Ordering::SeqCst);
871 {
872 debug!("inserting connid: {}", connection_id);
873 let mut connections = self.connections.write().expect("lock");
874 assert!(connections.insert(connection_id));
875 }
876
877 self.metrics.active_connections.inc();
878 PubSubConnection {
879 connection_id,
880 notifier,
881 state: self,
882 }
883 }
884
885 fn remove_connection(&self, connection_id: usize) {
886 let now = Instant::now();
887
888 {
889 debug!("removing connid: {}", connection_id);
890 let mut connections = self.connections.write().expect("lock");
891 assert!(
892 connections.remove(&connection_id),
893 "unknown connection id: {}",
894 connection_id
895 );
896 }
897
898 {
899 let mut subscribers = self.shard_subscribers.write().expect("lock poisoned");
900 subscribers.retain(|_shard, connections_for_shard| {
901 connections_for_shard.remove(&connection_id);
902 !connections_for_shard.is_empty()
903 });
904 }
905
906 self.metrics
907 .connection_cleanup_seconds
908 .inc_by(now.elapsed().as_secs_f64());
909 self.metrics.active_connections.dec();
910 }
911
912 fn push_diff(&self, connection_id: usize, shard_id: &ShardId, data: &VersionedData) {
913 let now = Instant::now();
914 self.metrics.push_call_count.inc();
915
916 assert!(
917 self.connections
918 .read()
919 .expect("lock")
920 .contains(&connection_id),
921 "unknown connection id: {}",
922 connection_id
923 );
924
925 let subscribers = self.shard_subscribers.read().expect("lock poisoned");
926 if let Some(subscribed_connections) = subscribers.get(shard_id) {
927 let mut num_sent = 0;
928 let mut data_size = 0;
929
930 for (subscribed_conn_id, tx) in subscribed_connections {
931 if *subscribed_conn_id == connection_id {
933 continue;
934 }
935 debug!(
936 "server forwarding req to conn {}: {} {} {}",
937 subscribed_conn_id,
938 &shard_id,
939 data.seqno,
940 data.data.len()
941 );
942 let req = create_request(proto_pub_sub_message::Message::PushDiff(ProtoPushDiff {
943 seqno: data.seqno.into_proto(),
944 shard_id: shard_id.to_string(),
945 diff: Bytes::clone(&data.data),
946 }));
947 data_size = req.encoded_len();
948 match tx.try_send(Ok(req)) {
949 Ok(_) => {
950 num_sent += 1;
951 }
952 Err(TrySendError::Full(_)) => {
953 self.metrics.broadcasted_diff_dropped_channel_full.inc();
954 }
955 Err(TrySendError::Closed(_)) => {}
956 };
957 }
958
959 self.metrics.broadcasted_diff_count.inc_by(num_sent);
960 self.metrics
961 .broadcasted_diff_bytes
962 .inc_by(num_sent * u64::cast_from(data_size));
963 }
964
965 self.metrics
966 .push_seconds
967 .inc_by(now.elapsed().as_secs_f64());
968 }
969
970 fn subscribe(
971 &self,
972 connection_id: usize,
973 notifier: Sender<Result<ProtoPubSubMessage, Status>>,
974 shard_id: &ShardId,
975 ) {
976 let now = Instant::now();
977 self.metrics.subscribe_call_count.inc();
978
979 assert!(
980 self.connections
981 .read()
982 .expect("lock")
983 .contains(&connection_id),
984 "unknown connection id: {}",
985 connection_id
986 );
987
988 {
989 let mut subscribed_shards = self.shard_subscribers.write().expect("lock poisoned");
990 subscribed_shards
991 .entry(*shard_id)
992 .or_default()
993 .insert(connection_id, notifier);
994 }
995
996 self.metrics
997 .subscribe_seconds
998 .inc_by(now.elapsed().as_secs_f64());
999 }
1000
1001 fn unsubscribe(&self, connection_id: usize, shard_id: &ShardId) {
1002 let now = Instant::now();
1003 self.metrics.unsubscribe_call_count.inc();
1004
1005 assert!(
1006 self.connections
1007 .read()
1008 .expect("lock")
1009 .contains(&connection_id),
1010 "unknown connection id: {}",
1011 connection_id
1012 );
1013
1014 {
1015 let mut subscribed_shards = self.shard_subscribers.write().expect("lock poisoned");
1016 if let Entry::Occupied(mut entry) = subscribed_shards.entry(*shard_id) {
1017 let subscribed_connections = entry.get_mut();
1018 subscribed_connections.remove(&connection_id);
1019
1020 if subscribed_connections.is_empty() {
1021 entry.remove_entry();
1022 }
1023 }
1024 }
1025
1026 self.metrics
1027 .unsubscribe_seconds
1028 .inc_by(now.elapsed().as_secs_f64());
1029 }
1030
1031 #[cfg(test)]
1032 fn new_for_test() -> Self {
1033 Self {
1034 connection_id_counter: AtomicUsize::new(0),
1035 shard_subscribers: Default::default(),
1036 connections: Default::default(),
1037 metrics: Arc::new(PubSubServerMetrics::new(&MetricsRegistry::new())),
1038 }
1039 }
1040
1041 #[cfg(test)]
1042 fn active_connections(&self) -> HashSet<usize> {
1043 self.connections.read().expect("lock").clone()
1044 }
1045
1046 #[cfg(test)]
1047 fn subscriptions(&self, connection_id: usize) -> HashSet<ShardId> {
1048 let mut shards = HashSet::new();
1049
1050 let subscribers = self.shard_subscribers.read().expect("lock");
1051 for (shard, subscribed_connections) in subscribers.iter() {
1052 if subscribed_connections.contains_key(&connection_id) {
1053 shards.insert(*shard);
1054 }
1055 }
1056
1057 shards
1058 }
1059
1060 #[cfg(test)]
1061 fn shard_subscription_counts(&self) -> mz_ore::collections::HashMap<ShardId, usize> {
1062 let mut shards = mz_ore::collections::HashMap::new();
1063
1064 let subscribers = self.shard_subscribers.read().expect("lock");
1065 for (shard, subscribed_connections) in subscribers.iter() {
1066 shards.insert(*shard, subscribed_connections.len());
1067 }
1068
1069 shards
1070 }
1071}
1072
1073#[derive(Debug)]
1075pub struct PersistGrpcPubSubServer {
1076 cfg: PersistConfig,
1077 state: Arc<PubSubState>,
1078}
1079
1080impl PersistGrpcPubSubServer {
1081 pub fn new(cfg: &PersistConfig, metrics_registry: &MetricsRegistry) -> Self {
1083 let metrics = PubSubServerMetrics::new(metrics_registry);
1084 let state = Arc::new(PubSubState {
1085 connection_id_counter: AtomicUsize::new(0),
1086 shard_subscribers: Default::default(),
1087 connections: Default::default(),
1088 metrics: Arc::new(metrics),
1089 });
1090
1091 PersistGrpcPubSubServer {
1092 cfg: cfg.clone(),
1093 state,
1094 }
1095 }
1096
1097 pub fn new_same_process_connection(&self) -> PubSubClientConnection {
1101 let (tx, rx) =
1102 tokio::sync::mpsc::channel(PUBSUB_CLIENT_RECEIVER_CHANNEL_SIZE.get(&self.cfg));
1103 let sender: Arc<dyn PubSubSender> = Arc::new(SubscriptionTrackingSender::new(Arc::new(
1104 Arc::clone(&self.state).new_connection(tx),
1105 )));
1106
1107 PubSubClientConnection {
1108 sender,
1109 receiver: Box::new(
1110 ReceiverStream::new(rx).map(|x| x.expect("cannot receive grpc errors locally")),
1111 ),
1112 }
1113 }
1114
1115 pub async fn serve(self, listen_addr: SocketAddr) -> Result<(), anyhow::Error> {
1117 tonic::transport::Server::builder()
1119 .add_service(
1120 ProtoPersistPubSubServer::new(self)
1121 .max_decoding_message_size(MAX_GRPC_MESSAGE_SIZE),
1122 )
1123 .serve(listen_addr)
1124 .await?;
1125 Ok(())
1126 }
1127
1128 pub async fn serve_with_stream(
1131 self,
1132 listener: tokio_stream::wrappers::TcpListenerStream,
1133 ) -> Result<(), anyhow::Error> {
1134 tonic::transport::Server::builder()
1135 .add_service(
1136 ProtoPersistPubSubServer::new(self)
1137 .max_decoding_message_size(MAX_GRPC_MESSAGE_SIZE),
1138 )
1139 .serve_with_incoming(listener)
1140 .await?;
1141 Ok(())
1142 }
1143}
1144
1145#[async_trait]
1146impl proto_persist_pub_sub_server::ProtoPersistPubSub for PersistGrpcPubSubServer {
1147 type PubSubStream = Pin<Box<dyn Stream<Item = Result<ProtoPubSubMessage, Status>> + Send>>;
1148
1149 #[mz_ore::instrument(name = "persist::rpc::server", level = "info")]
1150 async fn pub_sub(
1151 &self,
1152 request: Request<Streaming<ProtoPubSubMessage>>,
1153 ) -> Result<Response<Self::PubSubStream>, Status> {
1154 let caller_id = request
1155 .metadata()
1156 .get(AsciiMetadataKey::from_static(PERSIST_PUBSUB_CALLER_KEY))
1157 .map(|key| key.to_str().ok())
1158 .flatten()
1159 .map(|key| key.to_string())
1160 .unwrap_or_else(|| "unknown".to_string());
1161 info!("Received Persist PubSub connection from: {:?}", caller_id);
1162
1163 let mut in_stream = request.into_inner();
1164 let (tx, rx) =
1165 tokio::sync::mpsc::channel(PUBSUB_SERVER_CONNECTION_CHANNEL_SIZE.get(&self.cfg));
1166
1167 let caller = caller_id.clone();
1168 let cfg = Arc::clone(&self.cfg.configs);
1169 let server_state = Arc::clone(&self.state);
1170 let connection_span = info_span!("connection", caller_id);
1174 mz_ore::task::spawn(
1175 || format!("persist_pubsub_connection({})", caller),
1176 async move {
1177 let connection = server_state.new_connection(tx);
1178 while let Some(result) = in_stream.next().await {
1179 let req = match result {
1180 Ok(req) => req,
1181 Err(err) => {
1182 warn!("pubsub connection err: {}", err);
1183 break;
1184 }
1185 };
1186
1187 match req.message {
1188 None => {
1189 warn!("received empty message from: {}", caller_id);
1190 }
1191 Some(proto_pub_sub_message::Message::PushDiff(req)) => {
1192 let shard_id = req.shard_id.parse().expect("valid shard id");
1193 let diff = VersionedData {
1194 seqno: req.seqno.into_rust().expect("valid seqno"),
1195 data: req.diff.clone(),
1196 };
1197 if PUBSUB_PUSH_DIFF_ENABLED.get(&cfg) {
1198 connection.push_diff(&shard_id, &diff);
1199 }
1200 }
1201 Some(proto_pub_sub_message::Message::Subscribe(diff)) => {
1202 let shard_id = diff.shard_id.parse().expect("valid shard id");
1203 connection.subscribe(&shard_id);
1204 }
1205 Some(proto_pub_sub_message::Message::Unsubscribe(diff)) => {
1206 let shard_id = diff.shard_id.parse().expect("valid shard id");
1207 connection.unsubscribe(&shard_id);
1208 }
1209 }
1210 }
1211
1212 info!("Persist PubSub connection ended: {:?}", caller_id);
1213 }
1214 .instrument(connection_span),
1215 );
1216
1217 let out_stream: Self::PubSubStream = Box::pin(ReceiverStream::new(rx));
1218 Ok(Response::new(out_stream))
1219 }
1220}
1221
1222#[derive(Debug)]
1226pub(crate) struct PubSubConnection {
1227 connection_id: usize,
1228 notifier: Sender<Result<ProtoPubSubMessage, Status>>,
1229 state: Arc<PubSubState>,
1230}
1231
1232impl PubSubSenderInternal for PubSubConnection {
1233 fn push_diff(&self, shard_id: &ShardId, diff: &VersionedData) {
1234 self.state.push_diff(self.connection_id, shard_id, diff)
1235 }
1236
1237 fn subscribe(&self, shard_id: &ShardId) {
1238 self.state
1239 .subscribe(self.connection_id, self.notifier.clone(), shard_id)
1240 }
1241
1242 fn unsubscribe(&self, shard_id: &ShardId) {
1243 self.state.unsubscribe(self.connection_id, shard_id)
1244 }
1245}
1246
1247impl Drop for PubSubConnection {
1248 fn drop(&mut self) {
1249 self.state.remove_connection(self.connection_id)
1250 }
1251}
1252
1253#[cfg(test)]
1254mod pubsub_state {
1255 use std::str::FromStr;
1256 use std::sync::Arc;
1257 use std::sync::LazyLock;
1258
1259 use bytes::Bytes;
1260 use mz_ore::collections::HashSet;
1261 use mz_persist::location::{SeqNo, VersionedData};
1262 use mz_proto::RustType;
1263 use tokio::sync::mpsc::Receiver;
1264 use tokio::sync::mpsc::error::TryRecvError;
1265 use tonic::Status;
1266
1267 use crate::ShardId;
1268 use crate::internal::service::ProtoPubSubMessage;
1269 use crate::internal::service::proto_pub_sub_message::Message;
1270 use crate::rpc::{PubSubSenderInternal, PubSubState};
1271
1272 static SHARD_ID_0: LazyLock<ShardId> =
1273 LazyLock::new(|| ShardId::from_str("s00000000-0000-0000-0000-000000000000").unwrap());
1274 static SHARD_ID_1: LazyLock<ShardId> =
1275 LazyLock::new(|| ShardId::from_str("s11111111-1111-1111-1111-111111111111").unwrap());
1276
1277 const VERSIONED_DATA_0: VersionedData = VersionedData {
1278 seqno: SeqNo(0),
1279 data: Bytes::from_static(&[0, 1, 2, 3]),
1280 };
1281
1282 const VERSIONED_DATA_1: VersionedData = VersionedData {
1283 seqno: SeqNo(1),
1284 data: Bytes::from_static(&[4, 5, 6, 7]),
1285 };
1286
1287 #[mz_ore::test]
1288 #[should_panic(expected = "unknown connection id: 100")]
1289 fn test_zero_connections_push_diff() {
1290 let state = Arc::new(PubSubState::new_for_test());
1291 state.push_diff(100, &SHARD_ID_0, &VERSIONED_DATA_0);
1292 }
1293
1294 #[mz_ore::test]
1295 #[should_panic(expected = "unknown connection id: 100")]
1296 fn test_zero_connections_subscribe() {
1297 let state = Arc::new(PubSubState::new_for_test());
1298 let (tx, _) = tokio::sync::mpsc::channel(100);
1299 state.subscribe(100, tx, &SHARD_ID_0);
1300 }
1301
1302 #[mz_ore::test]
1303 #[should_panic(expected = "unknown connection id: 100")]
1304 fn test_zero_connections_unsubscribe() {
1305 let state = Arc::new(PubSubState::new_for_test());
1306 state.unsubscribe(100, &SHARD_ID_0);
1307 }
1308
1309 #[mz_ore::test]
1310 #[should_panic(expected = "unknown connection id: 100")]
1311 fn test_zero_connections_remove() {
1312 let state = Arc::new(PubSubState::new_for_test());
1313 state.remove_connection(100)
1314 }
1315
1316 #[mz_ore::test]
1317 fn test_single_connection() {
1318 let state = Arc::new(PubSubState::new_for_test());
1319
1320 let (tx, mut rx) = tokio::sync::mpsc::channel(100);
1321 let connection = Arc::clone(&state).new_connection(tx);
1322
1323 assert_eq!(
1324 state.active_connections(),
1325 HashSet::from([connection.connection_id])
1326 );
1327
1328 assert!(matches!(rx.try_recv(), Err(TryRecvError::Empty)));
1330
1331 connection.push_diff(
1332 &SHARD_ID_0,
1333 &VersionedData {
1334 seqno: SeqNo::minimum(),
1335 data: Bytes::new(),
1336 },
1337 );
1338
1339 assert!(matches!(rx.try_recv(), Err(TryRecvError::Empty)));
1341
1342 connection.subscribe(&SHARD_ID_0);
1344 assert_eq!(
1345 state.subscriptions(connection.connection_id),
1346 HashSet::from([SHARD_ID_0.clone()])
1347 );
1348
1349 connection.unsubscribe(&SHARD_ID_0);
1351 assert!(state.subscriptions(connection.connection_id).is_empty());
1352
1353 connection.subscribe(&SHARD_ID_0);
1355 connection.subscribe(&SHARD_ID_1);
1356 assert_eq!(
1357 state.subscriptions(connection.connection_id),
1358 HashSet::from([*SHARD_ID_0, *SHARD_ID_1])
1359 );
1360
1361 connection.subscribe(&SHARD_ID_0);
1363 connection.subscribe(&SHARD_ID_0);
1364 assert_eq!(
1365 state.subscriptions(connection.connection_id),
1366 HashSet::from([*SHARD_ID_0, *SHARD_ID_1])
1367 );
1368
1369 let connection_id = connection.connection_id;
1371 drop(connection);
1372 assert!(state.subscriptions(connection_id).is_empty());
1373 assert!(state.active_connections().is_empty());
1374 }
1375
1376 #[mz_ore::test]
1377 fn test_many_connection() {
1378 let state = Arc::new(PubSubState::new_for_test());
1379
1380 let (tx1, mut rx1) = tokio::sync::mpsc::channel(100);
1381 let conn1 = Arc::clone(&state).new_connection(tx1);
1382
1383 let (tx2, mut rx2) = tokio::sync::mpsc::channel(100);
1384 let conn2 = Arc::clone(&state).new_connection(tx2);
1385
1386 let (tx3, mut rx3) = tokio::sync::mpsc::channel(100);
1387 let conn3 = Arc::clone(&state).new_connection(tx3);
1388
1389 conn1.subscribe(&SHARD_ID_0);
1390 conn2.subscribe(&SHARD_ID_0);
1391 conn2.subscribe(&SHARD_ID_1);
1392
1393 assert_eq!(
1394 state.active_connections(),
1395 HashSet::from([
1396 conn1.connection_id,
1397 conn2.connection_id,
1398 conn3.connection_id
1399 ])
1400 );
1401
1402 conn3.push_diff(&SHARD_ID_0, &VERSIONED_DATA_0);
1404 assert_push(&mut rx1, &SHARD_ID_0, &VERSIONED_DATA_0);
1405 assert_push(&mut rx2, &SHARD_ID_0, &VERSIONED_DATA_0);
1406 assert!(matches!(rx3.try_recv(), Err(TryRecvError::Empty)));
1407
1408 conn1.push_diff(&SHARD_ID_0, &VERSIONED_DATA_0);
1410 assert!(matches!(rx1.try_recv(), Err(TryRecvError::Empty)));
1411 assert_push(&mut rx2, &SHARD_ID_0, &VERSIONED_DATA_0);
1412 assert!(matches!(rx3.try_recv(), Err(TryRecvError::Empty)));
1413
1414 conn3.push_diff(&SHARD_ID_1, &VERSIONED_DATA_1);
1416 assert!(matches!(rx1.try_recv(), Err(TryRecvError::Empty)));
1417 assert_push(&mut rx2, &SHARD_ID_1, &VERSIONED_DATA_1);
1418 assert!(matches!(rx3.try_recv(), Err(TryRecvError::Empty)));
1419
1420 conn2.unsubscribe(&SHARD_ID_1);
1422 conn3.push_diff(&SHARD_ID_1, &VERSIONED_DATA_1);
1423 assert!(matches!(rx1.try_recv(), Err(TryRecvError::Empty)));
1424 assert!(matches!(rx2.try_recv(), Err(TryRecvError::Empty)));
1425 assert!(matches!(rx3.try_recv(), Err(TryRecvError::Empty)));
1426
1427 let conn1_id = conn1.connection_id;
1429 drop(conn1);
1430 conn3.push_diff(&SHARD_ID_0, &VERSIONED_DATA_0);
1431 assert!(matches!(rx1.try_recv(), Err(TryRecvError::Disconnected)));
1432 assert_push(&mut rx2, &SHARD_ID_0, &VERSIONED_DATA_0);
1433 assert!(matches!(rx3.try_recv(), Err(TryRecvError::Empty)));
1434
1435 assert!(state.subscriptions(conn1_id).is_empty());
1436 assert_eq!(
1437 state.subscriptions(conn2.connection_id),
1438 HashSet::from([*SHARD_ID_0])
1439 );
1440 assert_eq!(state.subscriptions(conn3.connection_id), HashSet::new());
1441 assert_eq!(
1442 state.active_connections(),
1443 HashSet::from([conn2.connection_id, conn3.connection_id])
1444 );
1445 }
1446
1447 fn assert_push(
1448 rx: &mut Receiver<Result<ProtoPubSubMessage, Status>>,
1449 shard: &ShardId,
1450 data: &VersionedData,
1451 ) {
1452 let message = rx
1453 .try_recv()
1454 .expect("message in channel")
1455 .expect("pubsub")
1456 .message
1457 .expect("proto contains message");
1458 match message {
1459 Message::PushDiff(x) => {
1460 assert_eq!(x.shard_id, shard.into_proto());
1461 assert_eq!(x.seqno, data.seqno.into_proto());
1462 assert_eq!(x.diff, data.data);
1463 }
1464 Message::Subscribe(_) | Message::Unsubscribe(_) => panic!("unexpected message type"),
1465 };
1466 }
1467}
1468
1469#[cfg(test)]
1470mod grpc {
1471 use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4};
1472 use std::str::FromStr;
1473 use std::sync::Arc;
1474 use std::time::{Duration, Instant};
1475
1476 use bytes::Bytes;
1477 use futures_util::FutureExt;
1478 use mz_dyncfg::ConfigUpdates;
1479 use mz_ore::assert_none;
1480 use mz_ore::collections::HashMap;
1481 use mz_ore::metrics::MetricsRegistry;
1482 use mz_persist::location::{SeqNo, VersionedData};
1483 use mz_proto::RustType;
1484 use std::sync::LazyLock;
1485 use tokio::net::TcpListener;
1486 use tokio_stream::StreamExt;
1487 use tokio_stream::wrappers::TcpListenerStream;
1488
1489 use crate::ShardId;
1490 use crate::cfg::PersistConfig;
1491 use crate::internal::service::ProtoPubSubMessage;
1492 use crate::internal::service::proto_pub_sub_message::Message;
1493 use crate::metrics::Metrics;
1494 use crate::rpc::{
1495 GrpcPubSubClient, PUBSUB_CLIENT_ENABLED, PUBSUB_RECONNECT_BACKOFF, PersistGrpcPubSubServer,
1496 PersistPubSubClient, PersistPubSubClientConfig, PubSubState,
1497 };
1498
1499 static SHARD_ID_0: LazyLock<ShardId> =
1500 LazyLock::new(|| ShardId::from_str("s00000000-0000-0000-0000-000000000000").unwrap());
1501 static SHARD_ID_1: LazyLock<ShardId> =
1502 LazyLock::new(|| ShardId::from_str("s11111111-1111-1111-1111-111111111111").unwrap());
1503 const VERSIONED_DATA_0: VersionedData = VersionedData {
1504 seqno: SeqNo(0),
1505 data: Bytes::from_static(&[0, 1, 2, 3]),
1506 };
1507 const VERSIONED_DATA_1: VersionedData = VersionedData {
1508 seqno: SeqNo(1),
1509 data: Bytes::from_static(&[4, 5, 6, 7]),
1510 };
1511
1512 const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
1513 const SUBSCRIPTIONS_TIMEOUT: Duration = Duration::from_secs(3);
1514 const SERVER_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(2);
1515
1516 #[mz_ore::test]
1521 #[cfg_attr(miri, ignore)] fn grpc_server() {
1523 let metrics = Arc::new(Metrics::new(
1524 &test_persist_config(),
1525 &MetricsRegistry::new(),
1526 ));
1527 let server_runtime = tokio::runtime::Runtime::new().expect("server runtime");
1528 let client_runtime = tokio::runtime::Runtime::new().expect("client runtime");
1529
1530 let (addr, tcp_listener_stream) = server_runtime.block_on(new_tcp_listener());
1532 let server_state = server_runtime.block_on(spawn_server(tcp_listener_stream));
1533
1534 {
1536 let _guard = client_runtime.enter();
1537 mz_ore::task::spawn(|| "client".to_string(), async move {
1538 let client = GrpcPubSubClient::connect(
1539 PersistPubSubClientConfig {
1540 url: format!("http://{}", addr),
1541 caller_id: "client".to_string(),
1542 persist_cfg: test_persist_config(),
1543 },
1544 metrics,
1545 );
1546 let _token = client.sender.subscribe(&SHARD_ID_0);
1547 tokio::time::sleep(Duration::MAX).await;
1548 });
1549 }
1550
1551 server_runtime.block_on(async {
1553 poll_until_true(CONNECT_TIMEOUT, || {
1554 server_state.active_connections().len() == 1
1555 })
1556 .await;
1557 poll_until_true(SUBSCRIPTIONS_TIMEOUT, || {
1558 server_state.shard_subscription_counts() == HashMap::from([(*SHARD_ID_0, 1)])
1559 })
1560 .await
1561 });
1562
1563 client_runtime.shutdown_timeout(SERVER_SHUTDOWN_TIMEOUT);
1565
1566 server_runtime.block_on(async {
1568 poll_until_true(CONNECT_TIMEOUT, || {
1569 server_state.active_connections().is_empty()
1570 })
1571 .await;
1572 poll_until_true(SUBSCRIPTIONS_TIMEOUT, || {
1573 server_state.shard_subscription_counts() == HashMap::new()
1574 })
1575 .await
1576 });
1577 }
1578
1579 #[mz_ore::test]
1580 #[cfg_attr(miri, ignore)] fn grpc_client_sender_reconnects() {
1582 let metrics = Arc::new(Metrics::new(
1583 &test_persist_config(),
1584 &MetricsRegistry::new(),
1585 ));
1586 let server_runtime = tokio::runtime::Runtime::new().expect("server runtime");
1587 let client_runtime = tokio::runtime::Runtime::new().expect("client runtime");
1588 let (addr, tcp_listener_stream) = server_runtime.block_on(new_tcp_listener());
1589
1590 let client = client_runtime.block_on(async {
1592 GrpcPubSubClient::connect(
1593 PersistPubSubClientConfig {
1594 url: format!("http://{}", addr),
1595 caller_id: "client".to_string(),
1596 persist_cfg: test_persist_config(),
1597 },
1598 metrics,
1599 )
1600 });
1601
1602 let _token = Arc::clone(&client.sender).subscribe(&SHARD_ID_0);
1604 let _token_2 = Arc::clone(&client.sender).subscribe(&SHARD_ID_1);
1606 drop(_token_2);
1607
1608 let server_state = server_runtime.block_on(spawn_server(tcp_listener_stream));
1610
1611 server_runtime.block_on(async {
1612 poll_until_true(CONNECT_TIMEOUT, || {
1614 server_state.active_connections().len() == 1
1615 })
1616 .await;
1617
1618 poll_until_true(SUBSCRIPTIONS_TIMEOUT, || {
1621 server_state.shard_subscription_counts() == HashMap::from([(*SHARD_ID_0, 1)])
1622 })
1623 .await;
1624 });
1625
1626 server_runtime.shutdown_timeout(SERVER_SHUTDOWN_TIMEOUT);
1628
1629 let _token_2 = Arc::clone(&client.sender).subscribe(&SHARD_ID_1);
1631
1632 let server_runtime = tokio::runtime::Runtime::new().expect("server runtime");
1634 let tcp_listener_stream = server_runtime.block_on(async {
1635 TcpListenerStream::new(
1636 TcpListener::bind(addr)
1637 .await
1638 .expect("can bind to previous addr"),
1639 )
1640 });
1641 let server_state = server_runtime.block_on(spawn_server(tcp_listener_stream));
1642
1643 server_runtime.block_on(async {
1644 poll_until_true(CONNECT_TIMEOUT, || {
1646 server_state.active_connections().len() == 1
1647 })
1648 .await;
1649
1650 poll_until_true(SUBSCRIPTIONS_TIMEOUT, || {
1653 server_state.shard_subscription_counts()
1654 == HashMap::from([(*SHARD_ID_0, 1), (*SHARD_ID_1, 1)])
1655 })
1656 .await;
1657 });
1658 }
1659
1660 #[mz_ore::test(tokio::test(flavor = "multi_thread"))]
1661 #[cfg_attr(miri, ignore)] async fn grpc_client_sender_subscription_tokens() {
1663 let metrics = Arc::new(Metrics::new(
1664 &test_persist_config(),
1665 &MetricsRegistry::new(),
1666 ));
1667
1668 let (addr, tcp_listener_stream) = new_tcp_listener().await;
1669 let server_state = spawn_server(tcp_listener_stream).await;
1670
1671 let client = GrpcPubSubClient::connect(
1672 PersistPubSubClientConfig {
1673 url: format!("http://{}", addr),
1674 caller_id: "client".to_string(),
1675 persist_cfg: test_persist_config(),
1676 },
1677 metrics,
1678 );
1679
1680 poll_until_true(CONNECT_TIMEOUT, || {
1682 server_state.active_connections().len() == 1
1683 })
1684 .await;
1685
1686 let token = Arc::clone(&client.sender).subscribe(&SHARD_ID_0);
1688 poll_until_true(SUBSCRIPTIONS_TIMEOUT, || {
1689 server_state.shard_subscription_counts() == HashMap::from([(*SHARD_ID_0, 1)])
1690 })
1691 .await;
1692
1693 drop(token);
1695 poll_until_true(SUBSCRIPTIONS_TIMEOUT, || {
1696 server_state.shard_subscription_counts() == HashMap::new()
1697 })
1698 .await;
1699
1700 let token = Arc::clone(&client.sender).subscribe(&SHARD_ID_0);
1702 poll_until_true(SUBSCRIPTIONS_TIMEOUT, || {
1703 server_state.shard_subscription_counts() == HashMap::from([(*SHARD_ID_0, 1)])
1704 })
1705 .await;
1706
1707 let token2 = Arc::clone(&client.sender).subscribe(&SHARD_ID_0);
1709 let token3 = Arc::clone(&client.sender).subscribe(&SHARD_ID_0);
1710 assert_eq!(Arc::strong_count(&token), 3);
1711 poll_until_true(SUBSCRIPTIONS_TIMEOUT, || {
1712 server_state.shard_subscription_counts() == HashMap::from([(*SHARD_ID_0, 1)])
1713 })
1714 .await;
1715
1716 drop(token);
1718 drop(token2);
1719 drop(token3);
1720 poll_until_true(SUBSCRIPTIONS_TIMEOUT, || {
1721 server_state.shard_subscription_counts() == HashMap::new()
1722 })
1723 .await;
1724
1725 let _token0 = Arc::clone(&client.sender).subscribe(&SHARD_ID_0);
1727 let _token1 = Arc::clone(&client.sender).subscribe(&SHARD_ID_1);
1728 poll_until_true(SUBSCRIPTIONS_TIMEOUT, || {
1729 server_state.shard_subscription_counts()
1730 == HashMap::from([(*SHARD_ID_0, 1), (*SHARD_ID_1, 1)])
1731 })
1732 .await;
1733 }
1734
1735 #[mz_ore::test]
1736 #[cfg_attr(miri, ignore)] fn grpc_client_receiver() {
1738 let metrics = Arc::new(Metrics::new(
1739 &PersistConfig::new_for_tests(),
1740 &MetricsRegistry::new(),
1741 ));
1742 let server_runtime = tokio::runtime::Runtime::new().expect("server runtime");
1743 let client_runtime = tokio::runtime::Runtime::new().expect("client runtime");
1744 let (addr, tcp_listener_stream) = server_runtime.block_on(new_tcp_listener());
1745
1746 let mut client_1 = client_runtime.block_on(async {
1748 GrpcPubSubClient::connect(
1749 PersistPubSubClientConfig {
1750 url: format!("http://{}", addr),
1751 caller_id: "client_1".to_string(),
1752 persist_cfg: test_persist_config(),
1753 },
1754 Arc::clone(&metrics),
1755 )
1756 });
1757 let mut client_2 = client_runtime.block_on(async {
1758 GrpcPubSubClient::connect(
1759 PersistPubSubClientConfig {
1760 url: format!("http://{}", addr),
1761 caller_id: "client_2".to_string(),
1762 persist_cfg: test_persist_config(),
1763 },
1764 metrics,
1765 )
1766 });
1767
1768 assert_none!(client_1.receiver.next().now_or_never());
1773 assert_none!(client_2.receiver.next().now_or_never());
1774
1775 let server_state = server_runtime.block_on(spawn_server(tcp_listener_stream));
1777
1778 server_runtime.block_on(poll_until_true(CONNECT_TIMEOUT, || {
1780 server_state.active_connections().len() == 2
1781 }));
1782
1783 assert_none!(client_1.receiver.next().now_or_never());
1785 assert_none!(client_2.receiver.next().now_or_never());
1786
1787 let _token_client_1 = Arc::clone(&client_1.sender).subscribe(&SHARD_ID_0);
1789 let _token_client_2 = Arc::clone(&client_2.sender).subscribe(&SHARD_ID_0);
1790 server_runtime.block_on(poll_until_true(SUBSCRIPTIONS_TIMEOUT, || {
1791 server_state.shard_subscription_counts() == HashMap::from([(*SHARD_ID_0, 2)])
1792 }));
1793
1794 client_1.sender.push_diff(&SHARD_ID_0, &VERSIONED_DATA_1);
1796 assert_none!(client_1.receiver.next().now_or_never());
1797 client_runtime.block_on(async {
1798 assert_push(
1799 client_2.receiver.next().await.expect("has diff"),
1800 &SHARD_ID_0,
1801 &VERSIONED_DATA_1,
1802 )
1803 });
1804
1805 server_runtime.shutdown_timeout(SERVER_SHUTDOWN_TIMEOUT);
1807
1808 assert_none!(client_1.receiver.next().now_or_never());
1810 assert_none!(client_2.receiver.next().now_or_never());
1811
1812 let server_runtime = tokio::runtime::Runtime::new().expect("server runtime");
1814 let tcp_listener_stream = server_runtime.block_on(async {
1815 TcpListenerStream::new(
1816 TcpListener::bind(addr)
1817 .await
1818 .expect("can bind to previous addr"),
1819 )
1820 });
1821 let server_state = server_runtime.block_on(spawn_server(tcp_listener_stream));
1822
1823 server_runtime.block_on(async {
1825 poll_until_true(CONNECT_TIMEOUT, || {
1826 server_state.active_connections().len() == 2
1827 })
1828 .await;
1829 poll_until_true(SUBSCRIPTIONS_TIMEOUT, || {
1830 server_state.shard_subscription_counts() == HashMap::from([(*SHARD_ID_0, 2)])
1831 })
1832 .await;
1833 });
1834
1835 client_2.sender.push_diff(&SHARD_ID_0, &VERSIONED_DATA_0);
1838 client_runtime.block_on(async {
1839 assert_push(
1840 client_1.receiver.next().await.expect("has diff"),
1841 &SHARD_ID_0,
1842 &VERSIONED_DATA_0,
1843 )
1844 });
1845 assert_none!(client_2.receiver.next().now_or_never());
1846 }
1847
1848 async fn new_tcp_listener() -> (SocketAddr, TcpListenerStream) {
1849 let addr = SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::LOCALHOST, 0));
1850 let tcp_listener = TcpListener::bind(addr).await.expect("tcp listener");
1851
1852 (
1853 tcp_listener.local_addr().expect("bound to local address"),
1854 TcpListenerStream::new(tcp_listener),
1855 )
1856 }
1857
1858 #[allow(clippy::unused_async)]
1859 async fn spawn_server(tcp_listener_stream: TcpListenerStream) -> Arc<PubSubState> {
1860 let server = PersistGrpcPubSubServer::new(&test_persist_config(), &MetricsRegistry::new());
1861 let server_state = Arc::clone(&server.state);
1862
1863 let _server_task = mz_ore::task::spawn(|| "server".to_string(), async move {
1864 server.serve_with_stream(tcp_listener_stream).await
1865 });
1866 server_state
1867 }
1868
1869 async fn poll_until_true<F>(timeout: Duration, f: F)
1870 where
1871 F: Fn() -> bool,
1872 {
1873 let now = Instant::now();
1874 loop {
1875 if f() {
1876 return;
1877 }
1878
1879 if now.elapsed() > timeout {
1880 panic!("timed out");
1881 }
1882
1883 tokio::time::sleep(Duration::from_millis(1)).await;
1884 }
1885 }
1886
1887 fn assert_push(message: ProtoPubSubMessage, shard: &ShardId, data: &VersionedData) {
1888 let message = message.message.expect("proto contains message");
1889 match message {
1890 Message::PushDiff(x) => {
1891 assert_eq!(x.shard_id, shard.into_proto());
1892 assert_eq!(x.seqno, data.seqno.into_proto());
1893 assert_eq!(x.diff, data.data);
1894 }
1895 Message::Subscribe(_) | Message::Unsubscribe(_) => panic!("unexpected message type"),
1896 };
1897 }
1898
1899 fn test_persist_config() -> PersistConfig {
1900 let cfg = PersistConfig::new_for_tests();
1901
1902 let mut updates = ConfigUpdates::default();
1903 updates.add(&PUBSUB_CLIENT_ENABLED, true);
1904 updates.add(&PUBSUB_RECONNECT_BACKOFF, Duration::ZERO);
1905 cfg.apply_from(&updates);
1906
1907 cfg
1908 }
1909}