watermelon 0.5.2

High level actor based implementation NATS Core and NATS Jetstream client implementation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
use std::{
    fmt::{self, Debug},
    future::IntoFuture,
};

use bytes::Bytes;
use serde::{Deserialize, Serialize};
use watermelon_proto::{
    StatusCode, Subject,
    headers::{HeaderMap, HeaderName, HeaderValue, error::HeaderValueValidateError},
};

use crate::{
    client::{ClientClosedError, JetstreamClient, JetstreamError},
    util::BoxFuture,
};

/// Error returned when a `JetStream` publish does not succeed.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum JetstreamPublishError {
    /// `JetStream` is not enabled for this account.
    #[error("jetstream not enabled for this account")]
    JetStreamNotEnabled,
    /// No stream matches the subject.
    #[error("no stream matches the subject")]
    NoStreamMatches,
    /// The stream is full.
    #[error("stream is full")]
    StreamFull,
    /// Messages are being discarded from the stream.
    #[error("messages are being discarded")]
    MessagesDiscarded,
    /// Other `JetStream` publish error.
    #[error("jetstream publish error: {0}")]
    Other(String),
}

/// Acknowledgment of a successful `JetStream` publish.
#[derive(Debug, Deserialize)]
pub struct PubAck {
    /// The stream the message was published to.
    pub stream: String,
    /// The sequence number of the message in the stream.
    #[serde(rename = "seq")]
    pub sequence: u64,
    /// The domain (if applicable).
    #[serde(default)]
    pub domain: Option<String>,
    /// The publish was a duplicate; this is the original sequence.
    #[serde(default)]
    pub duplicate: Option<bool>,
}

/// A publishable `JetStream` message.
#[derive(Debug)]
pub struct JetstreamPublish {
    subject: Subject,
    payload: Bytes,
    stream: Option<String>,
    expected_stream: Option<String>,
    expected_last_stream_sequence: Option<u64>,
    expected_last_subject_sequence: Option<u64>,
    expected_last_message_id: Option<String>,
    message_id: Option<String>,
    ttl: Option<u32>,
}

/// A constructor for a publishable `JetStream` message.
///
/// Obtained from [`JetstreamPublish::builder`].
#[derive(Debug)]
pub struct JetstreamPublishBuilder {
    publish: JetstreamPublish,
}

/// A constructor for a `JetStream` publishable message to be sent using the given client.
///
/// Obtained from [`JetstreamClient::publish`].
pub struct ClientJetstreamPublish<'a> {
    client: &'a JetstreamClient,
    publish: JetstreamPublish,
}

/// A `JetStream` publishable message ready to be published to the given client.
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct DoClientJetstreamPublish<'a> {
    client: &'a JetstreamClient,
    publish: JetstreamPublish,
}

/// A constructor for a `JetStream` publishable message to be sent using the given owned client.
///
/// Obtained from [`JetstreamClient::publish_owned`].
pub struct OwnedClientJetstreamPublish {
    client: JetstreamClient,
    publish: JetstreamPublish,
}

/// A `JetStream` publishable message ready to be published to the given owned client.
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct DoOwnedClientJetstreamPublish {
    client: JetstreamClient,
    publish: JetstreamPublish,
}

macro_rules! jetstream_publish_builder {
    ($payload_t:ty) => {
        /// Set the stream to publish to.
        #[must_use]
        pub fn stream(mut self, stream: &str) -> Self {
            self.publish_mut().stream = Some(stream.to_owned());
            self
        }

        /// Expect the message to be in this stream, fail otherwise.
        #[must_use]
        pub fn expected_stream(mut self, stream: &str) -> Self {
            self.publish_mut().expected_stream = Some(stream.to_owned());
            self
        }

        /// Expect the last stream sequence to match this value.
        #[must_use]
        pub fn expected_last_stream_sequence(mut self, sequence: u64) -> Self {
            self.publish_mut().expected_last_stream_sequence = Some(sequence);
            self
        }

        /// Expect the last subject sequence to match this value.
        #[must_use]
        pub fn expected_last_subject_sequence(mut self, sequence: u64) -> Self {
            self.publish_mut().expected_last_subject_sequence = Some(sequence);
            self
        }

        /// Expect the last message ID to match this value.
        #[must_use]
        pub fn expected_last_message_id(mut self, id: &str) -> Self {
            self.publish_mut().expected_last_message_id = Some(id.to_owned());
            self
        }

        /// Set a message ID for deduplication.
        #[must_use]
        pub fn message_id(mut self, id: &str) -> Self {
            self.publish_mut().message_id = Some(id.to_owned());
            self
        }

        /// Set a TTL in seconds after which to discard the message.
        #[must_use]
        pub fn ttl(mut self, seconds: u32) -> Self {
            self.publish_mut().ttl = Some(seconds);
            self
        }

        /// Serialize `payload` to JSON and use it as the payload.
        ///
        /// # Errors
        ///
        /// Returns an error if the serializer fails.
        pub fn payload_json<T: Serialize>(
            self,
            payload: &T,
        ) -> Result<$payload_t, serde_json::Error> {
            let payload = serde_json::to_vec(payload)?;
            Ok(self.payload(Bytes::from(payload)))
        }
    };
}

