Skip to main content

dynamo_runtime/transports/event_plane/
dynamic_subscriber.rs

1// SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Dynamic subscriber that watches discovery and manages connections to multiple publishers.
5//!
6//! This module enables automatic discovery and connection to new publishers as they come online,
7//! and cleanup of disconnected publishers.
8
9use anyhow::Result;
10use bytes::Bytes;
11use futures::stream::StreamExt;
12use std::collections::HashMap;
13use std::sync::Arc;
14use tokio::sync::{RwLock, mpsc};
15use tokio_util::sync::CancellationToken;
16
17use super::transport::{EventTransportRx, WireStream};
18use super::zmq_transport::ZmqSubTransport;
19use crate::config::environment_names::event_plane::DYN_ZMQ_EVENT_SUBSCRIBER_CHANNEL_CAPACITY;
20use crate::discovery::{
21    Discovery, DiscoveryEvent, DiscoveryInstance, DiscoveryInstanceId, DiscoveryQuery,
22    EventTransport,
23};
24
25/// Manages dynamic subscriptions to multiple publishers.
26pub struct DynamicSubscriber {
27    discovery: Arc<dyn Discovery>,
28    query: DiscoveryQuery,
29    topic: String,
30    cancel_token: CancellationToken,
31}
32
33impl DynamicSubscriber {
34    pub fn new(discovery: Arc<dyn Discovery>, query: DiscoveryQuery, topic: String) -> Self {
35        Self::with_cancel_token(discovery, query, topic, CancellationToken::new())
36    }
37
38    pub fn with_cancel_token(
39        discovery: Arc<dyn Discovery>,
40        query: DiscoveryQuery,
41        topic: String,
42        cancel_token: CancellationToken,
43    ) -> Self {
44        Self {
45            discovery,
46            query,
47            topic,
48            cancel_token,
49        }
50    }
51
52    /// Start watching discovery and create a merged stream of events.
53    pub async fn start_zmq(self: Arc<Self>) -> Result<WireStream> {
54        // Bounded merged channel. Many peer publishers (e.g. every other
55        // frontend under replica-sync) feed this single-consumer channel; an
56        // unbounded channel grows RSS without limit when the consumer can't keep
57        // up (observed ~80 GiB/frontend at 168 frontends). Cap it and drop on
58        // overflow — the event plane is already best-effort/lossy (ZMQ RCVHWM),
59        // so a dropped event costs routing-estimate freshness, not correctness.
60        // Configurable via DYN_ZMQ_EVENT_SUBSCRIBER_CHANNEL_CAPACITY (default
61        // 100_000, matching ZMQ_RCVHWM).
62        let channel_cap = std::env::var(DYN_ZMQ_EVENT_SUBSCRIBER_CHANNEL_CAPACITY)
63            .ok()
64            .and_then(|v| v.parse::<usize>().ok())
65            .filter(|&n| n > 0)
66            .unwrap_or(100_000);
67        let (event_tx, event_rx) = mpsc::channel::<Bytes>(channel_cap);
68
69        // Track active endpoint connections with instance ID to endpoint mapping
70        let active_endpoints: Arc<
71            RwLock<HashMap<DiscoveryInstanceId, (String, CancellationToken)>>,
72        > = Arc::new(RwLock::new(HashMap::new()));
73
74        // Clone self for the spawned task
75        let subscriber_clone = Arc::clone(&self);
76
77        // Spawn background task to watch discovery
78        let discovery = Arc::clone(&self.discovery);
79        let query = self.query.clone();
80        // Use the actual topic for ZMQ native filtering (avoids decoding irrelevant messages)
81        let zmq_topic = self.topic.clone();
82        let cancel_token = self.cancel_token.clone();
83        let endpoints = Arc::clone(&active_endpoints);
84
85        tokio::spawn(async move {
86            tracing::debug!(
87                ?query,
88                cancel_token_cancelled = cancel_token.is_cancelled(),
89                "Attempting to start discovery watch"
90            );
91
92            // Pass cancellation through so the discovery backend can stop any
93            // task that it owns in addition to the consumer loop below.
94            let mut watch_stream = match discovery
95                .list_and_watch(query.clone(), Some(cancel_token.clone()))
96                .await
97            {
98                Ok(stream) => {
99                    tracing::debug!("Successfully obtained discovery watch stream");
100                    stream
101                }
102                Err(e) => {
103                    tracing::error!(error = %e, "Failed to start discovery watch");
104                    return;
105                }
106            };
107
108            tracing::info!(?query, "Started dynamic discovery watch for ZMQ publishers");
109
110            loop {
111                let event_result = tokio::select! {
112                    biased;
113
114                    _ = cancel_token.cancelled() => {
115                        tracing::info!("Dynamic subscriber cancelled, stopping watch");
116                        break;
117                    }
118                    result = watch_stream.next() => match result {
119                        Some(result) => result,
120                        None => break,
121                    },
122                };
123
124                tracing::debug!("Received discovery event: {:?}", event_result);
125
126                match event_result {
127                    Ok(DiscoveryEvent::Added(instance)) => {
128                        tracing::info!(instance = ?instance, "Discovery Added event received");
129                        let instance_id = instance.id();
130
131                        // Extract ZMQ endpoint from the instance
132                        if let Some(endpoint) = Self::extract_zmq_endpoint(&instance, &zmq_topic) {
133                            let mut endpoints_guard = endpoints.write().await;
134
135                            // Skip if instance already tracked
136                            if endpoints_guard.contains_key(&instance_id) {
137                                tracing::debug!(endpoint = %endpoint, ?instance_id, "Already connected to ZMQ publisher");
138                                continue;
139                            }
140
141                            tracing::info!(endpoint = %endpoint, ?instance_id, "Connecting to new ZMQ publisher");
142
143                            // Create cancellation token for this endpoint's stream
144                            let endpoint_cancel = CancellationToken::new();
145                            endpoints_guard.insert(
146                                instance_id.clone(),
147                                (endpoint.clone(), endpoint_cancel.clone()),
148                            );
149                            drop(endpoints_guard);
150
151                            // Spawn task to handle this endpoint's stream
152                            let event_tx_clone = event_tx.clone();
153                            let zmq_topic_clone = zmq_topic.clone();
154                            let endpoint_clone = endpoint.clone();
155                            let endpoints_clone = Arc::clone(&endpoints);
156                            let instance_id_clone = instance_id.clone();
157
158                            tokio::spawn(async move {
159                                if let Err(e) = Self::consume_endpoint_stream(
160                                    &endpoint_clone,
161                                    &zmq_topic_clone,
162                                    event_tx_clone,
163                                    &endpoint_cancel,
164                                )
165                                .await
166                                {
167                                    tracing::warn!(
168                                        endpoint = %endpoint_clone,
169                                        error = %e,
170                                        "Error consuming ZMQ endpoint stream"
171                                    );
172                                }
173                                // A cancelled token means the watcher already handled this
174                                // entry, and the ID may now belong to a newer stream.
175                                let mut endpoints_guard = endpoints_clone.write().await;
176                                if !endpoint_cancel.is_cancelled() {
177                                    endpoints_guard.remove(&instance_id_clone);
178                                }
179                            });
180                        } else {
181                            tracing::debug!(
182                                instance = ?instance,
183                                expected_topic = %zmq_topic,
184                                "Discovery event is not a matching ZMQ publisher"
185                            );
186                        }
187                    }
188                    Ok(DiscoveryEvent::ModelTaintsUpdated(_)) => {}
189                    Ok(DiscoveryEvent::Resync(_)) => {}
190                    Ok(DiscoveryEvent::Removed(instance_id)) => {
191                        let is_expected_topic = matches!(
192                            &instance_id,
193                            DiscoveryInstanceId::EventChannel(channel_id)
194                                if channel_id.topic == zmq_topic
195                        );
196                        if !is_expected_topic {
197                            tracing::debug!(
198                                ?instance_id,
199                                expected_topic = %zmq_topic,
200                                "Ignoring removal for unrelated event channel"
201                            );
202                            continue;
203                        }
204
205                        tracing::info!(
206                            ?instance_id,
207                            "ZMQ publisher removed from discovery, cancelling endpoint stream"
208                        );
209
210                        // Cancel the endpoint's stream via its CancellationToken
211                        if let Some((_endpoint, cancel)) =
212                            endpoints.write().await.remove(&instance_id)
213                        {
214                            cancel.cancel();
215                            tracing::info!(?instance_id, "Cancelled endpoint stream");
216                        } else {
217                            tracing::debug!(
218                                ?instance_id,
219                                "No active endpoint found for removed stream instance"
220                            );
221                        }
222                    }
223                    Err(e) => {
224                        tracing::error!(error = %e, "Discovery watch error");
225                        break;
226                    }
227                }
228            }
229
230            // Cancel all active endpoints on shutdown
231            let endpoints_guard = endpoints.write().await;
232            for (_id, (_endpoint, cancel)) in endpoints_guard.iter() {
233                cancel.cancel();
234            }
235            tracing::info!("Discovery watch stream ended");
236        });
237
238        // Return a stream that reads from the merged channel
239        let stream = async_stream::stream! {
240            // Keep subscriber_clone alive by capturing it in the stream
241            let _subscriber = subscriber_clone;
242            let mut rx = event_rx;
243            while let Some(bytes) = rx.recv().await {
244                yield Ok(bytes);
245            }
246        };
247
248        Ok(Box::pin(stream))
249    }
250
251    /// Extract ZMQ endpoint from a discovery instance.
252    fn extract_zmq_endpoint(instance: &DiscoveryInstance, expected_topic: &str) -> Option<String> {
253        if let DiscoveryInstance::EventChannel {
254            topic, transport, ..
255        } = instance
256            && topic == expected_topic
257            && let EventTransport::Zmq { endpoint } = transport
258        {
259            return Some(endpoint.clone());
260        }
261        None
262    }
263
264    /// Consume events from a single endpoint and forward to the merged channel.
265    async fn consume_endpoint_stream(
266        endpoint: &str,
267        zmq_topic: &str,
268        event_tx: mpsc::Sender<Bytes>,
269        cancel_token: &CancellationToken,
270    ) -> Result<()> {
271        // Connect to the endpoint
272        let sub_transport = ZmqSubTransport::connect(endpoint, zmq_topic).await?;
273        let mut stream = sub_transport.subscribe(zmq_topic).await?;
274
275        tracing::info!(endpoint = %endpoint, topic = %zmq_topic, "Started consuming ZMQ endpoint stream");
276
277        loop {
278            tokio::select! {
279                _ = cancel_token.cancelled() => {
280                    tracing::info!(endpoint = %endpoint, "Endpoint stream cancelled");
281                    break;
282                }
283
284                event = stream.next() => {
285                    match event {
286                        Some(Ok(bytes)) => {
287                            match event_tx.try_send(bytes) {
288                                Ok(()) => {}
289                                Err(mpsc::error::TrySendError::Full(_)) => {
290                                    // Consumer is behind; drop to bound memory.
291                                    // Best-effort plane — a stale estimate
292                                    // self-corrects on subsequent events.
293                                    tracing::trace!(endpoint = %endpoint, "Event subscriber channel full; dropping event");
294                                }
295                                Err(mpsc::error::TrySendError::Closed(_)) => {
296                                    tracing::warn!(endpoint = %endpoint, "Event channel closed, stopping endpoint stream");
297                                    break;
298                                }
299                            }
300                        }
301                        Some(Err(e)) => {
302                            tracing::error!(
303                                endpoint = %endpoint,
304                                error = %e,
305                                "Error receiving from ZMQ endpoint"
306                            );
307                            break;
308                        }
309                        None => {
310                            tracing::info!(endpoint = %endpoint, "ZMQ endpoint stream ended");
311                            break;
312                        }
313                    }
314                }
315            }
316        }
317
318        Ok(())
319    }
320
321    /// Stop watching and disconnect from all endpoints.
322    pub fn cancel(&self) {
323        self.cancel_token.cancel();
324    }
325}
326
327impl Drop for DynamicSubscriber {
328    fn drop(&mut self) {
329        self.cancel_token.cancel();
330    }
331}
332
333#[cfg(test)]
334mod tests {
335    use super::*;
336    use crate::discovery::{
337        DiscoverySpec, DiscoveryStream, EventChannelQuery, EventScope, MockDiscovery,
338        SharedMockRegistry,
339    };
340    use crate::transports::event_plane::{Codec, EventTransportTx, ZmqPubTransport};
341    use tokio::sync::Notify;
342    use tokio::time::{Duration, timeout};
343
344    struct CancellationAwareDiscovery {
345        backend_stopped: Arc<Notify>,
346    }
347
348    #[async_trait::async_trait]
349    impl Discovery for CancellationAwareDiscovery {
350        fn instance_id(&self) -> u64 {
351            1
352        }
353
354        async fn register_internal(&self, _spec: DiscoverySpec) -> Result<DiscoveryInstance> {
355            anyhow::bail!("register is not supported by this test discovery")
356        }
357
358        async fn unregister(&self, _instance: DiscoveryInstance) -> Result<()> {
359            anyhow::bail!("unregister is not supported by this test discovery")
360        }
361
362        async fn list(&self, _query: DiscoveryQuery) -> Result<Vec<DiscoveryInstance>> {
363            Ok(Vec::new())
364        }
365
366        async fn list_and_watch(
367            &self,
368            _query: DiscoveryQuery,
369            cancel_token: Option<CancellationToken>,
370        ) -> Result<DiscoveryStream> {
371            let cancel_token = cancel_token
372                .ok_or_else(|| anyhow::anyhow!("dynamic subscriber must pass cancellation"))?;
373            let backend_stopped = Arc::clone(&self.backend_stopped);
374            tokio::spawn(async move {
375                cancel_token.cancelled().await;
376                backend_stopped.notify_one();
377            });
378
379            Ok(Box::pin(futures::stream::pending()))
380        }
381    }
382
383    fn event_channel(topic: &str, transport: EventTransport) -> DiscoveryInstance {
384        DiscoveryInstance::EventChannel {
385            scope: EventScope::Component {
386                namespace: "test-ns".to_string(),
387                component: "test-component".to_string(),
388            },
389            topic: topic.to_string(),
390            instance_id: 1,
391            transport,
392        }
393    }
394
395    #[test]
396    fn extracts_only_matching_zmq_topic() {
397        let matching = event_channel("kv-events", EventTransport::zmq("tcp://127.0.0.1:1"));
398        let wrong_topic = event_channel("kv-metrics", EventTransport::zmq("tcp://127.0.0.1:2"));
399        let wrong_transport = event_channel(
400            "kv-events",
401            EventTransport::nats("namespace.test-ns.component.test-component"),
402        );
403
404        assert_eq!(
405            DynamicSubscriber::extract_zmq_endpoint(&matching, "kv-events").as_deref(),
406            Some("tcp://127.0.0.1:1")
407        );
408        assert_eq!(
409            DynamicSubscriber::extract_zmq_endpoint(&wrong_topic, "kv-events"),
410            None
411        );
412        assert_eq!(
413            DynamicSubscriber::extract_zmq_endpoint(&wrong_transport, "kv-events"),
414            None
415        );
416    }
417
418    #[tokio::test]
419    async fn cancellation_stops_idle_discovery_watch() {
420        let backend_stopped = Arc::new(Notify::new());
421        let discovery = Arc::new(CancellationAwareDiscovery {
422            backend_stopped: Arc::clone(&backend_stopped),
423        });
424        let query = DiscoveryQuery::EventChannels(EventChannelQuery::topic(
425            "test-ns",
426            "test-component",
427            "kv-events",
428        ));
429        let subscriber = Arc::new(DynamicSubscriber::new(
430            discovery,
431            query,
432            "kv-events".to_string(),
433        ));
434        let mut stream = Arc::clone(&subscriber).start_zmq().await.unwrap();
435
436        tokio::task::yield_now().await;
437        subscriber.cancel();
438
439        let next = timeout(Duration::from_secs(1), stream.next())
440            .await
441            .expect("subscriber stream should close promptly after cancellation");
442        assert!(next.is_none());
443
444        timeout(Duration::from_secs(1), backend_stopped.notified())
445            .await
446            .expect("discovery backend should receive cancellation");
447    }
448
449    #[tokio::test]
450    async fn dropping_returned_stream_cancels_idle_discovery_watch() {
451        let backend_stopped = Arc::new(Notify::new());
452        let discovery = Arc::new(CancellationAwareDiscovery {
453            backend_stopped: Arc::clone(&backend_stopped),
454        });
455        let query = DiscoveryQuery::EventChannels(EventChannelQuery::topic(
456            "test-ns",
457            "test-component",
458            "kv-events",
459        ));
460        let parent_token = CancellationToken::new();
461        let subscriber = Arc::new(DynamicSubscriber::with_cancel_token(
462            discovery,
463            query,
464            "kv-events".to_string(),
465            parent_token.child_token(),
466        ));
467        let weak_subscriber = Arc::downgrade(&subscriber);
468        let stream = subscriber.start_zmq().await.unwrap();
469
470        assert!(
471            weak_subscriber.upgrade().is_some(),
472            "returned stream should retain the dynamic subscriber"
473        );
474        drop(stream);
475        assert!(
476            weak_subscriber.upgrade().is_none(),
477            "dropping the returned stream should release the dynamic subscriber"
478        );
479        assert!(
480            !parent_token.is_cancelled(),
481            "dropping a subscriber must not cancel its parent token"
482        );
483
484        timeout(Duration::from_secs(1), backend_stopped.notified())
485            .await
486            .expect("dropping the stream should cancel the discovery backend");
487    }
488
489    #[tokio::test]
490    async fn reregistered_publisher_stops_on_next_removal() {
491        let topic = "kv-events";
492        let (publisher, endpoint) = ZmqPubTransport::bind("tcp://127.0.0.1:0", topic)
493            .await
494            .unwrap();
495        let discovery: Arc<dyn Discovery> =
496            Arc::new(MockDiscovery::new(None, SharedMockRegistry::new()));
497        let query = DiscoveryQuery::EventChannels(EventChannelQuery::topic(
498            "test-ns",
499            "test-component",
500            topic,
501        ));
502        let mut stream = Arc::new(DynamicSubscriber::new(
503            Arc::clone(&discovery),
504            query,
505            topic.to_string(),
506        ))
507        .start_zmq()
508        .await
509        .unwrap();
510        tokio::task::yield_now().await;
511
512        let spec = DiscoverySpec::EventChannel {
513            scope: EventScope::Component {
514                namespace: "test-ns".to_string(),
515                component: "test-component".to_string(),
516            },
517            topic: topic.to_string(),
518            publisher_id: 7,
519            transport: EventTransport::zmq(endpoint),
520        };
521        // The watcher handles all three changes before the first endpoint task runs.
522        let instance = discovery.register(spec.clone()).await.unwrap();
523        discovery.unregister(instance).await.unwrap();
524        let instance = discovery.register(spec).await.unwrap();
525
526        let codec = Codec::default();
527        let ready = codec
528            .encode_envelope_parts(7, 1, 1, topic, b"ready")
529            .unwrap();
530        timeout(Duration::from_secs(2), async {
531            loop {
532                publisher.publish(topic, ready.clone()).await.unwrap();
533                if let Ok(Some(_)) = timeout(Duration::from_millis(25), stream.next()).await {
534                    break;
535                }
536            }
537        })
538        .await
539        .expect("re-registered publisher should deliver events");
540
541        discovery.unregister(instance).await.unwrap();
542        tokio::time::sleep(Duration::from_millis(50)).await;
543
544        let removed = codec
545            .encode_envelope_parts(7, 2, 2, topic, b"removed")
546            .unwrap();
547        publisher.publish(topic, removed.clone()).await.unwrap();
548        let delivered = timeout(Duration::from_millis(250), async {
549            while stream.next().await.unwrap().unwrap() != removed {}
550        })
551        .await;
552        assert!(
553            delivered.is_err(),
554            "removed publisher still delivered events"
555        );
556    }
557}