pub struct HeaderMap { /* private fields */ }
Expand description

A struct for handling NATS headers. Has a similar API to http::header, but properly serializes and deserializes according to NATS requirements.

Examples

let client = async_nats::connect("demo.nats.io").await?;
let mut headers = async_nats::HeaderMap::new();
headers.insert("Key", "Value");
client.publish_with_headers("subject".to_string(), headers, "payload".into()).await?;

Implementations§

Examples found in repository?
src/jetstream/context.rs (line 898)
896
897
898
899
900
901
    pub fn header<N: IntoHeaderName, V: IntoHeaderValue>(mut self, name: N, value: V) -> Self {
        self.headers
            .get_or_insert(header::HeaderMap::new())
            .insert(name, value);
        self
    }
More examples
Hide additional examples
src/header.rs (line 65)
64
65
66
67
68
69
70
    fn from_iter<T: IntoIterator<Item = (HeaderName, HeaderValue)>>(iter: T) -> Self {
        let mut header_map = HeaderMap::new();
        for (key, value) in iter {
            header_map.insert(key, value);
        }
        header_map
    }
src/jetstream/stream.rs (line 1059)
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
fn parse_headers(
    buf: &[u8],
) -> Result<(Option<HeaderMap>, Option<StatusCode>, Option<String>), Error> {
    let mut headers = HeaderMap::new();
    let mut maybe_status: Option<StatusCode> = None;
    let mut maybe_description: Option<String> = None;
    let mut lines = if let Ok(line) = std::str::from_utf8(buf) {
        line.lines().peekable()
    } else {
        return Err(Box::new(std::io::Error::new(
            ErrorKind::Other,
            "invalid header",
        )));
    };

    if let Some(line) = lines.next() {
        if !line.starts_with(HEADER_LINE) {
            return Err(Box::new(std::io::Error::new(
                ErrorKind::Other,
                "version lie does not start with NATS/1.0",
            )));
        }

        // TODO: return this as description to be consistent?
        if let Some(slice) = line.get(HEADER_LINE_LEN..).map(|s| s.trim()) {
            match slice.split_once(' ') {
                Some((status, description)) => {
                    if !status.is_empty() {
                        maybe_status = Some(status.trim().parse()?);
                    }

                    if !description.is_empty() {
                        maybe_description = Some(description.trim().to_string());
                    }
                }
                None => {
                    if !slice.is_empty() {
                        maybe_status = Some(slice.trim().parse()?);
                    }
                }
            }
        }
    } else {
        return Err(Box::new(std::io::Error::new(
            ErrorKind::Other,
            "expected header information not found",
        )));
    };

    while let Some(line) = lines.next() {
        if line.is_empty() {
            continue;
        }

        if let Some((k, v)) = line.split_once(':').to_owned() {
            let mut s = String::from(v.trim());
            while let Some(v) = lines.next_if(|s| s.starts_with(is_continuation)).to_owned() {
                s.push(' ');
                s.push_str(v.trim());
            }

            headers.insert(
                HeaderName::from_str(k)?,
                HeaderValue::from_str(&s)
                    .map_err(|err| Box::new(io::Error::new(ErrorKind::Other, err)))?,
            );
        } else {
            return Err(Box::new(std::io::Error::new(
                ErrorKind::Other,
                "malformed header line",
            )));
        }
    }

    if headers.is_empty() {
        Ok((None, maybe_status, maybe_description))
    } else {
        Ok((Some(headers), maybe_status, maybe_description))
    }
}
src/jetstream/object_store/mod.rs (line 302)
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
    pub async fn put<T>(
        &self,
        meta: T,
        data: &mut (impl tokio::io::AsyncRead + std::marker::Unpin),
    ) -> Result<ObjectInfo, Error>
    where
        ObjectMeta: From<T>,
    {
        let object_meta: ObjectMeta = meta.into();

        let encoded_object_name = encode_object_name(&object_meta.name);
        if !is_valid_object_name(&encoded_object_name) {
            return Err(Box::new(io::Error::new(
                io::ErrorKind::InvalidInput,
                "invalid object name",
            )));
        }
        // Fetch any existing object info, if there is any for later use.
        let maybe_existing_object_info = match self.info(&encoded_object_name).await {
            Ok(object_info) => Some(object_info),
            Err(_) => None,
        };

        let object_nuid = nuid::next();
        let chunk_subject = format!("$O.{}.C.{}", &self.name, &object_nuid);

        let mut object_chunks = 0;
        let mut object_size = 0;

        let mut buffer = Box::new([0; DEFAULT_CHUNK_SIZE]);
        let mut context = ring::digest::Context::new(&SHA256);

        loop {
            let n = data.read(&mut *buffer).await?;

            if n == 0 {
                break;
            }
            context.update(&buffer[..n]);

            object_size += n;
            object_chunks += 1;

            // FIXME: this is ugly
            let payload = bytes::Bytes::from(buffer[..n].to_vec());

            self.stream
                .context
                .publish(chunk_subject.clone(), payload)
                .await?;
        }
        let digest = context.finish();
        let subject = format!("$O.{}.M.{}", &self.name, &encoded_object_name);
        let object_info = ObjectInfo {
            name: object_meta.name,
            description: object_meta.description,
            link: object_meta.link,
            bucket: self.name.clone(),
            nuid: object_nuid,
            chunks: object_chunks,
            size: object_size,
            digest: format!(
                "SHA-256={}",
                base64::encode_config(digest, base64::URL_SAFE)
            ),
            modified: OffsetDateTime::now_utc(),
            deleted: false,
        };

        let mut headers = HeaderMap::new();
        headers.insert(NATS_ROLLUP, ROLLUP_SUBJECT.parse::<HeaderValue>()?);
        let data = serde_json::to_vec(&object_info)?;

        // publish meta.
        self.stream
            .context
            .publish_with_headers(subject, headers, data.into())
            .await?;

        // Purge any old chunks.
        if let Some(existing_object_info) = maybe_existing_object_info {
            let chunk_subject = format!("$O.{}.C.{}", &self.name, &existing_object_info.nuid);

            self.stream.purge_subject(&chunk_subject).await?;
        }

        Ok(object_info)
    }