impl JetstreamPublish {
    /// Build a new [`JetstreamPublish`].
    #[must_use]
    pub fn builder(subject: Subject) -> JetstreamPublishBuilder {
        JetstreamPublishBuilder::subject(subject)
    }

    /// Publish this message to [`JetstreamClient`].
    pub fn client(self, client: &JetstreamClient) -> DoClientJetstreamPublish<'_> {
        DoClientJetstreamPublish {
            client,
            publish: self,
        }
    }

    /// Publish this message to [`JetstreamClient`], taking ownership of it.
    pub fn client_owned(self, client: JetstreamClient) -> DoOwnedClientJetstreamPublish {
        DoOwnedClientJetstreamPublish {
            client,
            publish: self,
        }
    }
}

impl JetstreamPublishBuilder {
    #[must_use]
    pub fn subject(subject: Subject) -> Self {
        Self {
            publish: JetstreamPublish {
                subject,
                payload: Bytes::new(),
                stream: None,
                expected_stream: None,
                expected_last_stream_sequence: None,
                expected_last_subject_sequence: None,
                expected_last_message_id: None,
                message_id: None,
                ttl: None,
            },
        }
    }

    jetstream_publish_builder!(JetstreamPublish);

    #[must_use]
    pub fn payload(mut self, payload: Bytes) -> JetstreamPublish {
        self.publish.payload = payload;
        self.publish
    }

    fn publish_mut(&mut self) -> &mut JetstreamPublish {
        &mut self.publish
    }
}

impl<'a> ClientJetstreamPublish<'a> {
    pub(crate) fn build(client: &'a JetstreamClient, subject: Subject) -> Self {
        Self {
            client,
            publish: JetstreamPublishBuilder::subject(subject).publish,
        }
    }

    jetstream_publish_builder!(DoClientJetstreamPublish<'a>);

    pub fn payload(mut self, payload: Bytes) -> DoClientJetstreamPublish<'a> {
        self.publish.payload = payload;
        self.publish.client(self.client)
    }

    /// Convert this into [`OwnedClientJetstreamPublish`].
    #[must_use]
    pub fn to_owned(self) -> OwnedClientJetstreamPublish {
        OwnedClientJetstreamPublish {
            client: self.client.clone(),
            publish: self.publish,
        }
    }

    fn publish_mut(&mut self) -> &mut JetstreamPublish {
        &mut self.publish
    }
}

impl OwnedClientJetstreamPublish {
    pub(crate) fn build(client: JetstreamClient, subject: Subject) -> Self {
        Self {
            client,
            publish: JetstreamPublishBuilder::subject(subject).publish,
        }
    }

    jetstream_publish_builder!(DoOwnedClientJetstreamPublish);

    pub fn payload(mut self, payload: Bytes) -> DoOwnedClientJetstreamPublish {
        self.publish.payload = payload;
        self.publish.client_owned(self.client)
    }

    fn publish_mut(&mut self) -> &mut JetstreamPublish {
        &mut self.publish
    }
}

impl DoClientJetstreamPublish<'_> {
    /// Publish this message and await the [`PubAck`].
    ///
    /// # Errors
    ///
    /// Returns an error if the client is closed or the server returns an error.
    pub async fn publish(self) -> Result<PubAck, JetstreamError> {
        do_publish(self.client, self.publish).await
    }
}

impl<'a> IntoFuture for DoClientJetstreamPublish<'a> {
    type Output = Result<PubAck, JetstreamError>;
    type IntoFuture = BoxFuture<'a, Self::Output>;

    fn into_future(self) -> Self::IntoFuture {
        Box::pin(async move { do_publish(self.client, self.publish).await })
    }
}

impl DoOwnedClientJetstreamPublish {
    /// Publish this message and await the [`PubAck`].
    ///
    /// # Errors
    ///
    /// Returns an error if the client is closed or the server returns an error.
    pub async fn publish(self) -> Result<PubAck, JetstreamError> {
        do_publish(&self.client, self.publish).await
    }
}

impl IntoFuture for DoOwnedClientJetstreamPublish {
    type Output = Result<PubAck, JetstreamError>;
    type IntoFuture = BoxFuture<'static, Self::Output>;

    fn into_future(self) -> Self::IntoFuture {
        Box::pin(async move { do_publish(&self.client, self.publish).await })
    }
}

