velesdb_server/handlers/points/
streaming.rs1use axum::{
4 body::Body,
5 extract::{Path, State},
6 http::StatusCode,
7 response::IntoResponse,
8 Json,
9};
10use futures::StreamExt;
11use std::sync::Arc;
12use std::time::{Duration, Instant};
13
14use crate::types::{EnableStreamingRequest, ErrorResponse, StreamInsertRequest};
15use crate::AppState;
16use velesdb_core::{BackpressureError, Point, VectorCollection};
17
18use crate::handlers::helpers::{error_response, get_vector_collection_or_404};
19
20const STREAM_BATCH_SIZE: usize = 100;
21const STREAM_BATCH_MAX_WAIT: Duration = Duration::from_millis(100);
22
23#[derive(Default)]
25struct StreamUpsertStats {
26 inserted: usize,
27 malformed: usize,
28 failed_upserts: usize,
29 network_errors: u64,
35}
36
37fn parse_ndjson_line(
38 line: &str,
39 batch: &mut Vec<Point>,
40 stats: &mut StreamUpsertStats,
41 point_id_hint: Option<u64>,
42) {
43 if line.is_empty() {
44 return;
45 }
46
47 match serde_json::from_str::<Point>(line) {
48 Ok(point) => batch.push(point),
49 Err(error) => {
50 stats.malformed += 1;
51 if let Some(id) = point_id_hint {
53 tracing::warn!(
54 error = %error,
55 point_id = id,
56 "Skipping malformed NDJSON point"
57 );
58 } else {
59 tracing::warn!(error = %error, "Skipping malformed NDJSON point");
60 }
61 }
62 }
63}
64
65async fn flush_point_batch_with_delta(
68 collection: &VectorCollection,
69 batch: &mut Vec<Point>,
70 stats: &mut StreamUpsertStats,
71) {
72 if batch.is_empty() {
73 return;
74 }
75
76 let points = std::mem::take(batch);
77 let batch_size = points.len();
78
79 #[cfg(feature = "persistence")]
82 let delta_entries: Vec<(u64, Vec<f32>)> = if collection.is_delta_active() {
83 points.iter().map(|p| (p.id, p.vector.clone())).collect()
84 } else {
85 Vec::new()
86 };
87
88 let coll = collection.clone();
89 match tokio::task::spawn_blocking(move || coll.upsert_bulk(&points)).await {
90 Ok(Ok(inserted)) => {
91 stats.inserted += inserted;
92
93 #[cfg(feature = "persistence")]
96 if !delta_entries.is_empty() {
97 collection.push_to_delta_if_active(&delta_entries);
98 }
99 }
100 Ok(Err(error)) => {
101 stats.failed_upserts += batch_size;
102 tracing::error!(
103 error = %error,
104 batch_size,
105 "Failed to upsert streamed batch"
106 );
107 }
108 Err(error) => {
109 stats.failed_upserts += batch_size;
110 tracing::error!(
111 error = %error,
112 batch_size,
113 "Stream upsert batch task panicked"
114 );
115 }
116 }
117}
118
119#[utoipa::path(
128 post,
129 path = "/collections/{name}/points/stream",
130 tag = "points",
131 params(
132 ("name" = String, Path, description = "Collection name")
133 ),
134 request_body(content = String, content_type = "application/x-ndjson", description = "NDJSON stream with one point per line"),
135 responses(
136 (status = 200, description = "Stream processed", body = Object),
137 (status = 404, description = "Collection not found", body = ErrorResponse)
138 )
139)]
140pub async fn stream_upsert_points(
141 State(state): State<Arc<AppState>>,
142 Path(name): Path<String>,
143 body: Body,
144) -> impl IntoResponse {
145 let collection = match get_vector_collection_or_404(&state, &name) {
146 Ok(c) => c,
147 Err(resp) => return resp,
148 };
149
150 let stats = process_ndjson_stream(&collection, body).await;
151
152 if stats.inserted > 0 {
153 #[allow(deprecated)]
158 state.db.notify_upsert(&name, stats.inserted);
159 }
160
161 Json(serde_json::json!({
162 "message": "Stream processed",
163 "inserted": stats.inserted,
164 "malformed": stats.malformed,
165 "failed_upserts": stats.failed_upserts,
166 "network_errors": stats.network_errors
167 }))
168 .into_response()
169}
170
171fn extract_id_hint(line: &str) -> Option<u64> {
173 serde_json::from_str::<serde_json::Value>(line)
174 .ok()
175 .and_then(|v| v.get("id").and_then(|id| id.as_u64()))
176}
177
178async fn process_ndjson_stream(collection: &VectorCollection, body: Body) -> StreamUpsertStats {
180 let mut stream = body.into_data_stream();
181 let mut buffer = Vec::<u8>::new();
182 let mut batch = Vec::with_capacity(STREAM_BATCH_SIZE);
183 let mut stats = StreamUpsertStats::default();
184 let mut last_flush = Instant::now();
185
186 while let Some(chunk_result) = stream.next().await {
187 match chunk_result {
188 Ok(chunk) => {
189 buffer.extend_from_slice(&chunk);
190 process_buffer_lines(&mut buffer, &mut batch, &mut stats);
191 if should_flush(&batch, last_flush) {
192 flush_point_batch_with_delta(collection, &mut batch, &mut stats).await;
193 last_flush = Instant::now();
194 }
195 }
196 Err(error) => {
197 stats.network_errors += 1;
198 tracing::warn!(error = %error, "Error while reading request body stream");
199 }
200 }
201 }
202
203 if !buffer.is_empty() {
205 let line = String::from_utf8_lossy(&buffer);
206 let id_hint = extract_id_hint(line.trim());
207 parse_ndjson_line(line.trim(), &mut batch, &mut stats, id_hint);
208 }
209
210 flush_point_batch_with_delta(collection, &mut batch, &mut stats).await;
211 stats
212}
213
214fn process_buffer_lines(
216 buffer: &mut Vec<u8>,
217 batch: &mut Vec<Point>,
218 stats: &mut StreamUpsertStats,
219) {
220 while let Some(newline_pos) = buffer.iter().position(|byte| *byte == b'\n') {
221 let line_bytes: Vec<u8> = buffer.drain(..=newline_pos).collect();
222 let line = String::from_utf8_lossy(&line_bytes);
223 let id_hint = extract_id_hint(line.trim());
224 parse_ndjson_line(line.trim(), batch, stats, id_hint);
225 }
226}
227
228fn should_flush(batch: &[Point], last_flush: Instant) -> bool {
230 batch.len() >= STREAM_BATCH_SIZE
231 || (!batch.is_empty() && last_flush.elapsed() >= STREAM_BATCH_MAX_WAIT)
232}
233
234#[utoipa::path(
243 post,
244 path = "/collections/{name}/stream/insert",
245 tag = "points",
246 params(
247 ("name" = String, Path, description = "Collection name")
248 ),
249 request_body = StreamInsertRequest,
250 responses(
251 (status = 202, description = "Point accepted into streaming buffer"),
252 (status = 429, description = "Streaming buffer full — retry after 1 second", body = ErrorResponse),
253 (status = 503, description = "Streaming drain task has exited — collection must be reconfigured", body = ErrorResponse),
254 (status = 404, description = "Collection not found", body = ErrorResponse),
255 (status = 409, description = "Streaming not configured", body = ErrorResponse)
256 )
257)]
258pub async fn stream_insert(
259 State(state): State<Arc<AppState>>,
260 Path(name): Path<String>,
261 Json(req): Json<StreamInsertRequest>,
262) -> impl IntoResponse {
263 let collection = match get_vector_collection_or_404(&state, &name) {
264 Ok(c) => c,
265 Err(resp) => return resp,
266 };
267
268 if let Err(resp) = validate_stream_dimension(&collection, &req) {
269 return resp;
270 }
271
272 let point = Point::new(req.id, req.vector, req.payload);
273 stream_insert_result_to_response(collection.stream_insert(point))
274}
275
276#[allow(clippy::result_large_err)]
278fn validate_stream_dimension(
279 collection: &VectorCollection,
280 req: &StreamInsertRequest,
281) -> Result<(), axum::response::Response> {
282 let expected_dim = collection.dimension();
283 if req.vector.len() != expected_dim {
284 return Err(error_response(
285 StatusCode::BAD_REQUEST,
286 format!(
287 "Vector dimension mismatch: collection expects {expected_dim}, got {}",
288 req.vector.len()
289 ),
290 ));
291 }
292 Ok(())
293}
294
295fn stream_insert_result_to_response(
297 result: Result<(), BackpressureError>,
298) -> axum::response::Response {
299 match result {
300 Ok(()) => StatusCode::ACCEPTED.into_response(),
301 Err(BackpressureError::BufferFull) => {
302 let mut headers = axum::http::HeaderMap::new();
303 headers.insert("Retry-After", axum::http::HeaderValue::from_static("1"));
304 (
305 StatusCode::TOO_MANY_REQUESTS,
306 headers,
307 Json(ErrorResponse {
308 error: "Stream buffer full, retry after 1s".to_string(),
309 code: None,
310 }),
311 )
312 .into_response()
313 }
314 Err(BackpressureError::DrainTaskDead) => error_response(
315 StatusCode::SERVICE_UNAVAILABLE,
316 "Streaming drain task has exited; the collection must be reconfigured".to_string(),
317 ),
318 Err(BackpressureError::NotConfigured) => error_response(
319 StatusCode::CONFLICT,
320 "Streaming not configured for this collection".to_string(),
321 ),
322 Err(e) => error_response(
323 StatusCode::INTERNAL_SERVER_ERROR,
324 format!("Unexpected streaming error: {e}"),
325 ),
326 }
327}
328
329#[utoipa::path(
340 post,
341 path = "/collections/{name}/stream/enable",
342 tag = "points",
343 params(
344 ("name" = String, Path, description = "Collection name")
345 ),
346 request_body = EnableStreamingRequest,
347 responses(
348 (status = 200, description = "Streaming enabled", body = Object),
349 (status = 404, description = "Collection not found", body = ErrorResponse)
350 )
351)]
352pub async fn enable_streaming(
353 State(state): State<Arc<AppState>>,
354 Path(name): Path<String>,
355 Json(req): Json<EnableStreamingRequest>,
356) -> impl IntoResponse {
357 let collection = match get_vector_collection_or_404(&state, &name) {
358 Ok(c) => c,
359 Err(resp) => return resp,
360 };
361
362 enable_streaming_on(&collection, &req);
363
364 Json(serde_json::json!({
365 "message": "Streaming enabled",
366 "collection": name,
367 }))
368 .into_response()
369}
370
371#[cfg(feature = "persistence")]
373fn enable_streaming_on(collection: &VectorCollection, req: &EnableStreamingRequest) {
374 collection.enable_streaming(req.to_config());
375}
376
377#[cfg(not(feature = "persistence"))]
379fn enable_streaming_on(_collection: &VectorCollection, _req: &EnableStreamingRequest) {}