src/connection.rs (line 269)
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
    pub(crate) fn try_read_op(&mut self) -> Result<Option<ServerOp>, io::Error> {
        let maybe_len = self.buffer.find(b"\r\n");
        if maybe_len.is_none() {
            return Ok(None);
        }

        let len = maybe_len.unwrap();

        if self.buffer.starts_with(b"+OK") {
            self.buffer.advance(len + 2);
            return Ok(Some(ServerOp::Ok));
        }

        if self.buffer.starts_with(b"PING") {
            self.buffer.advance(len + 2);
            return Ok(Some(ServerOp::Ping));
        }

        if self.buffer.starts_with(b"PONG") {
            self.buffer.advance(len + 2);
            return Ok(Some(ServerOp::Pong));
        }

        if self.buffer.starts_with(b"-ERR") {
            let description = str::from_utf8(&self.buffer[5..len])
                .map_err(|err| io::Error::new(io::ErrorKind::InvalidInput, err))?
                .trim_matches('\'')
                .to_string();

            self.buffer.advance(len + 2);

            return Ok(Some(ServerOp::Error(ServerError::new(description))));
        }

        if self.buffer.starts_with(b"INFO ") {
            let info = serde_json::from_slice(&self.buffer[4..len])
                .map_err(|err| io::Error::new(io::ErrorKind::InvalidInput, err))?;

            self.buffer.advance(len + 2);

            return Ok(Some(ServerOp::Info(Box::new(info))));
        }

        if self.buffer.starts_with(b"MSG ") {
            let line = str::from_utf8(&self.buffer[4..len]).unwrap();
            let args = line.split(' ').filter(|s| !s.is_empty());
            // TODO(caspervonb) we can drop this alloc
            let args = args.collect::<Vec<_>>();

            // Parse the operation syntax: MSG <subject> <sid> [reply-to] <#bytes>
            let (subject, sid, reply_to, payload_len) = match args[..] {
                [subject, sid, payload_len] => (subject, sid, None, payload_len),
                [subject, sid, reply_to, payload_len] => {
                    (subject, sid, Some(reply_to), payload_len)
                }
                _ => {
                    return Err(io::Error::new(
                        io::ErrorKind::InvalidInput,
                        "invalid number of arguments after MSG",
                    ));
                }
            };

            let sid = u64::from_str(sid)
                .map_err(|err| io::Error::new(io::ErrorKind::InvalidInput, err))?;

            // Parse the number of payload bytes.
            let payload_len = usize::from_str(payload_len)
                .map_err(|err| io::Error::new(io::ErrorKind::InvalidInput, err))?;

            // Return early without advancing if there is not enough data read the entire
            // message
            if len + payload_len + 4 > self.buffer.remaining() {
                return Ok(None);
            }

            let subject = subject.to_owned();
            let reply_to = reply_to.map(String::from);

            self.buffer.advance(len + 2);
            let payload = self.buffer.split_to(payload_len).freeze();
            self.buffer.advance(2);

            return Ok(Some(ServerOp::Message {
                sid,
                length: payload_len
                    + reply_to.as_ref().map(|reply| reply.len()).unwrap_or(0)
                    + subject.len(),
                reply: reply_to,
                headers: None,
                subject,
                payload,
                status: None,
                description: None,
            }));
        }

        if self.buffer.starts_with(b"HMSG ") {
            // Extract whitespace-delimited arguments that come after "HMSG".
            let line = std::str::from_utf8(&self.buffer[5..len]).unwrap();
            let args = line.split_whitespace().filter(|s| !s.is_empty());
            let args = args.collect::<Vec<_>>();

            // <subject> <sid> [reply-to] <# header bytes><# total bytes>
            let (subject, sid, reply_to, num_header_bytes, num_bytes) = match args[..] {
                [subject, sid, num_header_bytes, num_bytes] => {
                    (subject, sid, None, num_header_bytes, num_bytes)
                }
                [subject, sid, reply_to, num_header_bytes, num_bytes] => {
                    (subject, sid, Some(reply_to), num_header_bytes, num_bytes)
                }
                _ => {
                    return Err(io::Error::new(
                        io::ErrorKind::InvalidInput,
                        "invalid number of arguments after HMSG",
                    ));
                }
            };

            // Convert the slice into an owned string.
            let subject = subject.to_string();

            // Parse the subject ID.
            let sid = u64::from_str(sid).map_err(|_| {
                io::Error::new(
                    io::ErrorKind::InvalidInput,
                    "cannot parse sid argument after HMSG",
                )
            })?;

            // Convert the slice into an owned string.
            let reply_to = reply_to.map(ToString::to_string);

            // Parse the number of payload bytes.
            let num_header_bytes = usize::from_str(num_header_bytes).map_err(|_| {
                io::Error::new(
                    io::ErrorKind::InvalidInput,
                    "cannot parse the number of header bytes argument after \
                     HMSG",
                )
            })?;

            // Parse the number of payload bytes.
            let num_bytes = usize::from_str(num_bytes).map_err(|_| {
                io::Error::new(
                    io::ErrorKind::InvalidInput,
                    "cannot parse the number of bytes argument after HMSG",
                )
            })?;

            if num_bytes < num_header_bytes {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidInput,
                    "number of header bytes was greater than or equal to the \
                 total number of bytes after HMSG",
                ));
            }

            if len + num_bytes + 4 > self.buffer.remaining() {
                return Ok(None);
            }

            self.buffer.advance(len + 2);
            let buffer = self.buffer.split_to(num_header_bytes).freeze();
            let payload = self.buffer.split_to(num_bytes - num_header_bytes).freeze();
            self.buffer.advance(2);

            let mut lines = std::str::from_utf8(&buffer).unwrap().lines().peekable();
            let version_line = lines.next().ok_or_else(|| {
                io::Error::new(io::ErrorKind::InvalidInput, "no header version line found")
            })?;

            if !version_line.starts_with("NATS/1.0") {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidInput,
                    "header version line does not begin with nats/1.0",
                ));
            }

            let mut maybe_status: Option<StatusCode> = None;
            let mut maybe_description: Option<String> = None;
            if let Some(slice) = version_line.get("NATS/1.0".len()..).map(|s| s.trim()) {
                match slice.split_once(' ') {
                    Some((status, description)) => {
                        if !status.is_empty() {
                            maybe_status = Some(status.trim().parse().map_err(|_| {
                                std::io::Error::new(
                                    io::ErrorKind::Other,
                                    "could not covert Description header into header value",
                                )
                            })?);
                        }
                        if !description.is_empty() {
                            maybe_description = Some(description.trim().to_string());
                        }
                    }
                    None => {
                        if !slice.is_empty() {
                            maybe_status = Some(slice.trim().parse().map_err(|_| {
                                std::io::Error::new(
                                    io::ErrorKind::Other,
                                    "could not covert Description header into header value",
                                )
                            })?);
                        }
                    }
                }
            }

            let mut headers = HeaderMap::new();
            while let Some(line) = lines.next() {
                if line.is_empty() {
                    continue;
                }

                let (key, value) = line.split_once(':').ok_or_else(|| {
                    io::Error::new(io::ErrorKind::InvalidInput, "no header version line found")
                })?;

                let mut value = String::from_str(value).unwrap();
                while let Some(v) = lines.next_if(|s| s.starts_with(char::is_whitespace)) {
                    value.push_str(v);
                }

                headers.append(HeaderName::from_str(key).unwrap(), value.trim().to_string());
            }

            return Ok(Some(ServerOp::Message {
                length: reply_to.as_ref().map(|reply| reply.len()).unwrap_or(0)
                    + subject.len()
                    + num_bytes,
                sid,
                reply: reply_to,
                subject,
                headers: Some(headers),
                payload,
                status: maybe_status,
                description: maybe_description,
            }));
        }

        let buffer = self.buffer.split_to(len + 2);
        let line = str::from_utf8(&buffer).map_err(|_| {
            io::Error::new(io::ErrorKind::InvalidInput, "unable to parse unknown input")
        })?;

        Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            format!("invalid server operation: '{line}'"),
        ))
    }
Examples found in repository?
src/jetstream/stream.rs (line 1130)
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
fn parse_headers(
    buf: &[u8],
) -> Result<(Option<HeaderMap>, Option<StatusCode>, Option<String>), Error> {
    let mut headers = HeaderMap::new();
    let mut maybe_status: Option<StatusCode> = None;
    let mut maybe_description: Option<String> = None;
    let mut lines = if let Ok(line) = std::str::from_utf8(buf) {
        line.lines().peekable()
    } else {
        return Err(Box::new(std::io::Error::new(
            ErrorKind::Other,
            "invalid header",
        )));
    };

    if let Some(line) = lines.next() {
        if !line.starts_with(HEADER_LINE) {
            return Err(Box::new(std::io::Error::new(
                ErrorKind::Other,
                "version lie does not start with NATS/1.0",
            )));
        }

        // TODO: return this as description to be consistent?
        if let Some(slice) = line.get(HEADER_LINE_LEN..).map(|s| s.trim()) {
            match slice.split_once(' ') {
                Some((status, description)) => {
                    if !status.is_empty() {
                        maybe_status = Some(status.trim().parse()?);
                    }

                    if !description.is_empty() {
                        maybe_description = Some(description.trim().to_string());
                    }
                }
                None => {
                    if !slice.is_empty() {
                        maybe_status = Some(slice.trim().parse()?);
                    }
                }
            }
        }
    } else {
        return Err(Box::new(std::io::Error::new(
            ErrorKind::Other,
            "expected header information not found",
        )));
    };

    while let Some(line) = lines.next() {
        if line.is_empty() {
            continue;
        }

        if let Some((k, v)) = line.split_once(':').to_owned() {
            let mut s = String::from(v.trim());
            while let Some(v) = lines.next_if(|s| s.starts_with(is_continuation)).to_owned() {
                s.push(' ');
                s.push_str(v.trim());
            }

            headers.insert(
                HeaderName::from_str(k)?,
                HeaderValue::from_str(&s)
                    .map_err(|err| Box::new(io::Error::new(ErrorKind::Other, err)))?,
            );
        } else {
            return Err(Box::new(std::io::Error::new(
                ErrorKind::Other,
                "malformed header line",
            )));
        }
    }

    if headers.is_empty() {
        Ok((None, maybe_status, maybe_description))
    } else {
        Ok((Some(headers), maybe_status, maybe_description))
    }
}

