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
//! Streaming HTTP client for pushing unified JSONL to a RustGraph ingest endpoint.
//!
//! Implements `std::io::Write` so it can be passed directly to
//! `RustGraphUnifiedExporter::export_to_writer`. Buffers JSONL lines in memory
//! and auto-flushes when batch size is reached.
use std::io::{self, Write};
use std::time::Duration;
use reqwest::blocking::Client;
use tracing::{debug, warn};
/// Configuration for the streaming client.
#[derive(Debug, Clone)]
pub struct StreamConfig {
/// Target URL for the RustGraph ingest endpoint.
pub target_url: String,
/// Number of JSONL lines per HTTP POST batch.
pub batch_size: usize,
/// HTTP request timeout in seconds.
pub timeout_secs: u64,
/// Optional API key for authentication.
pub api_key: Option<String>,
/// Maximum number of retries per batch.
pub max_retries: u32,
}
impl Default for StreamConfig {
fn default() -> Self {
Self {
target_url: String::new(),
batch_size: 1000,
timeout_secs: 30,
api_key: None,
max_retries: 3,
}
}
}
/// HTTP streaming client that implements `Write` for JSONL output.
///
/// Each complete line (terminated by `\n`) is buffered. When the buffer
/// reaches `batch_size` lines, the batch is POSTed to the target URL.
pub struct StreamClient {
config: StreamConfig,
client: Client,
/// Buffer of complete JSONL lines ready to send.
lines: Vec<String>,
/// Partial line buffer (data received without trailing newline).
partial: String,
/// Total lines sent.
total_sent: usize,
}
impl StreamClient {
/// Create a new streaming client with the given configuration.
pub fn new(config: StreamConfig) -> io::Result<Self> {
let client = Client::builder()
.timeout(Duration::from_secs(config.timeout_secs))
.build()
.map_err(io::Error::other)?;
Ok(Self {
config,
client,
lines: Vec::new(),
partial: String::new(),
total_sent: 0,
})
}
/// Returns the total number of lines sent so far.
pub fn total_sent(&self) -> usize {
self.total_sent
}
/// Send a batch of lines to the target endpoint.
fn send_batch(&mut self) -> io::Result<()> {
if self.lines.is_empty() {
return Ok(());
}
let payload = self.lines.join("");
let batch_len = self.lines.len();
for attempt in 0..=self.config.max_retries {
let mut request = self
.client
.post(&self.config.target_url)
.header("Content-Type", "application/x-ndjson")
.body(payload.clone());
if let Some(ref key) = self.config.api_key {
request = request.header("X-API-Key", key);
}
match request.send() {
Ok(response) if response.status().is_success() => {
debug!(
"Streamed batch of {} lines (total: {})",
batch_len,
self.total_sent + batch_len
);
self.total_sent += batch_len;
self.lines.clear();
return Ok(());
}
Ok(response) => {
let status = response.status();
if attempt < self.config.max_retries {
warn!(
"Stream batch failed (HTTP {}), retry {}/{}",
status,
attempt + 1,
self.config.max_retries
);
std::thread::sleep(Duration::from_millis(500 * (attempt as u64 + 1)));
} else {
return Err(io::Error::other(format!(
"Stream batch failed after {} retries (HTTP {})",
self.config.max_retries, status
)));
}
}
Err(e) => {
if attempt < self.config.max_retries {
warn!(
"Stream batch error: {}, retry {}/{}",
e,
attempt + 1,
self.config.max_retries
);
std::thread::sleep(Duration::from_millis(500 * (attempt as u64 + 1)));
} else {
return Err(io::Error::other(format!(
"Stream batch failed after {} retries: {}",
self.config.max_retries, e
)));
}
}
}
}
Ok(())
}
}
impl Write for StreamClient {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
let s =
std::str::from_utf8(buf).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
self.partial.push_str(s);
// Split on newlines and buffer complete lines
while let Some(pos) = self.partial.find('\n') {
let line = self.partial[..=pos].to_string();
self.partial = self.partial[pos + 1..].to_string();
self.lines.push(line);
// Auto-flush when batch size reached
if self.lines.len() >= self.config.batch_size {
self.send_batch()?;
}
}
Ok(buf.len())
}
fn flush(&mut self) -> io::Result<()> {
// If there's a partial line remaining, treat it as a complete line
if !self.partial.is_empty() {
let mut line = std::mem::take(&mut self.partial);
if !line.ends_with('\n') {
line.push('\n');
}
self.lines.push(line);
}
// Send any remaining buffered lines
self.send_batch()
}
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
use super::*;
#[test]
fn test_stream_config_default() {
let config = StreamConfig::default();
assert_eq!(config.batch_size, 1000);
assert_eq!(config.timeout_secs, 30);
assert_eq!(config.max_retries, 3);
assert!(config.api_key.is_none());
}
#[test]
fn test_line_buffering() {
// We can't easily test HTTP posting without a server, but we can
// test the line buffering logic by using a large batch_size so
// no actual sends happen.
let config = StreamConfig {
target_url: "http://localhost:9999/ingest".to_string(),
batch_size: 10000, // Large so no auto-flush
..Default::default()
};
let mut client = StreamClient::new(config).unwrap();
// Write some JSONL
client
.write_all(b"{\"_type\":\"node\",\"id\":\"1\"}\n")
.unwrap();
client
.write_all(b"{\"_type\":\"node\",\"id\":\"2\"}\n")
.unwrap();
assert_eq!(client.lines.len(), 2);
assert!(client.partial.is_empty());
assert_eq!(client.total_sent, 0);
}
#[test]
fn test_partial_line_handling() {
let config = StreamConfig {
target_url: "http://localhost:9999/ingest".to_string(),
batch_size: 10000,
..Default::default()
};
let mut client = StreamClient::new(config).unwrap();
// Write partial line
client.write_all(b"{\"_type\":\"node\"").unwrap();
assert_eq!(client.lines.len(), 0);
assert_eq!(client.partial, "{\"_type\":\"node\"");
// Complete the line
client.write_all(b",\"id\":\"1\"}\n").unwrap();
assert_eq!(client.lines.len(), 1);
assert!(client.partial.is_empty());
}
}