/// Internal helper used by both the builder types and `JetstreamClient::publish`.
pub(crate) async fn do_publish(
    client: &JetstreamClient,
    jetstream_publish: JetstreamPublish,
) -> Result<PubAck, JetstreamError> {
    let JetstreamPublish {
        subject,
        payload,
        stream,
        expected_stream,
        expected_last_stream_sequence,
        expected_last_subject_sequence,
        expected_last_message_id,
        message_id,
        ttl,
    } = jetstream_publish;

    let headers = build_headers(
        stream.as_deref(),
        expected_stream.as_deref(),
        expected_last_stream_sequence,
        expected_last_subject_sequence,
        expected_last_message_id.as_deref(),
        message_id.as_deref(),
        ttl,
    )
    .map_err(JetstreamError::HeaderValue)?;

    // Use the core client's request API — it handles reply subjects,
    // multiplexed subscriptions, and timeouts for us.
    let response_fut = client
        .client()
        .request(subject)
        .headers(headers)
        .payload(payload)
        .await
        .map_err(JetstreamError::ClientClosed)?;

    let response = response_fut
        .await
        .map_err(|_| JetstreamError::ClientClosed(ClientClosedError))?;

    // Check for status codes
    if let Some(status) = response.status_code {
        if status == StatusCode::NO_RESPONDERS {
            return Err(JetstreamError::PublishStatus(
                crate::client::jetstream::JetstreamPublishError::JetStreamNotEnabled,
            ));
        }
        let status_u16 = u16::from(status);
        return Err(match status_u16 {
            503 => JetstreamError::PublishStatus(
                crate::client::jetstream::JetstreamPublishError::JetStreamNotEnabled,
            ),
            409 => JetstreamError::PublishStatus(
                crate::client::jetstream::JetstreamPublishError::NoStreamMatches,
            ),
            _ => {
                let detail = String::from_utf8_lossy(&response.base.payload).to_string();
                JetstreamError::PublishStatus(
                    crate::client::jetstream::JetstreamPublishError::Other(detail),
                )
            }
        });
    }

    let pub_ack =
        serde_json::from_slice::<PubAck>(&response.base.payload).map_err(JetstreamError::Json)?;
    Ok(pub_ack)
}

pub(crate) fn build_headers(
    stream: Option<&str>,
    expected_stream: Option<&str>,
    expected_last_stream_sequence: Option<u64>,
    expected_last_subject_sequence: Option<u64>,
    expected_last_message_id: Option<&str>,
    message_id: Option<&str>,
    ttl: Option<u32>,
) -> Result<HeaderMap, HeaderValueValidateError> {
    let mut headers = HeaderMap::new();

    if let Some(s) = stream {
        headers.insert(
            HeaderName::from_static("Nats-Stream"),
            HeaderValue::from_bytes(s.as_bytes())?,
        );
    }
    if let Some(s) = expected_stream {
        headers.insert(
            HeaderName::from_static("Nats-Expected-Stream"),
            HeaderValue::from_bytes(s.as_bytes())?,
        );
    }
    if let Some(seq) = expected_last_stream_sequence {
        headers.insert(
            HeaderName::from_static("Nats-Expected-Last-Sequence"),
            // Stringified integers are always valid header values
            HeaderValue::from_dangerous_value(Bytes::from(seq.to_string())),
        );
    }
    if let Some(seq) = expected_last_subject_sequence {
        headers.insert(
            HeaderName::from_static("Nats-Expected-Last-Subject-Sequence"),
            HeaderValue::from_dangerous_value(Bytes::from(seq.to_string())),
        );
    }
    if let Some(id) = expected_last_message_id {
        headers.insert(
            HeaderName::from_static("Nats-Expected-Last-Message-Id"),
            HeaderValue::from_bytes(id.as_bytes())?,
        );
    }
    if let Some(id) = message_id {
        headers.insert(
            HeaderName::from_static("Nats-Message-Id"),
            HeaderValue::from_bytes(id.as_bytes())?,
        );
    }
    if let Some(t) = ttl {
        headers.insert(
            HeaderName::from_static("Nats-TTL"),
            HeaderValue::from_dangerous_value(Bytes::from(t.to_string())),
        );
    }

    Ok(headers)
}

impl Debug for ClientJetstreamPublish<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ClientJetstreamPublish")
            .field("publish", &self.publish)
            .finish_non_exhaustive()
    }
}

impl Debug for DoClientJetstreamPublish<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("DoClientJetstreamPublish")
            .field("publish", &self.publish)
            .finish_non_exhaustive()
    }
}

impl Debug for OwnedClientJetstreamPublish {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("OwnedClientJetstreamPublish")
            .field("publish", &self.publish)
            .finish_non_exhaustive()
    }
}

impl Debug for DoOwnedClientJetstreamPublish {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("DoOwnedClientJetstreamPublish")
            .field("publish", &self.publish)
            .finish_non_exhaustive()
    }
}