Inserts a new value to a HeaderMap.

Examples
let mut headers = async_nats::HeaderMap::new();
headers.insert("Key", "Value");
Examples found in repository?
src/jetstream/context.rs (line 899)
896
897
898
899
900
901
    pub fn header<N: IntoHeaderName, V: IntoHeaderValue>(mut self, name: N, value: V) -> Self {
        self.headers
            .get_or_insert(header::HeaderMap::new())
            .insert(name, value);
        self
    }
More examples
Hide additional examples
src/header.rs (line 67)
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
    fn from_iter<T: IntoIterator<Item = (HeaderName, HeaderValue)>>(iter: T) -> Self {
        let mut header_map = HeaderMap::new();
        for (key, value) in iter {
            header_map.insert(key, value);
        }
        header_map
    }
}

impl HeaderMap {
    pub fn iter(&self) -> std::collections::hash_map::Iter<'_, HeaderName, HeaderValue> {
        self.inner.iter()
    }
}

impl HeaderMap {
    pub fn new() -> Self {
        HeaderMap::default()
    }

    pub fn is_empty(&self) -> bool {
        self.inner.is_empty()
    }
}

impl HeaderMap {
    /// Inserts a new value to a [HeaderMap].
    ///
    /// # Examples
    ///
    /// ```
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), async_nats::Error> {
    /// let mut headers = async_nats::HeaderMap::new();
    /// headers.insert("Key", "Value");
    /// # Ok(())
    /// # }
    /// ```
    pub fn insert<K: IntoHeaderName, V: IntoHeaderValue>(&mut self, name: K, value: V) {
        self.inner
            .insert(name.into_header_name(), value.into_header_value());
    }

    /// Appends a new value to the list of values to a given key.
    /// If the key did not exist, it will be inserted with provided value.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), async_nats::Error> {
    /// let mut headers = async_nats::HeaderMap::new();
    /// headers.append("Key", "Value");
    /// headers.append("Key", "Another");
    /// # Ok(())
    /// # }
    /// ```
    pub fn append<K: IntoHeaderName, V: ToString>(&mut self, name: K, value: V) {
        let key = name.into_header_name();
        let v = self.inner.get_mut(&key);
        match v {
            Some(v) => {
                v.value.push(value.to_string());
            }
            None => {
                self.insert(key, value.to_string().into_header_value());
            }
        }
    }
src/jetstream/kv/mod.rs (lines 487-490)
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
    pub async fn update<T: AsRef<str>>(
        &self,
        key: T,
        value: Bytes,
        revision: u64,
    ) -> Result<u64, Error> {
        if !is_valid_key(key.as_ref()) {
            return Err(Box::new(io::Error::new(
                io::ErrorKind::InvalidInput,
                "invalid key",
            )));
        }
        let subject = format!("{}{}", self.prefix.as_str(), key.as_ref());

        let mut headers = crate::HeaderMap::default();
        headers.insert(
            header::NATS_EXPECTED_LAST_SUBJECT_SEQUENCE,
            HeaderValue::from(revision),
        );

        self.stream
            .context
            .publish_with_headers(subject, headers, value)
            .await?
            .await
            .map(|publish_ack| publish_ack.sequence)
    }

    /// Deletes a given key. This is a non-destructive operation, which sets a `DELETE` marker.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), async_nats::Error> {
    /// use futures::StreamExt;
    /// let client = async_nats::connect("demo.nats.io:4222").await?;
    /// let jetstream = async_nats::jetstream::new(client);
    /// let kv = jetstream.create_key_value(async_nats::jetstream::kv::Config {
    ///     bucket: "kv".to_string(),
    ///     history: 10,
    ///     ..Default::default()
    /// }).await?;
    /// kv.put("key", "value".into()).await?;
    /// kv.delete("key").await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn delete<T: AsRef<str>>(&self, key: T) -> Result<(), Error> {
        if !is_valid_key(key.as_ref()) {
            return Err(Box::new(io::Error::new(
                io::ErrorKind::InvalidInput,
                "invalid key",
            )));
        }
        let mut subject = String::new();
        if self.use_jetstream_prefix {
            subject.push_str(&self.stream.context.prefix);
            subject.push('.');
        }
        subject.push_str(self.put_prefix.as_ref().unwrap_or(&self.prefix));
        subject.push_str(key.as_ref());

        let mut headers = crate::HeaderMap::default();
        // TODO: figure out which headers k/v should be where.
        headers.insert(KV_OPERATION, KV_OPERATION_DELETE.parse::<HeaderValue>()?);

        self.stream
            .context
            .publish_with_headers(subject, headers, "".into())
            .await?;
        Ok(())
    }

    /// Purges all the revisions of a entry destructively, leaving behind a single purge entry in-place.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), async_nats::Error> {
    /// use futures::StreamExt;
    /// let client = async_nats::connect("demo.nats.io:4222").await?;
    /// let jetstream = async_nats::jetstream::new(client);
    /// let kv = jetstream.create_key_value(async_nats::jetstream::kv::Config {
    ///     bucket: "kv".to_string(),
    ///     history: 10,
    ///     ..Default::default()
    /// }).await?;
    /// kv.put("key", "value".into()).await?;
    /// kv.put("key", "another".into()).await?;
    /// kv.purge("key").await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn purge<T: AsRef<str>>(&self, key: T) -> Result<(), Error> {
        if !is_valid_key(key.as_ref()) {
            return Err(Box::new(io::Error::new(
                io::ErrorKind::InvalidInput,
                "invalid key",
            )));
        }

        let subject = format!("{}{}", self.prefix.as_str(), key.as_ref());

        let mut headers = crate::HeaderMap::default();
        headers.insert(KV_OPERATION, HeaderValue::from(KV_OPERATION_PURGE));
        headers.insert(NATS_ROLLUP, HeaderValue::from(ROLLUP_SUBJECT));

        self.stream
            .context
            .publish_with_headers(subject, headers, "".into())
            .await?;
        Ok(())
    }
