1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
use crate::runtime::{InternalMessage, InternalMessageState, MessageStatus};
use crate::{Error, Output, OutputBatch, SHUTDOWN_MESSAGE_ID};
use flume::{Receiver, Sender};
use std::time::Duration;
use tokio::time::{timeout, Instant};
use tracing::{debug, error, trace};
#[cfg(feature = "amqp")]
pub mod amqp;
#[cfg(feature = "clickhouse")]
pub mod clickhouse;
pub mod drop;
#[cfg(feature = "elasticsearch")]
pub mod elasticsearch;
#[cfg(feature = "http_client")]
pub mod http;
#[cfg(feature = "mqtt")]
pub mod mqtt;
#[cfg(feature = "redis")]
pub mod redis;
pub mod stdout;
pub mod switch;
#[cfg(feature = "zeromq")]
pub mod zeromq;
pub(crate) fn register_plugins() -> Result<(), Error> {
drop::register_drop()?;
#[cfg(feature = "elasticsearch")]
elasticsearch::register_elasticsearch()?;
#[cfg(feature = "clickhouse")]
clickhouse::register_clickhouse()?;
#[cfg(feature = "http_client")]
http::register_http()?;
#[cfg(feature = "redis")]
redis::register_redis()?;
#[cfg(feature = "mqtt")]
mqtt::register_mqtt()?;
#[cfg(feature = "zeromq")]
zeromq::register_zeromq()?;
#[cfg(feature = "amqp")]
amqp::register_amqp()?;
stdout::register_stdout()?;
switch::register_switch()?;
Ok(())
}
pub(crate) async fn run_output(
input: Receiver<InternalMessage>,
state: Sender<InternalMessageState>,
mut o: Box<dyn Output + Send + Sync>,
retry_policy: Option<crate::RetryPolicy>,
) -> Result<(), Error> {
debug!("output connected");
loop {
match input.recv_async().await {
Ok(msg) => {
trace!("received output message");
let stream_id = msg.message.stream_id.clone();
let message_id = msg.message_id;
let output_bytes = msg.message.bytes.len() as u64;
let max_attempts = retry_policy.as_ref().map_or(1, |r| r.max_retries + 1);
let mut last_error = None;
for attempt in 0..max_attempts {
let msg_clone = msg.message.clone();
match o.write(msg_clone).await {
Ok(_) => {
trace!("sending message");
state
.send_async(InternalMessageState {
message_id: message_id.clone(),
status: MessageStatus::Output,
stream_id: stream_id.clone(),
is_stream: false,
bytes: output_bytes,
})
.await
.map_err(|e| Error::UnableToSendToChannel(format!("{e}")))?;
last_error = None;
break;
}
Err(e) => match e {
Error::ConditionalCheckfailed => {
debug!("conditional check failed for output");
last_error = None;
break;
}
Error::UnRetryable(ref msg) => {
debug!(error = %msg, "unretryable output error");
state
.send_async(InternalMessageState {
message_id: message_id.clone(),
status: MessageStatus::OutputError(format!("{e}")),
stream_id: stream_id.clone(),
is_stream: false,
bytes: 0,
})
.await
.map_err(|e| Error::UnableToSendToChannel(format!("{e}")))?;
last_error = None;
break;
}
_ => {
if attempt + 1 < max_attempts {
let wait = retry_policy
.as_ref()
.map_or(Duration::from_secs(1), |rp| {
rp.compute_wait(attempt)
});
tracing::warn!(
attempt = attempt + 1,
max_retries = max_attempts - 1,
wait_ms = wait.as_millis() as u64,
error = %e,
"output write failed, retrying"
);
state
.send_async(InternalMessageState {
message_id: message_id.clone(),
status: MessageStatus::Retry,
stream_id: stream_id.clone(),
is_stream: false,
bytes: 0,
})
.await
.map_err(|e| {
Error::UnableToSendToChannel(format!("{e}"))
})?;
tokio::time::sleep(wait).await;
} else {
last_error = Some(e);
}
}
},
}
}
if let Some(e) = last_error {
tracing::error!(
attempts = max_attempts,
error = %e,
"output write failed after all retries"
);
state
.send_async(InternalMessageState {
message_id: message_id.clone(),
status: MessageStatus::RetriesExhausted,
stream_id: stream_id.clone(),
is_stream: false,
bytes: 0,
})
.await
.map_err(|e| Error::UnableToSendToChannel(format!("{e}")))?;
state
.send_async(InternalMessageState {
message_id,
status: MessageStatus::OutputError(format!("{e}")),
stream_id,
is_stream: false,
bytes: 0,
})
.await
.map_err(|e| Error::UnableToSendToChannel(format!("{e}")))?;
}
}
Err(_) => {
// Channel disconnected - clean shutdown
o.close().await?;
debug!("output closed");
state
.send_async(InternalMessageState {
message_id: SHUTDOWN_MESSAGE_ID.into(),
status: MessageStatus::Shutdown,
..Default::default()
})
.await
.map_err(|e| Error::UnableToSendToChannel(format!("{e}")))?;
return Ok(());
}
}
}
}
pub(crate) async fn run_output_batch(
input: Receiver<InternalMessage>,
state: Sender<InternalMessageState>,
mut o: Box<dyn OutputBatch + Send + Sync>,
retry_policy: Option<crate::RetryPolicy>,
) -> Result<(), Error> {
debug!("output connected");
let batch_size = o.batch_size().await;
let interval = o.interval().await;
let max_batch_bytes = o.max_batch_bytes().await;
loop {
let deadline = Instant::now() + interval;
let mut internal_msg_batch: Vec<InternalMessage> = Vec::with_capacity(batch_size);
let mut batch_bytes: usize = 0;
// Collect messages until batch is full, byte limit reached, or timeout
while internal_msg_batch.len() < batch_size {
let remaining = deadline.saturating_duration_since(Instant::now());
if remaining.is_zero() {
break;
}
match timeout(remaining, input.recv_async()).await {
Ok(Ok(msg)) => {
let msg_bytes = msg.message.bytes.len();
// Estimate total serialized size including minimal JSON
// array framing: [] brackets (2 bytes) + commas between
// items (count - 1 bytes after adding this message).
let new_count = internal_msg_batch.len() + 1;
let estimated_total = batch_bytes + msg_bytes + 2 + new_count.saturating_sub(1);
// If adding this message would exceed the byte limit and we
// already have messages, flush current batch first.
// A single message larger than the limit is always accepted
// (batch of 1) so we don't drop oversized messages.
if max_batch_bytes > 0
&& estimated_total > max_batch_bytes
&& !internal_msg_batch.is_empty()
{
process_batch(&mut o, &state, internal_msg_batch, &retry_policy).await?;
internal_msg_batch = Vec::with_capacity(batch_size);
batch_bytes = 0;
}
batch_bytes += msg_bytes;
internal_msg_batch.push(msg);
}
Ok(Err(_)) => {
// Channel disconnected - process remaining batch and exit
if !internal_msg_batch.is_empty() {
process_batch(&mut o, &state, internal_msg_batch, &retry_policy).await?;
}
o.close().await?;
match state
.send_async(InternalMessageState {
message_id: SHUTDOWN_MESSAGE_ID.into(),
status: MessageStatus::Shutdown,
..Default::default()
})
.await
{
Ok(_) => debug!("exited successfully"),
Err(e) => error!("unable to exit {e}"),
}
return Ok(());
}
Err(_) => break, // Timeout reached
}
}
if !internal_msg_batch.is_empty() {
process_batch(&mut o, &state, internal_msg_batch, &retry_policy).await?;
}
}
}
/// Helper function to process a batch of messages
async fn process_batch(
o: &mut Box<dyn OutputBatch + Send + Sync>,
state: &Sender<InternalMessageState>,
internal_msg_batch: Vec<InternalMessage>,
retry_policy: &Option<crate::RetryPolicy>,
) -> Result<(), Error> {
let metadata: Vec<(String, Option<String>, u64)> = internal_msg_batch
.iter()
.map(|i| {
(
i.message_id.clone(),
i.message.stream_id.clone(),
i.message.bytes.len() as u64,
)
})
.collect();
let max_attempts = retry_policy.as_ref().map_or(1, |r| r.max_retries + 1);
let mut last_error = None;
for attempt in 0..max_attempts {
let msg_batch: Vec<crate::Message> = internal_msg_batch
.iter()
.map(|i| i.message.clone())
.collect();
match o.write_batch(msg_batch).await {
Ok(_) => {
for (message_id, stream_id, bytes) in &metadata {
state
.send_async(InternalMessageState {
message_id: message_id.clone(),
status: MessageStatus::Output,
stream_id: stream_id.clone(),
is_stream: false,
bytes: *bytes,
})
.await
.map_err(|e| Error::UnableToSendToChannel(format!("{e}")))?;
}
last_error = None;
break;
}
Err(e) => match e {
Error::ConditionalCheckfailed => {
debug!("conditional check failed for output");
last_error = None;
break;
}
Error::UnRetryable(ref msg) => {
debug!(error = %msg, "unretryable batch output error");
for (message_id, stream_id, _bytes) in &metadata {
state
.send_async(InternalMessageState {
message_id: message_id.clone(),
status: MessageStatus::OutputError(format!("{e}")),
stream_id: stream_id.clone(),
is_stream: false,
bytes: 0,
})
.await
.map_err(|e| Error::UnableToSendToChannel(format!("{e}")))?;
}
last_error = None;
break;
}
_ => {
if attempt + 1 < max_attempts {
let wait = retry_policy
.as_ref()
.map_or(Duration::from_secs(1), |rp| rp.compute_wait(attempt));
tracing::warn!(
attempt = attempt + 1,
max_retries = max_attempts - 1,
batch_size = metadata.len(),
wait_ms = wait.as_millis() as u64,
error = %e,
"batch output write failed, retrying"
);
state
.send_async(InternalMessageState {
message_id: String::new(),
status: MessageStatus::Retry,
..Default::default()
})
.await
.map_err(|e| Error::UnableToSendToChannel(format!("{e}")))?;
tokio::time::sleep(wait).await;
} else {
last_error = Some(e);
}
}
},
}
}
if let Some(e) = last_error {
tracing::error!(
attempts = max_attempts,
batch_size = metadata.len(),
error = %e,
"batch output write failed after all retries"
);
state
.send_async(InternalMessageState {
message_id: String::new(),
status: MessageStatus::RetriesExhausted,
..Default::default()
})
.await
.map_err(|e| Error::UnableToSendToChannel(format!("{e}")))?;
for (message_id, stream_id, _bytes) in &metadata {
state
.send_async(InternalMessageState {
message_id: message_id.clone(),
status: MessageStatus::OutputError(format!("{e}")),
stream_id: stream_id.clone(),
is_stream: false,
bytes: 0,
})
.await
.map_err(|e| Error::UnableToSendToChannel(format!("{e}")))?;
}
}
Ok(())
}