Skip to main content

velesdb_server/handlers/points/
mod.rs

1//! Point operations handlers.
2
3pub mod raw;
4pub mod relations;
5pub mod streaming;
6
7pub use raw::upsert_points_raw;
8pub use relations::{get_point_relations, relate_points, set_point_ttl, unrelate_points};
9pub use streaming::{
10    __path_enable_streaming, __path_stream_insert, __path_stream_upsert_points, enable_streaming,
11    stream_insert, stream_upsert_points,
12};
13
14use axum::{
15    extract::{Path, State},
16    http::StatusCode,
17    response::IntoResponse,
18    Json,
19};
20use std::sync::Arc;
21
22use crate::types::{
23    ErrorResponse, ScrollPoint, ScrollRequest, ScrollResponse, SparseVectorInput,
24    UpsertPointsRequest,
25};
26use crate::AppState;
27use velesdb_core::api_types::serde_id;
28use velesdb_core::Point;
29
30use crate::handlers::helpers::{
31    auto_core_error_response, error_response, get_vector_collection_or_404,
32};
33
34use velesdb_core::index::sparse::SparseVector;
35
36/// Converts sparse vector input fields from a request into a `BTreeMap<String, SparseVector>`.
37///
38/// Merges `sparse_vector` (single, stored under `""`) and `sparse_vectors` (named map).
39/// Named map takes precedence if both provide the same key.
40fn convert_sparse_inputs(
41    sparse_vector: Option<SparseVectorInput>,
42    sparse_vectors: Option<std::collections::BTreeMap<String, SparseVectorInput>>,
43) -> Result<Option<std::collections::BTreeMap<String, SparseVector>>, String> {
44    let has_single = sparse_vector.is_some();
45    let has_named = sparse_vectors.as_ref().is_some_and(|m| !m.is_empty());
46
47    if !has_single && !has_named {
48        return Ok(None);
49    }
50
51    let mut result = std::collections::BTreeMap::new();
52
53    // Single sparse vector goes under default name ""
54    if let Some(sv_input) = sparse_vector {
55        let sv = sv_input.into_sparse_vector()?;
56        result.insert(String::new(), sv);
57    }
58
59    // Named sparse vectors (overwrite default if same key).
60    if let Some(named) = sparse_vectors {
61        merge_named_sparse_vectors(named, &mut result)?;
62    }
63
64    Ok(Some(result))
65}
66
67/// Merge a named-sparse-vector map into `result`, converting each input.
68///
69/// If both `sparse_vector` and `sparse_vectors[""]` are supplied, the named map
70/// wins; a debug trace is emitted so operators can spot this (usually
71/// unintentional) pattern.
72fn merge_named_sparse_vectors(
73    named: std::collections::BTreeMap<String, SparseVectorInput>,
74    result: &mut std::collections::BTreeMap<String, SparseVector>,
75) -> Result<(), String> {
76    for (name, sv_input) in named {
77        let sv = sv_input
78            .into_sparse_vector()
79            .map_err(|e| format!("sparse_vectors['{name}']: {e}"))?;
80        if name.is_empty() && result.contains_key("") {
81            tracing::debug!(
82                "sparse_vector (default \"\") is being overwritten by \
83                 sparse_vectors[\"\"] — supply only one to avoid ambiguity"
84            );
85        }
86        result.insert(name, sv);
87    }
88    Ok(())
89}
90
91/// Maximum number of points in a single JSON upsert request.
92///
93/// Consistent with `MAX_BULK_DELETE_SIZE` and `MAX_SCROLL_BATCH_SIZE`.
94/// The 100 MB body limit on the route already bounds bytes; this constant
95/// bounds the point *count* to prevent memory amplification from metadata-only
96/// or tiny-vector collections where 100 MB of JSON can represent millions of points.
97const MAX_UPSERT_BATCH_SIZE: usize = 100_000;
98
99/// Upsert points to a collection.
100#[utoipa::path(
101    post,
102    path = "/collections/{name}/points",
103    tag = "points",
104    params(
105        ("name" = String, Path, description = "Collection name")
106    ),
107    request_body = UpsertPointsRequest,
108    responses(
109        (status = 200, description = "Points upserted", body = Object),
110        (status = 404, description = "Collection not found", body = ErrorResponse),
111        (status = 400, description = "Invalid request or batch too large", body = ErrorResponse)
112    )
113)]
114pub async fn upsert_points(
115    State(state): State<Arc<AppState>>,
116    Path(name): Path<String>,
117    Json(req): Json<UpsertPointsRequest>,
118) -> impl IntoResponse {
119    if req.points.len() > MAX_UPSERT_BATCH_SIZE {
120        return error_response(
121            StatusCode::BAD_REQUEST,
122            format!(
123                "Batch too large: {} points (max {MAX_UPSERT_BATCH_SIZE})",
124                req.points.len()
125            ),
126        );
127    }
128
129    let collection = match get_vector_collection_or_404(&state, &name) {
130        Ok(c) => c,
131        Err(resp) => return resp,
132    };
133
134    let points = match build_points_from_request(req) {
135        Ok(p) => p,
136        Err(e) => {
137            return error_response(StatusCode::BAD_REQUEST, e);
138        }
139    };
140
141    // CRITICAL: upsert_bulk is blocking (HNSW insertion + I/O).
142    // Must use spawn_blocking to avoid blocking the async runtime.
143    let result = tokio::task::spawn_blocking(move || collection.upsert_bulk(&points)).await;
144
145    upsert_result_to_response(&state, &name, result)
146}
147
148/// Convert a `spawn_blocking` bulk-upsert result into an HTTP response.
149///
150/// On success it notifies the observer and returns `{message, count}`; a core
151/// error maps via [`auto_core_error_response`] and a task panic yields a 500.
152/// Shared by [`upsert_points`] and [`raw::upsert_points_raw`].
153pub(super) fn upsert_result_to_response(
154    state: &AppState,
155    name: &str,
156    result: Result<velesdb_core::Result<usize>, tokio::task::JoinError>,
157) -> axum::response::Response {
158    match result {
159        Ok(Ok(inserted)) => {
160            state.db.notify_upsert(name, inserted);
161            Json(serde_json::json!({
162                "message": "Points upserted",
163                "count": inserted
164            }))
165            .into_response()
166        }
167        Ok(Err(e)) => auto_core_error_response(&e),
168        Err(e) => error_response(
169            StatusCode::INTERNAL_SERVER_ERROR,
170            format!("Task panicked: {e}"),
171        ),
172    }
173}
174
175/// Convert an `UpsertPointsRequest` into a `Vec<Point>`, merging sparse inputs.
176fn build_points_from_request(req: UpsertPointsRequest) -> Result<Vec<Point>, String> {
177    let mut points: Vec<Point> = Vec::with_capacity(req.points.len());
178    for p in req.points {
179        let sparse = convert_sparse_inputs(p.sparse_vector, p.sparse_vectors)?;
180        let mut point = Point::new(p.id, p.vector, p.payload);
181        point.sparse_vectors = sparse;
182        points.push(point);
183    }
184    Ok(points)
185}
186
187/// Get a point by ID.
188#[utoipa::path(
189    get,
190    path = "/collections/{name}/points/{id}",
191    tag = "points",
192    params(
193        ("name" = String, Path, description = "Collection name"),
194        ("id" = String, Path, description = "Point ID (u64 as a string; precision-safe above 2^53-1)", pattern = "^[0-9]+$")
195    ),
196    responses(
197        (status = 200, description = "Point found", body = Object),
198        (status = 404, description = "Point or collection not found", body = ErrorResponse)
199    )
200)]
201pub async fn get_point(
202    State(state): State<Arc<AppState>>,
203    Path((name, id)): Path<(String, u64)>,
204) -> impl IntoResponse {
205    let collection = match get_vector_collection_or_404(&state, &name) {
206        Ok(c) => c,
207        Err(resp) => return resp,
208    };
209
210    let points = collection.get(&[id]);
211
212    match points.into_iter().next().flatten() {
213        Some(point) => Json(serde_json::json!({
214            "id": point.id,
215            "vector": point.vector,
216            "payload": point.payload
217        }))
218        .into_response(),
219        // PR #586 Devin fix: emit `VELES-003 PointNotFound` via
220        // `auto_core_error_response` so typed-error clients surface
221        // `PointNotFoundError` instead of a generic fallback.
222        None => auto_core_error_response(&velesdb_core::Error::PointNotFound(id)),
223    }
224}
225
226/// Delete a point by ID.
227#[utoipa::path(
228    delete,
229    path = "/collections/{name}/points/{id}",
230    tag = "points",
231    params(
232        ("name" = String, Path, description = "Collection name"),
233        ("id" = String, Path, description = "Point ID (u64 as a string; precision-safe above 2^53-1)", pattern = "^[0-9]+$")
234    ),
235    responses(
236        (status = 200, description = "Point deleted", body = Object),
237        (status = 404, description = "Point or collection not found", body = ErrorResponse)
238    )
239)]
240pub async fn delete_point(
241    State(state): State<Arc<AppState>>,
242    Path((name, id)): Path<(String, u64)>,
243) -> impl IntoResponse {
244    let collection = match get_vector_collection_or_404(&state, &name) {
245        Ok(c) => c,
246        Err(resp) => return resp,
247    };
248
249    match collection.delete(&[id]) {
250        Ok(()) => Json(serde_json::json!({
251            "message": "Point deleted",
252            "id": id
253        }))
254        .into_response(),
255        Err(e) => auto_core_error_response(&e),
256    }
257}
258
259/// Maximum allowed batch size for scroll requests.
260const MAX_SCROLL_BATCH_SIZE: u32 = 10_000;
261
262/// Scroll through collection points with cursor-based pagination.
263#[utoipa::path(
264    post,
265    path = "/collections/{name}/points/scroll",
266    tag = "points",
267    params(("name" = String, Path, description = "Collection name")),
268    request_body = ScrollRequest,
269    responses(
270        (status = 200, description = "Scroll batch", body = ScrollResponse),
271        (status = 400, description = "Invalid request", body = ErrorResponse),
272        (status = 404, description = "Collection not found", body = ErrorResponse)
273    )
274)]
275pub async fn scroll_points(
276    State(state): State<Arc<AppState>>,
277    Path(name): Path<String>,
278    Json(req): Json<ScrollRequest>,
279) -> impl IntoResponse {
280    if req.batch_size == 0 || req.batch_size > MAX_SCROLL_BATCH_SIZE {
281        return error_response(
282            StatusCode::BAD_REQUEST,
283            "batch_size must be between 1 and 10000".to_string(),
284        );
285    }
286
287    let collection = match get_vector_collection_or_404(&state, &name) {
288        Ok(c) => c,
289        Err(resp) => return resp,
290    };
291
292    let filter = match parse_scroll_filter(&req.filter) {
293        Ok(f) => f,
294        Err(resp) => return resp,
295    };
296
297    let batch_size = req.batch_size as usize;
298    let cursor = req.cursor;
299
300    // scroll_batch is blocking (reads from storage).
301    let result = tokio::task::spawn_blocking(move || {
302        collection.scroll_batch(cursor, batch_size, filter.as_ref())
303    })
304    .await;
305
306    match result {
307        Ok(Ok(batch)) => build_scroll_response(batch),
308        Ok(Err(e)) => auto_core_error_response(&e),
309        Err(e) => error_response(
310            StatusCode::INTERNAL_SERVER_ERROR,
311            format!("Task panicked: {e}"),
312        ),
313    }
314}
315
316/// Parse the optional filter JSON into a core `Filter`.
317#[allow(clippy::result_large_err)]
318fn parse_scroll_filter(
319    filter_json: &Option<serde_json::Value>,
320) -> Result<Option<velesdb_core::Filter>, axum::response::Response> {
321    let Some(ref json) = filter_json else {
322        return Ok(None);
323    };
324    serde_json::from_value::<velesdb_core::Filter>(json.clone())
325        .map(Some)
326        .map_err(|e| error_response(StatusCode::BAD_REQUEST, format!("Invalid filter: {e}")))
327}
328
329/// Convert a core `ScrollBatch` into an HTTP JSON response.
330fn build_scroll_response(batch: velesdb_core::ScrollBatch) -> axum::response::Response {
331    let points: Vec<ScrollPoint> = batch
332        .points
333        .into_iter()
334        .map(|p| ScrollPoint {
335            id: p.id,
336            vector: p.vector,
337            payload: p.payload,
338        })
339        .collect();
340    Json(ScrollResponse {
341        next_cursor: batch.next_cursor,
342        points,
343    })
344    .into_response()
345}
346
347/// Maximum number of IDs in a single bulk delete request.
348const MAX_BULK_DELETE_SIZE: usize = 10_000;
349
350/// Request body for bulk point deletion.
351#[derive(serde::Deserialize, utoipa::ToSchema)]
352pub struct BulkDeleteRequest {
353    /// List of point IDs to delete.
354    #[serde(deserialize_with = "serde_id::deserialize_ids_from_string_or_number")]
355    #[cfg_attr(feature = "openapi", schema(schema_with = serde_id::ids_array_schema))]
356    pub ids: Vec<u64>,
357}
358
359/// Deletes multiple points by ID in a single request.
360///
361/// Accepts a JSON body with a list of point IDs. All IDs are passed to
362/// the underlying `Collection::delete(&[u64])` in one call, which is
363/// more efficient than individual deletions.
364///
365/// Returns the number of points that were requested for deletion.
366/// Points that do not exist are silently skipped (idempotent delete).
367///
368/// # Empty payload semantics
369///
370/// `{ "ids": [] }` is treated as a successful no-op: the response is
371/// `200 OK` with `deleted_count = 0`. This matches Kubernetes-style
372/// idempotent batch APIs and lets callers send empty batches without
373/// special-casing on the client side.
374///
375/// # Limits
376///
377/// Batches larger than `MAX_BULK_DELETE_SIZE` (10000) are rejected with
378/// `400 BAD_REQUEST`.
379#[utoipa::path(
380    post,
381    path = "/collections/{name}/points/delete",
382    tag = "points",
383    params(
384        ("name" = String, Path, description = "Collection name")
385    ),
386    request_body = BulkDeleteRequest,
387    responses(
388        (status = 200, description = "Points deleted", body = Object),
389        (status = 400, description = "Batch too large", body = ErrorResponse),
390        (status = 404, description = "Collection not found", body = ErrorResponse),
391        (status = 500, description = "Delete failed", body = ErrorResponse)
392    )
393)]
394pub async fn bulk_delete_points(
395    State(state): State<Arc<AppState>>,
396    Path(name): Path<String>,
397    Json(req): Json<BulkDeleteRequest>,
398) -> impl IntoResponse {
399    if req.ids.is_empty() {
400        return Json(serde_json::json!({
401            "message": "No points to delete",
402            "collection": name,
403            "deleted_count": 0
404        }))
405        .into_response();
406    }
407
408    if req.ids.len() > MAX_BULK_DELETE_SIZE {
409        return error_response(
410            StatusCode::BAD_REQUEST,
411            format!(
412                "Batch too large: {} IDs (max {MAX_BULK_DELETE_SIZE})",
413                req.ids.len()
414            ),
415        );
416    }
417
418    let collection = match get_vector_collection_or_404(&state, &name) {
419        Ok(c) => c,
420        Err(resp) => return resp,
421    };
422
423    let ids = req.ids;
424    let count = ids.len();
425    let coll_name = name.clone();
426
427    let result = tokio::task::spawn_blocking(move || collection.delete(&ids)).await;
428    match result {
429        Ok(Ok(())) => Json(serde_json::json!({
430            "message": "Points deleted",
431            "collection": coll_name,
432            "deleted_count": count
433        }))
434        .into_response(),
435        Ok(Err(e)) => auto_core_error_response(&e),
436        Err(join_err) => error_response(
437            StatusCode::INTERNAL_SERVER_ERROR,
438            format!("bulk_delete task panicked: {join_err}"),
439        ),
440    }
441}
442
443#[cfg(test)]
444mod tests {
445    use super::*;
446
447    #[test]
448    fn upsert_batch_constant_matches_expected_value() {
449        assert_eq!(MAX_UPSERT_BATCH_SIZE, 100_000);
450    }
451
452    #[test]
453    fn scroll_batch_constant_matches_expected_value() {
454        assert_eq!(MAX_SCROLL_BATCH_SIZE, 10_000);
455    }
456
457    #[test]
458    fn bulk_delete_batch_constant_matches_expected_value() {
459        assert_eq!(MAX_BULK_DELETE_SIZE, 10_000);
460    }
461
462    #[test]
463    fn upsert_batch_limit_is_larger_than_delete_limit() {
464        // Upsert is intentionally higher: ingestion workloads need larger batches.
465        assert!(MAX_UPSERT_BATCH_SIZE > MAX_BULK_DELETE_SIZE);
466    }
467}