src/jetstream/object_store/mod.rs (line 161)
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
    pub async fn delete<T: AsRef<str>>(&self, object_name: T) -> Result<(), Error> {
        let object_name = object_name.as_ref();
        let mut object_info = self.info(object_name).await?;
        object_info.chunks = 0;
        object_info.size = 0;
        object_info.deleted = true;

        let data = serde_json::to_vec(&object_info)?;

        let mut headers = HeaderMap::default();
        headers.insert(NATS_ROLLUP, HeaderValue::from_str(ROLLUP_SUBJECT)?);

        let subject = format!("$O.{}.M.{}", &self.name, encode_object_name(object_name));

        self.stream
            .context
            .publish_with_headers(subject, headers, data.into())
            .await?;

        let chunk_subject = format!("$O.{}.C.{}", self.name, object_info.nuid);

        self.stream.purge_subject(&chunk_subject).await?;

        Ok(())
    }

    /// Retrieves [Object] [ObjectInfo].
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), async_nats::Error> {
    /// let client = async_nats::connect("demo.nats.io").await?;
    /// let jetstream = async_nats::jetstream::new(client);
    ///
    /// let bucket = jetstream.get_object_store("store").await?;
    /// let info = bucket.info("FOO").await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn info<T: AsRef<str>>(&self, object_name: T) -> Result<ObjectInfo, Error> {
        let object_name = object_name.as_ref();
        let object_name = encode_object_name(object_name);
        if !is_valid_object_name(&object_name) {
            return Err(Box::new(io::Error::new(
                io::ErrorKind::InvalidInput,
                "invalid object name",
            )));
        }

        // Grab last meta value we have.
        let subject = format!("$O.{}.M.{}", &self.name, &object_name);

        let message = self
            .stream
            .get_last_raw_message_by_subject(subject.as_str())
            .await?;
        let decoded_payload = base64::decode(message.payload)
            .map_err(|err| Box::new(std::io::Error::new(ErrorKind::Other, err)))?;
        let object_info = serde_json::from_slice::<ObjectInfo>(&decoded_payload)?;

        Ok(object_info)
    }

    /// Puts an [Object] into the [ObjectStore].
    /// This method implements `tokio::io::AsyncRead`.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), async_nats::Error> {
    /// let client = async_nats::connect("demo.nats.io").await?;
    /// let jetstream = async_nats::jetstream::new(client);
    ///
    /// let bucket = jetstream.get_object_store("store").await?;
    /// let mut file = tokio::fs::File::open("foo.txt").await?;
    /// bucket.put("file", &mut file).await.unwrap();
    /// # Ok(())
    /// # }
    /// ```
    pub async fn put<T>(
        &self,
        meta: T,
        data: &mut (impl tokio::io::AsyncRead + std::marker::Unpin),
    ) -> Result<ObjectInfo, Error>
    where
        ObjectMeta: From<T>,
    {
        let object_meta: ObjectMeta = meta.into();

        let encoded_object_name = encode_object_name(&object_meta.name);
        if !is_valid_object_name(&encoded_object_name) {
            return Err(Box::new(io::Error::new(
                io::ErrorKind::InvalidInput,
                "invalid object name",
            )));
        }
        // Fetch any existing object info, if there is any for later use.
        let maybe_existing_object_info = match self.info(&encoded_object_name).await {
            Ok(object_info) => Some(object_info),
            Err(_) => None,
        };

        let object_nuid = nuid::next();
        let chunk_subject = format!("$O.{}.C.{}", &self.name, &object_nuid);

        let mut object_chunks = 0;
        let mut object_size = 0;

        let mut buffer = Box::new([0; DEFAULT_CHUNK_SIZE]);
        let mut context = ring::digest::Context::new(&SHA256);

        loop {
            let n = data.read(&mut *buffer).await?;

            if n == 0 {
                break;
            }
            context.update(&buffer[..n]);

            object_size += n;
            object_chunks += 1;

            // FIXME: this is ugly
            let payload = bytes::Bytes::from(buffer[..n].to_vec());

            self.stream
                .context
                .publish(chunk_subject.clone(), payload)
                .await?;
        }
        let digest = context.finish();
        let subject = format!("$O.{}.M.{}", &self.name, &encoded_object_name);
        let object_info = ObjectInfo {
            name: object_meta.name,
            description: object_meta.description,
            link: object_meta.link,
            bucket: self.name.clone(),
            nuid: object_nuid,
            chunks: object_chunks,
            size: object_size,
            digest: format!(
                "SHA-256={}",
                base64::encode_config(digest, base64::URL_SAFE)
            ),
            modified: OffsetDateTime::now_utc(),
            deleted: false,
        };

        let mut headers = HeaderMap::new();
        headers.insert(NATS_ROLLUP, ROLLUP_SUBJECT.parse::<HeaderValue>()?);
        let data = serde_json::to_vec(&object_info)?;

        // publish meta.
        self.stream
            .context
            .publish_with_headers(subject, headers, data.into())
            .await?;

        // Purge any old chunks.
        if let Some(existing_object_info) = maybe_existing_object_info {
            let chunk_subject = format!("$O.{}.C.{}", &self.name, &existing_object_info.nuid);

            self.stream.purge_subject(&chunk_subject).await?;
        }

        Ok(object_info)
    }
src/jetstream/stream.rs (lines 1117-1121)
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
fn parse_headers(
    buf: &[u8],
) -> Result<(Option<HeaderMap>, Option<StatusCode>, Option<String>), Error> {
    let mut headers = HeaderMap::new();
    let mut maybe_status: Option<StatusCode> = None;
    let mut maybe_description: Option<String> = None;
    let mut lines = if let Ok(line) = std::str::from_utf8(buf) {
        line.lines().peekable()
    } else {
        return Err(Box::new(std::io::Error::new(
            ErrorKind::Other,
            "invalid header",
        )));
    };

    if let Some(line) = lines.next() {
        if !line.starts_with(HEADER_LINE) {
            return Err(Box::new(std::io::Error::new(
                ErrorKind::Other,
                "version lie does not start with NATS/1.0",
            )));
        }

        // TODO: return this as description to be consistent?
        if let Some(slice) = line.get(HEADER_LINE_LEN..).map(|s| s.trim()) {
            match slice.split_once(' ') {
                Some((status, description)) => {
                    if !status.is_empty() {
                        maybe_status = Some(status.trim().parse()?);
                    }

                    if !description.is_empty() {
                        maybe_description = Some(description.trim().to_string());
                    }
                }
                None => {
                    if !slice.is_empty() {
                        maybe_status = Some(slice.trim().parse()?);
                    }
                }
            }
        }
    } else {
        return Err(Box::new(std::io::Error::new(
            ErrorKind::Other,
            "expected header information not found",
        )));
    };

    while let Some(line) = lines.next() {
        if line.is_empty() {
            continue;
        }

        if let Some((k, v)) = line.split_once(':').to_owned() {
            let mut s = String::from(v.trim());
            while let Some(v) = lines.next_if(|s| s.starts_with(is_continuation)).to_owned() {
                s.push(' ');
                s.push_str(v.trim());
            }

            headers.insert(
                HeaderName::from_str(k)?,
                HeaderValue::from_str(&s)
                    .map_err(|err| Box::new(io::Error::new(ErrorKind::Other, err)))?,
            );
        } else {
            return Err(Box::new(std::io::Error::new(
                ErrorKind::Other,
                "malformed header line",
            )));
        }
    }

    if headers.is_empty() {
        Ok((None, maybe_status, maybe_description))
    } else {
        Ok((Some(headers), maybe_status, maybe_description))
    }
}

Appends a new value to the list of values to a given key. If the key did not exist, it will be inserted with provided value.

