Skip to main content

subspace_farmer/cluster/
nats_client.rs

1//! NATS client
2//!
3//! [`NatsClient`] provided here is a wrapper around [`Client`] that provides convenient methods
4//! using domain-specific traits.
5//!
6//! Before reading code, make sure to familiarize yourself with NATS documentation, especially with
7//! [subjects](https://docs.nats.io/nats-concepts/subjects) and
8//! [Core NATS](https://docs.nats.io/nats-concepts/core-nats) features.
9//!
10//! Abstractions provided here cover a few use cases:
11//! * request/response (for example piece request)
12//! * request/stream of responses (for example a stream of plotted sectors of the farmer)
13//! * notifications (typically targeting a particular instance of an app) and corresponding subscriptions (for example solution notification)
14//! * broadcasts and corresponding subscriptions (for example slot info broadcast)
15
16use anyhow::anyhow;
17use async_nats::{
18    Client, ConnectOptions, HeaderMap, HeaderValue, Message, PublishError, RequestError,
19    RequestErrorKind, Subject, SubscribeError, Subscriber, ToServerAddrs,
20};
21use backon::{BackoffBuilder, ExponentialBuilder};
22use futures::channel::mpsc;
23use futures::stream::FuturesUnordered;
24use futures::{FutureExt, Stream, StreamExt, select};
25use parity_scale_codec::{Decode, Encode, decode_from_bytes};
26use std::any::type_name;
27use std::collections::VecDeque;
28use std::future::Future;
29use std::marker::PhantomData;
30use std::ops::Deref;
31use std::pin::Pin;
32use std::sync::Arc;
33use std::task::{Context, Poll};
34use std::time::Duration;
35use std::{fmt, mem};
36use subspace_process::AsyncJoinOnDrop;
37use thiserror::Error;
38use tracing::{Instrument, debug, error, trace, warn};
39use ulid::Ulid;
40
41const EXPECTED_MESSAGE_SIZE: usize = 2 * 1024 * 1024;
42const ACKNOWLEDGEMENT_TIMEOUT: Duration = Duration::from_mins(1);
43/// Requests should time out eventually, but we should set a larger timeout to allow for spikes in
44/// load to be absorbed gracefully
45const REQUEST_TIMEOUT: Duration = Duration::from_mins(5);
46
47/// Generic request with associated response.
48///
49/// Used for cases where request/response pattern is needed and response contains a single small
50/// message. For large messages or multiple messages chunking with [`GenericStreamRequest`] can be
51/// used instead.
52pub trait GenericRequest: Encode + Decode + fmt::Debug + Send + Sync + 'static {
53    /// Request subject with optional `*` in place of application instance to receive the request
54    const SUBJECT: &'static str;
55    /// Response type that corresponds to this request
56    type Response: Encode + Decode + fmt::Debug + Send + Sync + 'static;
57}
58
59/// Generic stream request where response is streamed using
60/// [`NatsClient::stream_request_responder`].
61///
62/// Used for cases where a large payload that doesn't fit into NATS message needs to be sent or
63/// there is a very large number of messages to send. For simple request/response patten
64/// [`GenericRequest`] can be used instead.
65pub trait GenericStreamRequest: Encode + Decode + fmt::Debug + Send + Sync + 'static {
66    /// Request subject with optional `*` in place of application instance to receive the request
67    const SUBJECT: &'static str;
68    /// Response type that corresponds to this stream request.
69    ///
70    /// These responses are send as a stream of messages, each message must fit into NATS message,
71    /// [`NatsClient::approximate_max_message_size()`] can be used to estimate appropriate message
72    /// size in case chunking is needed.
73    type Response: Encode + Decode + fmt::Debug + Send + Sync + 'static;
74}
75
76/// Messages sent in response to [`GenericStreamRequest`].
77///
78/// Empty list of responses means the end of the stream.
79#[derive(Debug, Encode, Decode)]
80enum GenericStreamResponses<Response> {
81    /// Some responses, but the stream didn't end yet
82    Continue {
83        /// Monotonically increasing index of responses in a stream
84        index: u32,
85        /// Individual responses
86        responses: VecDeque<Response>,
87        /// Subject where to send acknowledgement of received stream response indices, which acts as
88        /// a backpressure mechanism
89        ack_subject: String,
90    },
91    /// Remaining responses and this is the end of the stream.
92    Last {
93        /// Monotonically increasing index of responses in a stream
94        index: u32,
95        /// Individual responses
96        responses: VecDeque<Response>,
97    },
98}
99
100impl<Response> From<GenericStreamResponses<Response>> for VecDeque<Response> {
101    #[inline]
102    fn from(value: GenericStreamResponses<Response>) -> Self {
103        match value {
104            GenericStreamResponses::Continue { responses, .. } => responses,
105            GenericStreamResponses::Last { responses, .. } => responses,
106        }
107    }
108}
109
110impl<Response> GenericStreamResponses<Response> {
111    fn next(&mut self) -> Option<Response> {
112        match self {
113            GenericStreamResponses::Continue { responses, .. } => responses.pop_front(),
114            GenericStreamResponses::Last { responses, .. } => responses.pop_front(),
115        }
116    }
117
118    fn index(&self) -> u32 {
119        match self {
120            GenericStreamResponses::Continue { index, .. } => *index,
121            GenericStreamResponses::Last { index, .. } => *index,
122        }
123    }
124
125    fn ack_subject(&self) -> Option<&str> {
126        if let GenericStreamResponses::Continue { ack_subject, .. } = self {
127            Some(ack_subject)
128        } else {
129            None
130        }
131    }
132
133    fn is_last(&self) -> bool {
134        matches!(self, Self::Last { .. })
135    }
136}
137
138/// Stream request error
139#[derive(Debug, Error)]
140pub enum StreamRequestError {
141    /// Subscribe error
142    #[error("Subscribe error: {0}")]
143    Subscribe(#[from] SubscribeError),
144    /// Publish error
145    #[error("Publish error: {0}")]
146    Publish(#[from] PublishError),
147}
148
149/// Wrapper around subscription that transforms stream of wrapped response messages into a normal
150/// `Response` stream.
151#[derive(Debug)]
152#[pin_project::pin_project]
153pub struct StreamResponseSubscriber<Response> {
154    #[pin]
155    subscriber: Subscriber,
156    response_subject: String,
157    buffered_responses: Option<GenericStreamResponses<Response>>,
158    next_index: u32,
159    acknowledgement_sender: mpsc::UnboundedSender<(String, u32)>,
160    _background_task: AsyncJoinOnDrop<()>,
161    _phantom: PhantomData<Response>,
162}
163
164impl<Response> Stream for StreamResponseSubscriber<Response>
165where
166    Response: Decode,
167{
168    type Item = Response;
169
170    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
171        if let Some(buffered_responses) = self.buffered_responses.as_mut() {
172            if let Some(response) = buffered_responses.next() {
173                return Poll::Ready(Some(response));
174            } else if buffered_responses.is_last() {
175                return Poll::Ready(None);
176            }
177
178            self.buffered_responses.take();
179            self.next_index += 1;
180        }
181
182        let mut projected = self.project();
183        match projected.subscriber.poll_next_unpin(cx) {
184            Poll::Ready(Some(message)) => {
185                match decode_from_bytes::<GenericStreamResponses<Response>>(message.payload.clone())
186                {
187                    Ok(mut responses) => {
188                        if responses.index() != *projected.next_index {
189                            warn!(
190                                actual_index = %responses.index(),
191                                expected_index = %*projected.next_index,
192                                message_type = %type_name::<Response>(),
193                                response_subject = %projected.response_subject,
194                                "Received unexpected response stream index, aborting stream"
195                            );
196
197                            return Poll::Ready(None);
198                        }
199
200                        if let Some(ack_subject) = responses.ack_subject() {
201                            let index = responses.index();
202                            let ack_subject = ack_subject.to_string();
203
204                            if let Err(error) = projected
205                                .acknowledgement_sender
206                                .unbounded_send((ack_subject.clone(), index))
207                            {
208                                warn!(
209                                    %error,
210                                    %index,
211                                    message_type = %type_name::<Response>(),
212                                    response_subject = %projected.response_subject,
213                                    %ack_subject,
214                                    "Failed to send acknowledgement for stream response"
215                                );
216                            }
217                        }
218
219                        if let Some(response) = responses.next() {
220                            *projected.buffered_responses = Some(responses);
221                            Poll::Ready(Some(response))
222                        } else {
223                            Poll::Ready(None)
224                        }
225                    }
226                    Err(error) => {
227                        warn!(
228                            %error,
229                            response_type = %type_name::<Response>(),
230                            response_subject = %projected.response_subject,
231                            message = %hex::encode(message.payload),
232                            "Failed to decode stream response"
233                        );
234
235                        Poll::Ready(None)
236                    }
237                }
238            }
239            Poll::Ready(None) => Poll::Ready(None),
240            Poll::Pending => Poll::Pending,
241        }
242    }
243}
244
245impl<Response> StreamResponseSubscriber<Response> {
246    fn new(subscriber: Subscriber, response_subject: String, nats_client: NatsClient) -> Self {
247        let (acknowledgement_sender, mut acknowledgement_receiver) =
248            mpsc::unbounded::<(String, u32)>();
249
250        let ack_publisher_fut = {
251            let response_subject = response_subject.clone();
252
253            async move {
254                while let Some((subject, index)) = acknowledgement_receiver.next().await {
255                    trace!(
256                        %subject,
257                        %index,
258                        %response_subject,
259                        %index,
260                        "Sending stream response acknowledgement"
261                    );
262                    if let Err(error) = nats_client
263                        .publish(subject.clone(), index.to_le_bytes().to_vec().into())
264                        .await
265                    {
266                        warn!(
267                            %error,
268                            %subject,
269                            %index,
270                            %response_subject,
271                            %index,
272                            "Failed to send stream response acknowledgement"
273                        );
274                        return;
275                    }
276                }
277            }
278        };
279        let background_task =
280            AsyncJoinOnDrop::new(tokio::spawn(ack_publisher_fut.in_current_span()), true);
281
282        Self {
283            response_subject,
284            subscriber,
285            buffered_responses: None,
286            next_index: 0,
287            acknowledgement_sender,
288            _background_task: background_task,
289            _phantom: PhantomData,
290        }
291    }
292}
293
294/// Generic one-off notification
295pub trait GenericNotification: Encode + Decode + fmt::Debug + Send + Sync + 'static {
296    /// Notification subject with optional `*` in place of application instance receiving the
297    /// request
298    const SUBJECT: &'static str;
299}
300
301/// Generic broadcast message.
302///
303/// Broadcast messages are sent by an instance to (potentially) an instance-specific subject that
304/// any other app can subscribe to. The same broadcast message can also originate from multiple
305/// places and be de-duplicated using [`Self::deterministic_message_id`].
306pub trait GenericBroadcast: Encode + Decode + fmt::Debug + Send + Sync + 'static {
307    /// Broadcast subject with optional `*` in place of application instance sending broadcast
308    const SUBJECT: &'static str;
309
310    /// Deterministic message ID that is used for de-duplicating messages broadcast by different
311    /// instances
312    fn deterministic_message_id(&self) -> Option<HeaderValue> {
313        None
314    }
315}
316
317/// Subscriber wrapper that decodes messages automatically and skips messages that can't be decoded
318#[derive(Debug)]
319#[pin_project::pin_project]
320pub struct SubscriberWrapper<Message> {
321    #[pin]
322    subscriber: Subscriber,
323    _phantom: PhantomData<Message>,
324}
325
326impl<Message> Stream for SubscriberWrapper<Message>
327where
328    Message: Decode,
329{
330    type Item = Message;
331
332    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
333        match self.project().subscriber.poll_next_unpin(cx) {
334            Poll::Ready(Some(message)) => {
335                match decode_from_bytes::<Message>(message.payload.clone()) {
336                    Ok(message) => Poll::Ready(Some(message)),
337                    Err(error) => {
338                        warn!(
339                            %error,
340                            message_type = %type_name::<Message>(),
341                            message = %hex::encode(message.payload),
342                            "Failed to decode stream message"
343                        );
344
345                        Poll::Pending
346                    }
347                }
348            }
349            Poll::Ready(None) => Poll::Ready(None),
350            Poll::Pending => Poll::Pending,
351        }
352    }
353}
354
355#[derive(Debug)]
356struct Inner {
357    client: Client,
358    request_retry_backoff_policy: ExponentialBuilder,
359    approximate_max_message_size: usize,
360    max_message_size: usize,
361}
362
363/// NATS client wrapper that can be used to interact with other Subspace-specific clients
364#[derive(Debug, Clone)]
365pub struct NatsClient {
366    inner: Arc<Inner>,
367}
368
369impl Deref for NatsClient {
370    type Target = Client;
371
372    #[inline]
373    fn deref(&self) -> &Self::Target {
374        &self.inner.client
375    }
376}
377
378impl NatsClient {
379    /// Create new instance by connecting to specified addresses
380    pub async fn new<A: ToServerAddrs>(
381        addrs: A,
382        request_retry_backoff_policy: ExponentialBuilder,
383    ) -> Result<Self, async_nats::Error> {
384        let servers = addrs.to_server_addrs()?.collect::<Vec<_>>();
385        Self::from_client(
386            async_nats::connect_with_options(
387                &servers,
388                ConnectOptions::default().request_timeout(Some(REQUEST_TIMEOUT)),
389            )
390            .await?,
391            request_retry_backoff_policy,
392        )
393    }
394
395    /// Create new client from existing NATS instance
396    pub fn from_client(
397        client: Client,
398        request_retry_backoff_policy: ExponentialBuilder,
399    ) -> Result<Self, async_nats::Error> {
400        let max_payload = client.server_info().max_payload;
401        if max_payload < EXPECTED_MESSAGE_SIZE {
402            return Err(format!(
403                "Max payload {max_payload} is smaller than expected {EXPECTED_MESSAGE_SIZE}, \
404                increase it by specifying max_payload = 2MB or higher number in NATS configuration"
405            )
406            .into());
407        }
408
409        let inner = Inner {
410            client,
411            request_retry_backoff_policy,
412            // Allow up to 90%, the rest will be wrapper data structures, etc.
413            approximate_max_message_size: max_payload * 9 / 10,
414            // Allow up to 90%, the rest will be wrapper data structures, etc.
415            max_message_size: max_payload,
416        };
417
418        Ok(Self {
419            inner: Arc::new(inner),
420        })
421    }
422
423    /// Approximate max message size (a few more bytes will not hurt), the actual limit is expected
424    /// to be a bit higher
425    pub fn approximate_max_message_size(&self) -> usize {
426        self.inner.approximate_max_message_size
427    }
428
429    /// Make request and wait for response
430    pub async fn request<Request>(
431        &self,
432        request: &Request,
433        instance: Option<&str>,
434    ) -> Result<Request::Response, RequestError>
435    where
436        Request: GenericRequest,
437    {
438        let subject = subject_with_instance(Request::SUBJECT, instance);
439        let mut maybe_retry_backoff = None;
440        let message = loop {
441            match self
442                .inner
443                .client
444                .request(subject.clone(), request.encode().into())
445                .await
446            {
447                Ok(message) => {
448                    break message;
449                }
450                Err(error) => {
451                    match error.kind() {
452                        RequestErrorKind::TimedOut | RequestErrorKind::NoResponders => {
453                            // Continue with retries
454                        }
455                        RequestErrorKind::Other
456                        | RequestErrorKind::InvalidSubject
457                        | RequestErrorKind::MaxPayloadExceeded => {
458                            return Err(error);
459                        }
460                    }
461
462                    let retry_backoff = maybe_retry_backoff
463                        .get_or_insert_with(|| self.inner.request_retry_backoff_policy.build());
464
465                    if let Some(delay) = retry_backoff.next() {
466                        debug!(
467                            %subject,
468                            %error,
469                            request_type = %type_name::<Request>(),
470                            ?delay,
471                            "Failed to make request, retrying after some delay"
472                        );
473
474                        tokio::time::sleep(delay).await;
475                        continue;
476                    } else {
477                        return Err(error);
478                    }
479                }
480            }
481        };
482
483        let response =
484            decode_from_bytes::<Request::Response>(message.payload.clone()).map_err(|error| {
485                warn!(
486                    %subject,
487                    %error,
488                    response_type = %type_name::<Request::Response>(),
489                    response = %hex::encode(message.payload),
490                    "Response decoding failed"
491                );
492
493                RequestErrorKind::Other
494            })?;
495
496        Ok(response)
497    }
498
499    /// Responds to requests from the given subject using the provided processing function.
500    ///
501    /// This will create a subscription on the subject for the given instance (if provided) and
502    /// queue group. Incoming messages will be deserialized as the request type `Request` and passed
503    /// to the `process` function to produce a response of type `Request::Response`. The response
504    /// will then be sent back on the reply subject from the original request.
505    ///
506    /// Each request is processed in a newly created async tokio task.
507    ///
508    /// # Arguments
509    ///
510    /// * `instance` - Optional instance name to use in place of the `*` in the subject
511    /// * `group` - The queue group name for the subscription
512    /// * `process` - The function to call with the decoded request to produce a response
513    pub async fn request_responder<Request, F, OP>(
514        &self,
515        instance: Option<&str>,
516        queue_group: Option<String>,
517        process: OP,
518    ) -> anyhow::Result<()>
519    where
520        Request: GenericRequest,
521        F: Future<Output = Option<Request::Response>> + Send,
522        OP: Fn(Request) -> F + Send + Sync,
523    {
524        // Initialize with pending future so it never ends
525        let mut processing = FuturesUnordered::new();
526
527        let subscription = self
528            .common_subscribe(Request::SUBJECT, instance, queue_group)
529            .await
530            .map_err(|error| {
531                anyhow!(
532                    "Failed to subscribe to {} requests for {instance:?}: {error}",
533                    type_name::<Request>(),
534                )
535            })?;
536
537        debug!(
538            request_type = %type_name::<Request>(),
539            ?subscription,
540            "Requests subscription"
541        );
542        let mut subscription = subscription.fuse();
543
544        loop {
545            select! {
546                message = subscription.select_next_some() => {
547                    // Create background task for concurrent processing
548                    processing.push(
549                        self
550                            .process_request(
551                                message,
552                                &process,
553                            )
554                            .in_current_span(),
555                    );
556                },
557                _ = processing.next() => {
558                    // Nothing to do here
559                },
560                complete => {
561                    break;
562                }
563            }
564        }
565
566        Ok(())
567    }
568
569    async fn process_request<Request, F, OP>(&self, message: Message, process: OP)
570    where
571        Request: GenericRequest,
572        F: Future<Output = Option<Request::Response>> + Send,
573        OP: Fn(Request) -> F + Send + Sync,
574    {
575        let Some(reply_subject) = message.reply else {
576            return;
577        };
578
579        let message_payload_size = message.payload.len();
580        let request = match decode_from_bytes::<Request>(message.payload.clone()) {
581            Ok(request) => {
582                // Free allocation early
583                drop(message.payload);
584                request
585            }
586            Err(error) => {
587                warn!(
588                    request_type = %type_name::<Request>(),
589                    %error,
590                    message = %hex::encode(message.payload),
591                    "Failed to decode request"
592                );
593                return;
594            }
595        };
596
597        // Avoid printing large messages in logs
598        if message_payload_size > 1024 {
599            trace!(
600                request_type = %type_name::<Request>(),
601                %reply_subject,
602                "Processing request"
603            );
604        } else {
605            trace!(
606                request_type = %type_name::<Request>(),
607                ?request,
608                %reply_subject,
609                "Processing request"
610            );
611        }
612
613        if let Some(response) = process(request).await
614            && let Err(error) = self.publish(reply_subject, response.encode().into()).await
615        {
616            warn!(
617                request_type = %type_name::<Request>(),
618                %error,
619                "Failed to send response"
620            );
621        }
622    }
623
624    /// Make request that expects stream response
625    pub async fn stream_request<Request>(
626        &self,
627        request: &Request,
628        instance: Option<&str>,
629    ) -> Result<StreamResponseSubscriber<Request::Response>, StreamRequestError>
630    where
631        Request: GenericStreamRequest,
632    {
633        let stream_request_subject = subject_with_instance(Request::SUBJECT, instance);
634        let stream_response_subject = format!("stream-response.{}", Ulid::generate());
635
636        let subscriber = self
637            .inner
638            .client
639            .subscribe(stream_response_subject.clone())
640            .await?;
641
642        debug!(
643            request_type = %type_name::<Request>(),
644            %stream_request_subject,
645            %stream_response_subject,
646            ?subscriber,
647            "Stream request subscription"
648        );
649
650        self.inner
651            .client
652            .publish_with_reply(
653                stream_request_subject,
654                stream_response_subject.clone(),
655                request.encode().into(),
656            )
657            .await?;
658
659        Ok(StreamResponseSubscriber::new(
660            subscriber,
661            stream_response_subject,
662            self.clone(),
663        ))
664    }
665
666    /// Responds to stream requests from the given subject using the provided processing function.
667    ///
668    /// This will create a subscription on the subject for the given instance (if provided) and
669    /// queue group. Incoming messages will be deserialized as the request type `Request` and passed
670    /// to the `process` function to produce a stream response of type `Request::Response`. The
671    /// stream response will then be sent back on the reply subject from the original request.
672    ///
673    /// Each request is processed in a newly created async tokio task.
674    ///
675    /// # Arguments
676    ///
677    /// * `instance` - Optional instance name to use in place of the `*` in the subject
678    /// * `group` - The queue group name for the subscription
679    /// * `process` - The function to call with the decoded request to produce a response
680    pub async fn stream_request_responder<Request, F, S, OP>(
681        &self,
682        instance: Option<&str>,
683        queue_group: Option<String>,
684        process: OP,
685    ) -> anyhow::Result<()>
686    where
687        Request: GenericStreamRequest,
688        F: Future<Output = Option<S>> + Send,
689        S: Stream<Item = Request::Response> + Unpin,
690        OP: Fn(Request) -> F + Send + Sync,
691    {
692        // Initialize with pending future so it never ends
693        let mut processing = FuturesUnordered::new();
694
695        let subscription = self
696            .common_subscribe(Request::SUBJECT, instance, queue_group)
697            .await
698            .map_err(|error| {
699                anyhow!(
700                    "Failed to subscribe to {} stream requests for {instance:?}: {error}",
701                    type_name::<Request>(),
702                )
703            })?;
704
705        debug!(
706            request_type = %type_name::<Request>(),
707            ?subscription,
708            "Stream requests subscription"
709        );
710        let mut subscription = subscription.fuse();
711
712        loop {
713            select! {
714                message = subscription.select_next_some() => {
715                    // Create background task for concurrent processing
716                    processing.push(
717                        self
718                        .process_stream_request(
719                            message,
720                            &process,
721                        )
722                        .in_current_span(),
723                    );
724                },
725                _ = processing.next() => {
726                    // Nothing to do here
727                },
728                complete => {
729                    break;
730                }
731            }
732        }
733
734        Ok(())
735    }
736
737    async fn process_stream_request<Request, F, S, OP>(&self, message: Message, process: OP)
738    where
739        Request: GenericStreamRequest,
740        F: Future<Output = Option<S>> + Send,
741        S: Stream<Item = Request::Response> + Unpin,
742        OP: Fn(Request) -> F + Send + Sync,
743    {
744        let Some(reply_subject) = message.reply else {
745            return;
746        };
747
748        let message_payload_size = message.payload.len();
749        let request = match decode_from_bytes::<Request>(message.payload.clone()) {
750            Ok(request) => {
751                // Free allocation early
752                drop(message.payload);
753                request
754            }
755            Err(error) => {
756                warn!(
757                    request_type = %type_name::<Request>(),
758                    %error,
759                    message = %hex::encode(message.payload),
760                    "Failed to decode request"
761                );
762                return;
763            }
764        };
765
766        // Avoid printing large messages in logs
767        if message_payload_size > 1024 {
768            trace!(
769                request_type = %type_name::<Request>(),
770                %reply_subject,
771                "Processing request"
772            );
773        } else {
774            trace!(
775                request_type = %type_name::<Request>(),
776                ?request,
777                %reply_subject,
778                "Processing request"
779            );
780        }
781
782        if let Some(stream) = process(request).await {
783            self.stream_response::<Request, _>(reply_subject, stream)
784                .await;
785        }
786    }
787
788    /// Helper method to send responses to requests initiated with [`Self::stream_request`]
789    async fn stream_response<Request, S>(&self, response_subject: Subject, response_stream: S)
790    where
791        Request: GenericStreamRequest,
792        S: Stream<Item = Request::Response> + Unpin,
793    {
794        type Response<Request> =
795            GenericStreamResponses<<Request as GenericStreamRequest>::Response>;
796
797        let mut response_stream = response_stream.fuse();
798
799        // Pull the first element to measure response size
800        let first_element = match response_stream.next().await {
801            Some(first_element) => first_element,
802            None => {
803                if let Err(error) = self
804                    .publish(
805                        response_subject.clone(),
806                        Response::<Request>::Last {
807                            index: 0,
808                            responses: VecDeque::new(),
809                        }
810                        .encode()
811                        .into(),
812                    )
813                    .await
814                {
815                    warn!(
816                        %response_subject,
817                        %error,
818                        request_type = %type_name::<Request>(),
819                        response_type = %type_name::<Request::Response>(),
820                        "Failed to send stream response"
821                    );
822                }
823
824                return;
825            }
826        };
827        let max_message_size = self.inner.max_message_size;
828        let approximate_max_message_size = self.approximate_max_message_size();
829        let max_responses_per_message = approximate_max_message_size / first_element.encoded_size();
830
831        let ack_subject = format!("stream-response-ack.{}", Ulid::generate());
832        let mut ack_subscription = match self.subscribe(ack_subject.clone()).await {
833            Ok(ack_subscription) => ack_subscription,
834            Err(error) => {
835                warn!(
836                    %response_subject,
837                    %error,
838                    request_type = %type_name::<Request>(),
839                    response_type = %type_name::<Request::Response>(),
840                    "Failed to subscribe to ack subject"
841                );
842                return;
843            }
844        };
845        debug!(
846            %response_subject,
847            request_type = %type_name::<Request>(),
848            response_type = %type_name::<Request::Response>(),
849            ?ack_subscription,
850            "Ack subscription subscription"
851        );
852        let mut index = 0;
853        // Initialize buffer that will be reused for responses
854        let mut buffer = VecDeque::with_capacity(max_responses_per_message);
855        buffer.push_back(first_element);
856        let mut overflow_buffer = VecDeque::new();
857
858        loop {
859            // Try to fill the buffer
860            if buffer.is_empty()
861                && let Some(element) = response_stream.next().await
862            {
863                buffer.push_back(element);
864            }
865            // Tracked incrementally, encoding the whole buffer for every added element is
866            // quadratic. Growth of the length prefix is not accounted for, but the size is
867            // approximate anyway and the real one is checked below.
868            let mut buffer_encoded_size = buffer.encoded_size();
869            while buffer_encoded_size < approximate_max_message_size
870                && let Some(element) = response_stream.next().now_or_never().flatten()
871            {
872                buffer_encoded_size += element.encoded_size();
873                buffer.push_back(element);
874            }
875
876            loop {
877                let is_done = response_stream.is_done() && overflow_buffer.is_empty();
878                let num_messages = buffer.len();
879                let response = if is_done {
880                    Response::<Request>::Last {
881                        index,
882                        responses: buffer,
883                    }
884                } else {
885                    Response::<Request>::Continue {
886                        index,
887                        responses: buffer,
888                        ack_subject: ack_subject.clone(),
889                    }
890                };
891                let encoded_response = response.encode();
892                let encoded_response_len = encoded_response.len();
893                // When encoded response is too large, remove one of the responses from it and try
894                // again
895                if encoded_response_len > max_message_size {
896                    buffer = response.into();
897                    if let Some(element) = buffer.pop_back() {
898                        if buffer.is_empty() {
899                            error!(
900                                ?element,
901                                encoded_response_len,
902                                max_message_size,
903                                "Element was too large to fit into NATS message, this is an \
904                                implementation bug"
905                            );
906                        }
907                        overflow_buffer.push_front(element);
908                        continue;
909                    } else {
910                        error!(
911                            %response_subject,
912                            request_type = %type_name::<Request>(),
913                            response_type = %type_name::<Request::Response>(),
914                            "Empty response overflown message size, this should never happen"
915                        );
916                        return;
917                    }
918                }
919
920                debug!(
921                    %response_subject,
922                    num_messages,
923                    %index,
924                    %is_done,
925                    "Publishing stream response messages",
926                );
927
928                if let Err(error) = self
929                    .publish(response_subject.clone(), encoded_response.into())
930                    .await
931                {
932                    warn!(
933                        %response_subject,
934                        %error,
935                        request_type = %type_name::<Request>(),
936                        response_type = %type_name::<Request::Response>(),
937                        "Failed to send stream response"
938                    );
939                    return;
940                }
941
942                if is_done {
943                    return;
944                } else {
945                    buffer = response.into();
946                    buffer.clear();
947                    // Fill buffer with any overflown responses that may have been stored
948                    buffer.extend(overflow_buffer.drain(..));
949                }
950
951                if index >= 1 {
952                    // Acknowledgements are received with delay
953                    let expected_index = index - 1;
954
955                    trace!(
956                        %response_subject,
957                        %expected_index,
958                        "Waiting for acknowledgement"
959                    );
960                    match tokio::time::timeout(ACKNOWLEDGEMENT_TIMEOUT, ack_subscription.next())
961                        .await
962                    {
963                        Ok(Some(message)) => {
964                            if let Some(received_index) = message
965                                .payload
966                                .split_at_checked(mem::size_of::<u32>())
967                                .map(|(bytes, _)| {
968                                    u32::from_le_bytes(
969                                        bytes.try_into().expect("Correctly chunked slice; qed"),
970                                    )
971                                })
972                            {
973                                debug!(
974                                    %response_subject,
975                                    %received_index,
976                                    "Received acknowledgement"
977                                );
978                                if received_index != expected_index {
979                                    warn!(
980                                        %response_subject,
981                                        %received_index,
982                                        %expected_index,
983                                        request_type = %type_name::<Request>(),
984                                        response_type = %type_name::<Request::Response>(),
985                                        message = %hex::encode(message.payload),
986                                        "Unexpected acknowledgement index"
987                                    );
988                                    return;
989                                }
990                            } else {
991                                warn!(
992                                    %response_subject,
993                                    request_type = %type_name::<Request>(),
994                                    response_type = %type_name::<Request::Response>(),
995                                    message = %hex::encode(message.payload),
996                                    "Unexpected acknowledgement message"
997                                );
998                                return;
999                            }
1000                        }
1001                        Ok(None) => {
1002                            warn!(
1003                                %response_subject,
1004                                request_type = %type_name::<Request>(),
1005                                response_type = %type_name::<Request::Response>(),
1006                                "Acknowledgement stream ended unexpectedly"
1007                            );
1008                            return;
1009                        }
1010                        Err(_error) => {
1011                            warn!(
1012                                %response_subject,
1013                                %expected_index,
1014                                request_type = %type_name::<Request>(),
1015                                response_type = %type_name::<Request::Response>(),
1016                                "Acknowledgement wait timed out"
1017                            );
1018                            return;
1019                        }
1020                    }
1021                }
1022
1023                index += 1;
1024
1025                // Unless `overflow_buffer` wasn't empty abort inner loop
1026                if buffer.is_empty() {
1027                    break;
1028                }
1029            }
1030        }
1031    }
1032
1033    /// Make notification without waiting for response
1034    pub async fn notification<Notification>(
1035        &self,
1036        notification: &Notification,
1037        instance: Option<&str>,
1038    ) -> Result<(), PublishError>
1039    where
1040        Notification: GenericNotification,
1041    {
1042        self.inner
1043            .client
1044            .publish(
1045                subject_with_instance(Notification::SUBJECT, instance),
1046                notification.encode().into(),
1047            )
1048            .await
1049    }
1050
1051    /// Send a broadcast message
1052    pub async fn broadcast<Broadcast>(
1053        &self,
1054        message: &Broadcast,
1055        instance: &str,
1056    ) -> Result<(), PublishError>
1057    where
1058        Broadcast: GenericBroadcast,
1059    {
1060        self.inner
1061            .client
1062            .publish_with_headers(
1063                Broadcast::SUBJECT.replace('*', instance),
1064                {
1065                    let mut headers = HeaderMap::new();
1066                    if let Some(message_id) = message.deterministic_message_id() {
1067                        headers.insert("Nats-Msg-Id", message_id);
1068                    }
1069                    headers
1070                },
1071                message.encode().into(),
1072            )
1073            .await
1074    }
1075
1076    /// Simple subscription that will produce decoded notifications, while skipping messages that
1077    /// fail to decode
1078    pub async fn subscribe_to_notifications<Notification>(
1079        &self,
1080        instance: Option<&str>,
1081        queue_group: Option<String>,
1082    ) -> Result<SubscriberWrapper<Notification>, SubscribeError>
1083    where
1084        Notification: GenericNotification,
1085    {
1086        self.simple_subscribe(Notification::SUBJECT, instance, queue_group)
1087            .await
1088    }
1089
1090    /// Simple subscription that will produce decoded broadcasts, while skipping messages that
1091    /// fail to decode
1092    pub async fn subscribe_to_broadcasts<Broadcast>(
1093        &self,
1094        instance: Option<&str>,
1095        queue_group: Option<String>,
1096    ) -> Result<SubscriberWrapper<Broadcast>, SubscribeError>
1097    where
1098        Broadcast: GenericBroadcast,
1099    {
1100        self.simple_subscribe(Broadcast::SUBJECT, instance, queue_group)
1101            .await
1102    }
1103
1104    /// Simple subscription that will produce decoded messages, while skipping messages that fail to
1105    /// decode
1106    async fn simple_subscribe<Message>(
1107        &self,
1108        subject: &'static str,
1109        instance: Option<&str>,
1110        queue_group: Option<String>,
1111    ) -> Result<SubscriberWrapper<Message>, SubscribeError>
1112    where
1113        Message: Decode,
1114    {
1115        let subscriber = self
1116            .common_subscribe(subject, instance, queue_group)
1117            .await?;
1118        debug!(
1119            %subject,
1120            message_type = %type_name::<Message>(),
1121            ?subscriber,
1122            "Simple subscription"
1123        );
1124
1125        Ok(SubscriberWrapper {
1126            subscriber,
1127            _phantom: PhantomData,
1128        })
1129    }
1130
1131    /// Simple subscription that will produce decoded messages, while skipping messages that fail to
1132    /// decode
1133    async fn common_subscribe(
1134        &self,
1135        subject: &'static str,
1136        instance: Option<&str>,
1137        queue_group: Option<String>,
1138    ) -> Result<Subscriber, SubscribeError> {
1139        let subscriber = if let Some(queue_group) = queue_group {
1140            self.inner
1141                .client
1142                .queue_subscribe(subject_with_instance(subject, instance), queue_group)
1143                .await?
1144        } else {
1145            self.inner
1146                .client
1147                .subscribe(subject_with_instance(subject, instance))
1148                .await?
1149        };
1150
1151        Ok(subscriber)
1152    }
1153}
1154
1155fn subject_with_instance(subject: &'static str, instance: Option<&str>) -> Subject {
1156    if let Some(instance) = instance {
1157        Subject::from(subject.replace('*', instance))
1158    } else {
1159        Subject::from_static(subject)
1160    }
1161}