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
use std::{
fmt, io,
sync::atomic::{AtomicBool, Ordering},
};
use crate::{client::Client, Headers};
pub struct Message {
pub subject: String,
pub reply: Option<String>,
pub data: Vec<u8>,
pub headers: Option<Headers>,
#[doc(hidden)]
pub client: Client,
#[doc(hidden)]
pub double_acked: AtomicBool,
}
impl Clone for Message {
fn clone(&self) -> Message {
Message {
subject: self.subject.clone(),
reply: self.reply.clone(),
data: self.data.clone(),
headers: self.headers.clone(),
client: self.client.clone(),
double_acked: AtomicBool::new(
self.double_acked.load(Ordering::Acquire),
),
}
}
}
impl Message {
pub fn respond(&self, msg: impl AsRef<[u8]>) -> io::Result<()> {
match self.reply.as_ref() {
None => Err(io::Error::new(
io::ErrorKind::InvalidInput,
"no reply subject available",
)),
Some(reply) => self.client.publish(reply, None, None, msg.as_ref()),
}
}
#[cfg(feature = "jetstream")]
pub fn ack(&self) -> io::Result<()> {
if self.double_acked.load(Ordering::Acquire) {
return Ok(());
}
self.respond(b"")
}
#[cfg(feature = "jetstream")]
pub fn ack_kind(
&self,
ack_kind: crate::jetstream::AckKind,
) -> io::Result<()> {
self.respond(ack_kind)
}
#[cfg(feature = "jetstream")]
pub fn double_ack(
&self,
ack_kind: crate::jetstream::AckKind,
) -> io::Result<()> {
if self.double_acked.load(Ordering::Acquire) {
return Ok(());
}
let original_reply = match self.reply.as_ref() {
None => {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"No reply subject available (not a JetStream message)",
))
}
Some(original_reply) => original_reply,
};
let mut retries = 0;
loop {
retries += 1;
if retries == 2 {
log::warn!("double_ack is retrying until the server connection is reestablished");
}
let ack_reply = format!("_INBOX.{}", nuid::next());
let sub_ret = self.client.subscribe(&ack_reply, None);
if sub_ret.is_err() {
std::thread::sleep(std::time::Duration::from_millis(100));
continue;
}
let (sid, receiver) = sub_ret?;
let sub = crate::Subscription::new(
sid,
ack_reply.to_string(),
receiver,
self.client.clone(),
);
let pub_ret = self.client.publish(
original_reply,
Some(&ack_reply),
None,
ack_kind.as_ref(),
);
if pub_ret.is_err() {
std::thread::sleep(std::time::Duration::from_millis(100));
continue;
}
if sub
.next_timeout(std::time::Duration::from_millis(100))
.is_ok()
{
self.double_acked.store(true, Ordering::Release);
return Ok(());
}
}
}
#[cfg(feature = "jetstream")]
pub fn jetstream_message_info(
&self,
) -> Option<crate::jetstream::JetStreamMessageInfo<'_>> {
let reply = self.reply.as_ref()?;
let mut split = reply.split('.');
if split.next()? != "$JS" || split.next()? != "ACK" {
return None;
}
Some(crate::jetstream::JetStreamMessageInfo {
stream: split.next()?,
consumer: split.next()?,
delivered: str::parse(split.next()?).ok()?,
stream_seq: str::parse(split.next()?).ok()?,
consumer_seq: str::parse(split.next()?).ok()?,
published: {
let nanos: u64 = str::parse(split.next()?).ok()?;
let offset = std::time::Duration::from_nanos(nanos);
std::time::UNIX_EPOCH + offset
},
pending: str::parse(split.next()?).ok()?,
})
}
}
impl fmt::Debug for Message {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
f.debug_struct("Message")
.field("subject", &self.subject)
.field("headers", &self.headers)
.field("reply", &self.reply)
.field("length", &self.data.len())
.finish()
}
}
impl fmt::Display for Message {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut body = format!("[{} bytes]", self.data.len());
if let Ok(str) = std::str::from_utf8(&self.data) {
body = str.to_string();
}
if let Some(reply) = &self.reply {
write!(
f,
"Message {{\n subject: \"{}\",\n reply: \"{}\",\n data: \
\"{}\"\n}}",
self.subject, reply, body
)
} else {
write!(
f,
"Message {{\n subject: \"{}\",\n data: \"{}\"\n}}",
self.subject, body
)
}
}
}