Examples
let mut headers = async_nats::HeaderMap::new();
headers.append("Key", "Value");
headers.append("Key", "Another");
Examples found in repository?
src/connection.rs (line 284)
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
    pub(crate) fn try_read_op(&mut self) -> Result<Option<ServerOp>, io::Error> {
        let maybe_len = self.buffer.find(b"\r\n");
        if maybe_len.is_none() {
            return Ok(None);
        }

        let len = maybe_len.unwrap();

        if self.buffer.starts_with(b"+OK") {
            self.buffer.advance(len + 2);
            return Ok(Some(ServerOp::Ok));
        }

        if self.buffer.starts_with(b"PING") {
            self.buffer.advance(len + 2);
            return Ok(Some(ServerOp::Ping));
        }

        if self.buffer.starts_with(b"PONG") {
            self.buffer.advance(len + 2);
            return Ok(Some(ServerOp::Pong));
        }

        if self.buffer.starts_with(b"-ERR") {
            let description = str::from_utf8(&self.buffer[5..len])
                .map_err(|err| io::Error::new(io::ErrorKind::InvalidInput, err))?
                .trim_matches('\'')
                .to_string();

            self.buffer.advance(len + 2);

            return Ok(Some(ServerOp::Error(ServerError::new(description))));
        }

        if self.buffer.starts_with(b"INFO ") {
            let info = serde_json::from_slice(&self.buffer[4..len])
                .map_err(|err| io::Error::new(io::ErrorKind::InvalidInput, err))?;

            self.buffer.advance(len + 2);

            return Ok(Some(ServerOp::Info(Box::new(info))));
        }

        if self.buffer.starts_with(b"MSG ") {
            let line = str::from_utf8(&self.buffer[4..len]).unwrap();
            let args = line.split(' ').filter(|s| !s.is_empty());
            // TODO(caspervonb) we can drop this alloc
            let args = args.collect::<Vec<_>>();

            // Parse the operation syntax: MSG <subject> <sid> [reply-to] <#bytes>
            let (subject, sid, reply_to, payload_len) = match args[..] {
                [subject, sid, payload_len] => (subject, sid, None, payload_len),
                [subject, sid, reply_to, payload_len] => {
                    (subject, sid, Some(reply_to), payload_len)
                }
                _ => {
                    return Err(io::Error::new(
                        io::ErrorKind::InvalidInput,
                        "invalid number of arguments after MSG",
                    ));
                }
            };

            let sid = u64::from_str(sid)
                .map_err(|err| io::Error::new(io::ErrorKind::InvalidInput, err))?;

            // Parse the number of payload bytes.
            let payload_len = usize::from_str(payload_len)
                .map_err(|err| io::Error::new(io::ErrorKind::InvalidInput, err))?;

            // Return early without advancing if there is not enough data read the entire
            // message
            if len + payload_len + 4 > self.buffer.remaining() {
                return Ok(None);
            }

            let subject = subject.to_owned();
            let reply_to = reply_to.map(String::from);

            self.buffer.advance(len + 2);
            let payload = self.buffer.split_to(payload_len).freeze();
            self.buffer.advance(2);

            return Ok(Some(ServerOp::Message {
                sid,
                length: payload_len
                    + reply_to.as_ref().map(|reply| reply.len()).unwrap_or(0)
                    + subject.len(),
                reply: reply_to,
                headers: None,
                subject,
                payload,
                status: None,
                description: None,
            }));
        }

        if self.buffer.starts_with(b"HMSG ") {
            // Extract whitespace-delimited arguments that come after "HMSG".
            let line = std::str::from_utf8(&self.buffer[5..len]).unwrap();
            let args = line.split_whitespace().filter(|s| !s.is_empty());
            let args = args.collect::<Vec<_>>();

            // <subject> <sid> [reply-to] <# header bytes><# total bytes>
            let (subject, sid, reply_to, num_header_bytes, num_bytes) = match args[..] {
                [subject, sid, num_header_bytes, num_bytes] => {
                    (subject, sid, None, num_header_bytes, num_bytes)
                }
                [subject, sid, reply_to, num_header_bytes, num_bytes] => {
                    (subject, sid, Some(reply_to), num_header_bytes, num_bytes)
                }
                _ => {
                    return Err(io::Error::new(
                        io::ErrorKind::InvalidInput,
                        "invalid number of arguments after HMSG",
                    ));
                }
            };

            // Convert the slice into an owned string.
            let subject = subject.to_string();

            // Parse the subject ID.
            let sid = u64::from_str(sid).map_err(|_| {
                io::Error::new(
                    io::ErrorKind::InvalidInput,
                    "cannot parse sid argument after HMSG",
                )
            })?;

            // Convert the slice into an owned string.
            let reply_to = reply_to.map(ToString::to_string);

            // Parse the number of payload bytes.
            let num_header_bytes = usize::from_str(num_header_bytes).map_err(|_| {
                io::Error::new(
                    io::ErrorKind::InvalidInput,
                    "cannot parse the number of header bytes argument after \
                     HMSG",
                )
            })?;

            // Parse the number of payload bytes.
            let num_bytes = usize::from_str(num_bytes).map_err(|_| {
                io::Error::new(
                    io::ErrorKind::InvalidInput,
                    "cannot parse the number of bytes argument after HMSG",
                )
            })?;

            if num_bytes < num_header_bytes {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidInput,
                    "number of header bytes was greater than or equal to the \
                 total number of bytes after HMSG",
                ));
            }

            if len + num_bytes + 4 > self.buffer.remaining() {
                return Ok(None);
            }

            self.buffer.advance(len + 2);
            let buffer = self.buffer.split_to(num_header_bytes).freeze();
            let payload = self.buffer.split_to(num_bytes - num_header_bytes).freeze();
            self.buffer.advance(2);

            let mut lines = std::str::from_utf8(&buffer).unwrap().lines().peekable();
            let version_line = lines.next().ok_or_else(|| {
                io::Error::new(io::ErrorKind::InvalidInput, "no header version line found")
            })?;

            if !version_line.starts_with("NATS/1.0") {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidInput,
                    "header version line does not begin with nats/1.0",
                ));
            }

            let mut maybe_status: Option<StatusCode> = None;
            let mut maybe_description: Option<String> = None;
            if let Some(slice) = version_line.get("NATS/1.0".len()..).map(|s| s.trim()) {
                match slice.split_once(' ') {
                    Some((status, description)) => {
                        if !status.is_empty() {
                            maybe_status = Some(status.trim().parse().map_err(|_| {
                                std::io::Error::new(
                                    io::ErrorKind::Other,
                                    "could not covert Description header into header value",
                                )
                            })?);
                        }
                        if !description.is_empty() {
                            maybe_description = Some(description.trim().to_string());
                        }
                    }
                    None => {
                        if !slice.is_empty() {
                            maybe_status = Some(slice.trim().parse().map_err(|_| {
                                std::io::Error::new(
                                    io::ErrorKind::Other,
                                    "could not covert Description header into header value",
                                )
                            })?);
                        }
                    }
                }
            }

            let mut headers = HeaderMap::new();
            while let Some(line) = lines.next() {
                if line.is_empty() {
                    continue;
                }

                let (key, value) = line.split_once(':').ok_or_else(|| {
                    io::Error::new(io::ErrorKind::InvalidInput, "no header version line found")
                })?;

                let mut value = String::from_str(value).unwrap();
                while let Some(v) = lines.next_if(|s| s.starts_with(char::is_whitespace)) {
                    value.push_str(v);
                }

                headers.append(HeaderName::from_str(key).unwrap(), value.trim().to_string());
            }

            return Ok(Some(ServerOp::Message {
                length: reply_to.as_ref().map(|reply| reply.len()).unwrap_or(0)
                    + subject.len()
                    + num_bytes,
                sid,
                reply: reply_to,
                subject,
                headers: Some(headers),
                payload,
                status: maybe_status,
                description: maybe_description,
            }));
        }

        let buffer = self.buffer.split_to(len + 2);
        let line = str::from_utf8(&buffer).map_err(|_| {
            io::Error::new(io::ErrorKind::InvalidInput, "unable to parse unknown input")
        })?;

        Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            format!("invalid server operation: '{line}'"),
        ))
    }

Gets a value for a given key. If key is not found, Option::None is returned.

