Skip to main content

velesdb_server/handlers/points/
streaming.rs

1//! NDJSON streaming upsert and bounded ingestion channel handlers.
2
3use 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/// Accumulates statistics over an NDJSON stream upsert operation.
24#[derive(Default)]
25struct StreamUpsertStats {
26    inserted: usize,
27    malformed: usize,
28    failed_upserts: usize,
29    /// Number of HTTP/transport errors encountered while reading the request body.
30    ///
31    /// A non-zero value means the stream was truncated mid-transfer; the response
32    /// `inserted` count is therefore a lower bound on how many points were actually
33    /// sent by the client.
34    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            // N-2: include point ID in the warning when it is available from context.
52            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
65/// Flushes a batch and -- if the collection's delta buffer is active -- also
66/// pushes the entries into the buffer for immediate searchability.
67async 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    // Snapshot (id, vector) pairs for delta before moving `points` into spawn_blocking.
80    // Only allocate when delta is active to keep the hot path allocation-free.
81    #[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            // C-3: push into the delta buffer after a successful upsert so that
94            // search can find these points before HNSW is rebuilt.
95            #[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/// Stream upsert points using NDJSON.
120///
121/// Accepts a `application/x-ndjson` body. Each line is a JSON-encoded [`Point`].
122/// Points are accumulated into micro-batches and flushed via `upsert_bulk`.
123///
124/// The response body includes a `network_errors` field: a non-zero value means
125/// the HTTP body stream was truncated (e.g., client disconnect or proxy error),
126/// and the server may have received fewer points than the client sent (M-7).
127#[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        // This REST path writes via the programmatic `Collection` API, which core
154        // does NOT instrument (core fires `on_upsert` only through the VelesQL DML
155        // use-case path). The shim is therefore the sole telemetry source here and
156        // does not double-count. See `Database::notify_upsert` deprecation note.
157        #[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
171/// Pre-parse the `id` field from a JSON line for diagnostic logging.
172fn 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
178/// Read an NDJSON body stream, batching points and flushing periodically.
179async 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    // Drain any remaining incomplete line in the buffer.
204    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
214/// Extract complete lines from the byte buffer and parse them as NDJSON points.
215fn 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
228/// Check whether the current batch should be flushed.
229fn 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/// Stream-insert a single point via the bounded ingestion channel.
235///
236/// Returns 202 Accepted on success, 429 Too Many Requests when the buffer is
237/// full (with `Retry-After: 1` header per RFC 7231), 503 Service Unavailable
238/// when the drain task has exited, and 404 when the collection is not found.
239///
240/// This handler is `async` to satisfy Axum's handler contract; it does not
241/// perform any async I/O internally (the channel send is non-blocking).
242#[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/// Validate that the request vector dimension matches the collection.
277#[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
295/// Convert a `stream_insert` result into an HTTP response.
296fn 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/// Enable streaming ingestion on a collection.
330///
331/// Spawns the background drain task so subsequent calls to
332/// `/collections/{name}/stream/insert` accept points instead of returning a
333/// `409 Conflict` "streaming not configured" error. Omitted body fields fall
334/// back to the engine defaults. Calling this again replaces the existing
335/// ingester (the old drain task is aborted).
336///
337/// Returns `200 OK` on success and `404 Not Found` when the collection does
338/// not exist.
339#[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/// Enables streaming on the collection when persistence is compiled in.
372#[cfg(feature = "persistence")]
373fn enable_streaming_on(collection: &VectorCollection, req: &EnableStreamingRequest) {
374    collection.enable_streaming(req.to_config());
375}
376
377/// No-op when persistence is disabled (the streaming pipeline is unavailable).
378#[cfg(not(feature = "persistence"))]
379fn enable_streaming_on(_collection: &VectorCollection, _req: &EnableStreamingRequest) {}