Examples
let mut headers = async_nats::HeaderMap::new();
headers.append("Key", "Value");
let key = headers.get("Key").unwrap();
Examples found in repository?
src/jetstream/kv/mod.rs (line 247)
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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
    pub async fn entry<T: Into<String>>(&self, key: T) -> Result<Option<Entry>, Error> {
        let key: String = key.into();
        if !is_valid_key(key.as_ref()) {
            return Err(Box::new(io::Error::new(
                io::ErrorKind::InvalidInput,
                "invalid key",
            )));
        }

        let subject = format!("{}{}", self.prefix.as_str(), &key);

        let result: Option<(Message, Operation, u64, OffsetDateTime)> = {
            if self.stream.info.config.allow_direct {
                let message = self
                    .stream
                    .direct_get_last_for_subject(subject.as_str())
                    .await;

                match message {
                    Ok(message) => {
                        let headers = message.headers.as_ref().ok_or_else(|| {
                            std::io::Error::new(io::ErrorKind::Other, "did not found headers")
                        })?;
                        let operation = headers.get(KV_OPERATION).map_or_else(
                            || Operation::Put,
                            |operation| match operation
                                .iter()
                                .next()
                                .cloned()
                                .unwrap_or_else(|| KV_OPERATION_PUT.to_string())
                                .as_ref()
                            {
                                KV_OPERATION_PURGE => Operation::Purge,
                                KV_OPERATION_DELETE => Operation::Delete,
                                _ => Operation::Put,
                            },
                        );
                        let sequence = headers
                            .get(header::NATS_SEQUENCE)
                            .ok_or_else(|| {
                                io::Error::new(
                                    io::ErrorKind::NotFound,
                                    "did not found sequence header",
                                )
                            })?
                            .iter()
                            .next()
                            .ok_or_else(|| {
                                io::Error::new(
                                    io::ErrorKind::NotFound,
                                    "did not found sequence header value",
                                )
                            })?
                            .parse()?;
                        let created = headers
                            .get(header::NATS_TIME_STAMP)
                            .ok_or_else(|| {
                                io::Error::new(
                                    io::ErrorKind::NotFound,
                                    "did not found timestamp header",
                                )
                            })?
                            .iter()
                            .next()
                            .ok_or_else(|| {
                                io::Error::new(
                                    io::ErrorKind::NotFound,
                                    "did not found timestamp header value",
                                )
                            })
                            .and_then(|created| {
                                OffsetDateTime::parse(created, &Rfc3339).map_err(|err| {
                                    std::io::Error::new(
                                        io::ErrorKind::Other,
                                        format!("failed to parse Nats-Time-Stamp: {err}"),
                                    )
                                })
                            })?;

                        Some((message.message, operation, sequence, created))
                    }
                    Err(err) => {
                        let e: std::io::Error = *err.downcast().unwrap();
                        if e.kind() == ErrorKind::NotFound {
                            None
                        } else {
                            return Err(Box::new(e));
                        }
                    }
                }
            } else {
                let raw_message = self
                    .stream
                    .get_last_raw_message_by_subject(subject.as_str())
                    .await;
                match raw_message {
                    Ok(raw_message) => {
                        let operation = kv_operation_from_stream_message(&raw_message);
                        // TODO: unnecessary expensive, cloning whole Message.
                        let nats_message = Message::try_from(raw_message.clone())?;
                        Some((
                            nats_message,
                            operation,
                            raw_message.sequence,
                            raw_message.time,
                        ))
                    }
                    Err(err) => {
                        let e: std::io::Error = *err.downcast().unwrap();
                        let d = e.get_ref().unwrap();
                        let de = d.downcast_ref::<response::Error>().unwrap();
                        // 10037 is returned when there are no messages found.
                        if de.code == 10037 {
                            None
                        } else {
                            return Err(Box::new(e));
                        }
                    }
                }
            }
        };

        match result {
            Some((message, operation, revision, created)) => {
                if message.status == Some(StatusCode::NO_RESPONDERS) {
                    return Ok(None);
                }

                let entry = Entry {
                    bucket: self.name.clone(),
                    key,
                    value: message.payload.to_vec(),
                    revision,
                    created,
                    operation,
                    delta: 0,
                };
                Ok(Some(entry))
            }
            // TODO: remember to touch this when Errors are in place.
            None => Ok(None),
        }
    }

    /// Creates a [futures::Stream] over [Entries][Entry]  a given key in the bucket, which yields
    /// values whenever there are changes for that key.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), async_nats::Error> {
    /// use futures::StreamExt;
    /// let client = async_nats::connect("demo.nats.io:4222").await?;
    /// let jetstream = async_nats::jetstream::new(client);
    /// let kv = jetstream.create_key_value(async_nats::jetstream::kv::Config {
    ///     bucket: "kv".to_string(),
    ///     history: 10,
    ///     ..Default::default()
    /// }).await?;
    /// let mut entries = kv.watch("kv").await?;
    /// while let Some(entry) = entries.next().await {
    ///     println!("entry: {:?}", entry);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn watch<T: AsRef<str>>(&self, key: T) -> Result<Watch<'_>, Error> {
        let subject = format!("{}{}", self.prefix.as_str(), key.as_ref());

        let consumer = self
            .stream
            .create_consumer(super::consumer::push::OrderedConfig {
                deliver_subject: self.stream.context.client.new_inbox(),
                description: Some("kv watch consumer".to_string()),
                filter_subject: subject,
                replay_policy: super::consumer::ReplayPolicy::Instant,
                deliver_policy: DeliverPolicy::New,
                ..Default::default()
            })
            .await?;

        Ok(Watch {
            subscription: consumer.messages().await?,
            prefix: self.prefix.clone(),
            bucket: self.name.clone(),
        })
    }

    /// Creates a [futures::Stream] over [Entries][Entry] for all keys, which yields
    /// values whenever there are changes in the bucket.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), async_nats::Error> {
    /// use futures::StreamExt;
    /// let client = async_nats::connect("demo.nats.io:4222").await?;
    /// let jetstream = async_nats::jetstream::new(client);
    /// let kv = jetstream.create_key_value(async_nats::jetstream::kv::Config {
    ///     bucket: "kv".to_string(),
    ///     history: 10,
    ///     ..Default::default()
    /// }).await?;
    /// let mut entries = kv.watch_all().await?;
    /// while let Some(entry) = entries.next().await {
    ///     println!("entry: {:?}", entry);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn watch_all(&self) -> Result<Watch<'_>, Error> {
        self.watch(ALL_KEYS).await
    }

    pub async fn get<T: Into<String>>(&self, key: T) -> Result<Option<Vec<u8>>, Error> {
        match self.entry(key).await {
            Ok(Some(entry)) => match entry.operation {
                Operation::Put => Ok(Some(entry.value)),
                _ => Ok(None),
            },
            Ok(None) => Ok(None),
            Err(err) => Err(err),
        }
    }

    /// Updates a value for a given key, but only if passed `revision` is the last `revision` in
    /// the bucket.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), async_nats::Error> {
    /// use futures::StreamExt;
    /// let client = async_nats::connect("demo.nats.io:4222").await?;
    /// let jetstream = async_nats::jetstream::new(client);
    /// let kv = jetstream.create_key_value(async_nats::jetstream::kv::Config {
    ///     bucket: "kv".to_string(),
    ///     history: 10,
    ///     ..Default::default()
    /// }).await?;
    /// let revision = kv.put("key", "value".into()).await?;
    /// kv.update("key", "updated".into(), revision).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn update<T: AsRef<str>>(
        &self,
        key: T,
        value: Bytes,
        revision: u64,
    ) -> Result<u64, Error> {
        if !is_valid_key(key.as_ref()) {
            return Err(Box::new(io::Error::new(
                io::ErrorKind::InvalidInput,
                "invalid key",
            )));
        }
        let subject = format!("{}{}", self.prefix.as_str(), key.as_ref());

        let mut headers = crate::HeaderMap::default();
        headers.insert(
            header::NATS_EXPECTED_LAST_SUBJECT_SEQUENCE,
            HeaderValue::from(revision),
        );

        self.stream
            .context
            .publish_with_headers(subject, headers, value)
            .await?
            .await
            .map(|publish_ack| publish_ack.sequence)
    }

    /// Deletes a given key. This is a non-destructive operation, which sets a `DELETE` marker.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), async_nats::Error> {
    /// use futures::StreamExt;
    /// let client = async_nats::connect("demo.nats.io:4222").await?;
    /// let jetstream = async_nats::jetstream::new(client);
    /// let kv = jetstream.create_key_value(async_nats::jetstream::kv::Config {
    ///     bucket: "kv".to_string(),
    ///     history: 10,
    ///     ..Default::default()
    /// }).await?;
    /// kv.put("key", "value".into()).await?;
    /// kv.delete("key").await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn delete<T: AsRef<str>>(&self, key: T) -> Result<(), Error> {
        if !is_valid_key(key.as_ref()) {
            return Err(Box::new(io::Error::new(
                io::ErrorKind::InvalidInput,
                "invalid key",
            )));
        }
        let mut subject = String::new();
        if self.use_jetstream_prefix {
            subject.push_str(&self.stream.context.prefix);
            subject.push('.');
        }
        subject.push_str(self.put_prefix.as_ref().unwrap_or(&self.prefix));
        subject.push_str(key.as_ref());

        let mut headers = crate::HeaderMap::default();
        // TODO: figure out which headers k/v should be where.
        headers.insert(KV_OPERATION, KV_OPERATION_DELETE.parse::<HeaderValue>()?);

        self.stream
            .context
            .publish_with_headers(subject, headers, "".into())
            .await?;
        Ok(())
    }

    /// Purges all the revisions of a entry destructively, leaving behind a single purge entry in-place.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), async_nats::Error> {
    /// use futures::StreamExt;
    /// let client = async_nats::connect("demo.nats.io:4222").await?;
    /// let jetstream = async_nats::jetstream::new(client);
    /// let kv = jetstream.create_key_value(async_nats::jetstream::kv::Config {
    ///     bucket: "kv".to_string(),
    ///     history: 10,
    ///     ..Default::default()
    /// }).await?;
    /// kv.put("key", "value".into()).await?;
    /// kv.put("key", "another".into()).await?;
    /// kv.purge("key").await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn purge<T: AsRef<str>>(&self, key: T) -> Result<(), Error> {
        if !is_valid_key(key.as_ref()) {
            return Err(Box::new(io::Error::new(
                io::ErrorKind::InvalidInput,
                "invalid key",
            )));
        }

        let subject = format!("{}{}", self.prefix.as_str(), key.as_ref());

        let mut headers = crate::HeaderMap::default();
        headers.insert(KV_OPERATION, HeaderValue::from(KV_OPERATION_PURGE));
        headers.insert(NATS_ROLLUP, HeaderValue::from(ROLLUP_SUBJECT));

        self.stream
            .context
            .publish_with_headers(subject, headers, "".into())
            .await?;
        Ok(())
    }

    /// Returns a [futures::Stream] that allows iterating over all [Operations][Operation] that
    /// happen for given key.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), async_nats::Error> {
    /// use futures::StreamExt;
    /// let client = async_nats::connect("demo.nats.io:4222").await?;
    /// let jetstream = async_nats::jetstream::new(client);
    /// let kv = jetstream.create_key_value(async_nats::jetstream::kv::Config {
    ///     bucket: "kv".to_string(),
    ///     history: 10,
    ///     ..Default::default()
    /// }).await?;
    /// let mut entries = kv.history("kv").await?;
    /// while let Some(entry) = entries.next().await {
    ///     println!("entry: {:?}", entry);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn history<T: AsRef<str>>(&self, key: T) -> Result<History<'_>, Error> {
        if !is_valid_key(key.as_ref()) {
            return Err(Box::new(io::Error::new(
                io::ErrorKind::InvalidInput,
                "invalid key",
            )));
        }
        let subject = format!("{}{}", self.prefix.as_str(), key.as_ref());

        let consumer = self
            .stream
            .create_consumer(super::consumer::push::OrderedConfig {
                deliver_subject: self.stream.context.client.new_inbox(),
                description: Some("kv history consumer".to_string()),
                filter_subject: subject,
                replay_policy: super::consumer::ReplayPolicy::Instant,
                ..Default::default()
            })
            .await?;

        Ok(History {
            subscription: consumer.messages().await?,
            done: false,
            prefix: self.prefix.clone(),
            bucket: self.name.clone(),
        })
    }

    /// Returns a [futures::Stream] that allows iterating over all keys in the bucket.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), async_nats::Error> {
    /// use futures::StreamExt;
    /// let client = async_nats::connect("demo.nats.io:4222").await?;
    /// let jetstream = async_nats::jetstream::new(client);
    /// let kv = jetstream.create_key_value(async_nats::jetstream::kv::Config {
    ///     bucket: "kv".to_string(),
    ///     history: 10,
    ///     ..Default::default()
    /// }).await?;
    /// let mut entries = kv.keys().await?;
    /// while let Some(key) = entries.next() {
    ///     println!("key: {:?}", key);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn keys(&self) -> Result<collections::hash_set::IntoIter<String>, Error> {
        let subject = format!("{}>", self.prefix.as_str());

        let consumer = self
            .stream
            .create_consumer(super::consumer::push::OrderedConfig {
                deliver_subject: self.stream.context.client.new_inbox(),
                description: Some("kv history consumer".to_string()),
                filter_subject: subject,
                headers_only: true,
                replay_policy: super::consumer::ReplayPolicy::Instant,
                ..Default::default()
            })
            .await?;

        let mut entries = History {
            done: consumer.info.num_pending == 0,
            subscription: consumer.messages().await?,
            prefix: self.prefix.clone(),
            bucket: self.name.clone(),
        };

        let mut keys = HashSet::new();
        while let Some(entry) = entries.try_next().await? {
            keys.insert(entry.key);
        }
        Ok(keys.into_iter())
    }
}

pub struct Watch<'a> {
    subscription: super::consumer::push::Ordered<'a>,
    prefix: String,
    bucket: String,
}

impl<'a> futures::Stream for Watch<'a> {
    type Item = Result<Entry, Error>;

    fn poll_next(
        mut self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Option<Self::Item>> {
        match self.subscription.poll_next_unpin(cx) {
            Poll::Ready(message) => match message {
                None => Poll::Ready(None),
                Some(message) => {
                    let message = message?;
                    let info = message.info()?;

                    let operation = match message
                        .headers
                        .as_ref()
                        .and_then(|headers| headers.get(KV_OPERATION))
                        .unwrap_or(&HeaderValue::from(KV_OPERATION_PUT))
                        .iter()
                        .next()
                        .unwrap()
                        .as_str()
                    {
                        KV_OPERATION_DELETE => Operation::Delete,
                        KV_OPERATION_PURGE => Operation::Purge,
                        _ => Operation::Put,
                    };

                    let key = message
                        .subject
                        .strip_prefix(&self.prefix)
                        .map(|s| s.to_string())
                        .unwrap();

                    Poll::Ready(Some(Ok(Entry {
                        bucket: self.bucket.clone(),
                        key,
                        value: message.payload.to_vec(),
                        revision: info.stream_sequence,
                        created: info.published,
                        delta: info.pending,
                        operation,
                    })))
                }
            },
            std::task::Poll::Pending => Poll::Pending,
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (0, None)
    }
}

pub struct History<'a> {
    subscription: super::consumer::push::Ordered<'a>,
    done: bool,
    prefix: String,
    bucket: String,
}

impl<'a> futures::Stream for History<'a> {
    type Item = Result<Entry, Error>;

    fn poll_next(
        mut self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Option<Self::Item>> {
        if self.done {
            return Poll::Ready(None);
        }
        match self.subscription.poll_next_unpin(cx) {
            Poll::Ready(message) => match message {
                None => Poll::Ready(None),
                Some(message) => {
                    let message = message?;
                    let info = message.info()?;
                    if info.pending == 0 {
                        self.done = true;
                    }

                    let operation = match message
                        .headers
                        .as_ref()
                        .and_then(|headers| headers.get(KV_OPERATION))
                        .unwrap_or(&HeaderValue::from(KV_OPERATION_PUT))
                        .iter()
                        .next()
                        .unwrap()
                        .as_str()
                    {
                        KV_OPERATION_DELETE => Operation::Delete,
                        KV_OPERATION_PURGE => Operation::Purge,
                        _ => Operation::Put,
                    };

                    let key = message
                        .subject
                        .strip_prefix(&self.prefix)
                        .map(|s| s.to_string())
                        .unwrap();

                    Poll::Ready(Some(Ok(Entry {
                        bucket: self.bucket.clone(),
                        key,
                        value: message.payload.to_vec(),
                        revision: info.stream_sequence,
                        created: info.published,
                        delta: info.pending,
                        operation,
                    })))
                }
            },
            std::task::Poll::Pending => Poll::Pending,
        }
    }
More examples
Hide additional examples
src/jetstream/consumer/pull.rs (line 633)
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
    fn poll_next(
        mut self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Option<Self::Item>> {
        if self.terminated {
            return Poll::Ready(None);
        }
        loop {
            trace!("pending messages: {}", self.pending_messages);
            if (self.pending_messages <= self.batch_config.batch / 2
                || (self.batch_config.max_bytes > 0
                    && self.pending_bytes <= self.batch_config.max_bytes / 2))
                && !self.pending_request
            {
                debug!("pending messages reached threshold to send new fetch request");
                self.request_tx.send(()).unwrap();
                self.pending_request = true;
            }
            if self.heartbeat_handle.is_some() {
                match self.heartbeats_missing.poll_recv(cx) {
                    Poll::Ready(resp) => match resp {
                        Some(()) => {
                            self.terminated = true;
                            trace!("received missing heartbeats notification");
                            return Poll::Ready(Some(Err(Box::new(std::io::Error::new(
                                std::io::ErrorKind::TimedOut,
                                "did not receive idle heartbeat in time",
                            )))));
                        }
                        None => {
                            self.terminated = true;
                            return Poll::Ready(Some(Err(Box::new(std::io::Error::new(
                                std::io::ErrorKind::Other,
                                "unexpected termination of heartbeat checker",
                            )))));
                        }
                    },
                    Poll::Pending => {
                        trace!("pending message from missing heartbeats notification channel");
                    }
                }
            }
            match self.request_result_rx.poll_recv(cx) {
                Poll::Ready(resp) => match resp {
                    Some(resp) => match resp {
                        Ok(reset) => {
                            debug!("request successful, setting pending messages");
                            if reset {
                                self.pending_messages = self.batch_config.batch;
                                self.pending_bytes = self.batch_config.max_bytes;
                            } else {
                                self.pending_messages += self.batch_config.batch;
                                self.pending_bytes += self.batch_config.max_bytes;
                            }
                            self.pending_request = false;
                            continue;
                        }
                        Err(err) => return Poll::Ready(Some(Err(err))),
                    },
                    None => return Poll::Ready(None),
                },
                Poll::Pending => {
                    trace!("pending result");
                }
            }
            trace!("polling subscriber");
            match self.subscriber.receiver.poll_recv(cx) {
                Poll::Ready(maybe_message) => match maybe_message {
                    Some(message) => match message.status.unwrap_or(StatusCode::OK) {
                        StatusCode::TIMEOUT | StatusCode::REQUEST_TERMINATED => {
                            if message.description.as_deref() == Some("Consumer is push based") {
                                return Poll::Ready(Some(Err(Box::new(std::io::Error::new(
                                    std::io::ErrorKind::Other,
                                    format!("{:?}: {:?}", message.status, message.description),
                                )))));
                            }
                            let pending_messages = message
                                .headers
                                .as_ref()
                                .and_then(|headers| headers.get("Nats-Pending-Messages"))
                                .map(|h| h.iter())
                                .and_then(|mut i| i.next())
                                .map(|e| e.parse::<usize>())
                                .unwrap_or(Ok(self.batch_config.batch))?;
                            let pending_bytes = message
                                .headers
                                .as_ref()
                                .and_then(|headers| headers.get("Nats-Pending-Bytes"))
                                .map(|h| h.iter())
                                .and_then(|mut i| i.next())
                                .map(|e| e.parse::<usize>())
                                .unwrap_or(Ok(self.batch_config.max_bytes))?;
                            debug!(
                                "timeout reached. remaining messages: {}, bytes {}",
                                pending_messages, pending_bytes
                            );
                            self.pending_messages =
                                self.pending_messages.saturating_sub(pending_messages);
                            trace!("message bytes len: {}", pending_bytes);
                            self.pending_bytes = self.pending_bytes.saturating_sub(pending_bytes);
                            continue;
                        }

                        StatusCode::IDLE_HEARTBEAT => {
                            debug!("received idle heartbeat");
                            if !self.batch_config.idle_heartbeat.is_zero() {
                                *self.last_seen.lock().unwrap() = Instant::now();
                            }
                            continue;
                        }
                        StatusCode::OK => {
                            trace!("message received");
                            if !self.batch_config.idle_heartbeat.is_zero() {
                                *self.last_seen.lock().unwrap() = Instant::now();
                            }
                            *self.last_seen.lock().unwrap() = Instant::now();
                            self.pending_messages = self.pending_messages.saturating_sub(1);
                            self.pending_bytes = self.pending_bytes.saturating_sub(message.length);
                            return Poll::Ready(Some(Ok(jetstream::Message {
                                context: self.context.clone(),
                                message,
                            })));
                        }
                        status => {
                            return Poll::Ready(Some(Err(Box::new(std::io::Error::new(
                                std::io::ErrorKind::Other,
                                format!(
                                    "error while processing messages from the stream: {}, {:?}",
                                    status, message.description
                                ),
                            )))))
                        }
                    },
                    None => return Poll::Ready(None),
                },
                Poll::Pending => {
                    debug!("subscriber still pending");
                    return std::task::Poll::Pending;
                }
            }
        }
    }
src/jetstream/consumer/push.rs (line 535)
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
    fn poll_next(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Option<Self::Item>> {
        loop {
            match self.shutdown.try_recv() {
                Ok(err) => return Poll::Ready(Some(Err(err))),
                Err(TryRecvError::Closed) => {
                    return Poll::Ready(Some(Err(Box::from(io::Error::new(
                        ErrorKind::Other,
                        "push consumer task closed",
                    )))))
                }
                Err(TryRecvError::Empty) => {}
            }
            if self.subscriber.is_none() {
                match self.subscriber_future.as_mut() {
                    None => {
                        let context = self.context.clone();
                        let sequence = self.stream_sequence.clone();
                        let config = self.consumer.config.clone();
                        let stream_name = self.consumer.info.stream_name.clone();
                        self.subscriber_future = Some(Box::pin(async move {
                            recreate_consumer_and_subscription(
                                context,
                                config,
                                stream_name,
                                sequence.load(Ordering::Relaxed),
                            )
                            .await
                        }));
                        match self.subscriber_future.as_mut().unwrap().as_mut().poll(cx) {
                            Poll::Ready(subscriber) => {
                                self.subscriber_future = None;
                                self.subscriber = Some(subscriber?);
                            }
                            Poll::Pending => {
                                return Poll::Pending;
                            }
                        }
                    }
                    Some(subscriber) => match subscriber.as_mut().poll(cx) {
                        Poll::Ready(subscriber) => {
                            self.subscriber_future = None;
                            self.consumer_sequence.store(0, Ordering::Relaxed);
                            self.subscriber = Some(subscriber?);
                        }
                        Poll::Pending => {
                            return Poll::Pending;
                        }
                    },
                }
            }
            if let Some(subscriber) = self.subscriber.as_mut() {
                match subscriber.receiver.poll_recv(cx) {
                    Poll::Ready(maybe_message) => {
                        match maybe_message {
                            Some(message) => {
                                *self.last_seen.lock().unwrap() = Instant::now();
                                match message.status {
                                    Some(StatusCode::IDLE_HEARTBEAT) => {
                                        debug!("received idle heartbeats");
                                        if let Some(headers) = message.headers.as_ref() {
                                            if let Some(sequence) =
                                                headers.get(crate::header::NATS_LAST_STREAM)
                                            {
                                                let sequence: u64 = sequence
                                                    .iter().next().unwrap()
                                                    .parse()
                                                    .map_err(|err|
                                                           Box::new(io::Error::new(
                                                                   ErrorKind::Other,
                                                                   format!("could not parse header into u64: {err}"))
                                                               ))?;

                                                if sequence
                                                    != self.stream_sequence.load(Ordering::Relaxed)
                                                {
                                                    self.subscriber = None;
                                                }
                                            }
                                        }
                                        if let Some(subject) = message.reply {
                                            // TODO store pending_publish as a future and return errors from it
                                            let client = self.context.client.clone();
                                            tokio::task::spawn(async move {
                                                client
                                                    .publish(subject, Bytes::from_static(b""))
                                                    .await
                                                    .unwrap();
                                            });
                                        }
                                        continue;
                                    }
                                    Some(_) => {
                                        continue;
                                    }
                                    None => {
                                        let jetstream_message = jetstream::message::Message {
                                            message,
                                            context: self.context.clone(),
                                        };

                                        let info = jetstream_message.info()?;
                                        trace!("consumer sequence: {:?}, stream sequence {:?}, consumer sequence in message: {:?} stream sequence in message: {:?}",
                                               self.consumer_sequence,
                                               self.stream_sequence,
                                               info.consumer_sequence,
                                               info.stream_sequence);
                                        if info.consumer_sequence
                                            != self.consumer_sequence.load(Ordering::Relaxed) + 1
                                            && info.stream_sequence
                                                != self.stream_sequence.load(Ordering::Relaxed) + 1
                                        {
                                            debug!(
                                                "ordered consumer mismatch. current {}, info: {}",
                                                self.consumer_sequence.load(Ordering::Relaxed),
                                                info.consumer_sequence
                                            );
                                            self.subscriber = None;
                                            continue;
                                        }
                                        self.stream_sequence
                                            .store(info.stream_sequence, Ordering::Relaxed);
                                        self.consumer_sequence
                                            .store(info.consumer_sequence, Ordering::Relaxed);
                                        return Poll::Ready(Some(Ok(jetstream_message)));
                                    }
                                }
                            }
                            None => {
                                debug!("received None from subscription");
                                return Poll::Ready(None);
                            }
                        }
                    }
                    Poll::Pending => return Poll::Pending,
                }
            }
        }
    }

Trait Implementations§

Returns a copy of the value. Read more
Performs copy-assignment from source. Read more
Formats the value using the given formatter. Read more
Returns the “default value” for a type. Read more
Creates a value from an iterator. Read more
This method tests for self and other values to be equal, and is used by ==.
This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Instruments this type with the current Span, returning an Instrumented wrapper. Read more

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Should always be Self
The resulting type after obtaining ownership.
Creates owned data from borrowed data, usually by cloning. Read more
Uses borrowed data to replace owned data, usually by cloning. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.
Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more