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        // ID as a string for JS precision-safety above 2^53-1, consistent with
214        // every other read surface (search/scroll/relations, see `serde_id`).
215        Some(point) => Json(serde_json::json!({
216            "id": point.id.to_string(),
217            "vector": point.vector,
218            "payload": point.payload
219        }))
220        .into_response(),
221        // PR #586 Devin fix: emit `VELES-003 PointNotFound` via
222        // `auto_core_error_response` so typed-error clients surface
223        // `PointNotFoundError` instead of a generic fallback.
224        None => auto_core_error_response(&velesdb_core::Error::PointNotFound(id)),
225    }
226}
227
228/// Delete a point by ID.
229#[utoipa::path(
230    delete,
231    path = "/collections/{name}/points/{id}",
232    tag = "points",
233    params(
234        ("name" = String, Path, description = "Collection name"),
235        ("id" = String, Path, description = "Point ID (u64 as a string; precision-safe above 2^53-1)", pattern = "^[0-9]+$")
236    ),
237    responses(
238        (status = 200, description = "Point deleted", body = Object),
239        (status = 404, description = "Point or collection not found", body = ErrorResponse)
240    )
241)]
242pub async fn delete_point(
243    State(state): State<Arc<AppState>>,
244    Path((name, id)): Path<(String, u64)>,
245) -> impl IntoResponse {
246    let collection = match get_vector_collection_or_404(&state, &name) {
247        Ok(c) => c,
248        Err(resp) => return resp,
249    };
250
251    match collection.delete(&[id]) {
252        // ID as a string for JS precision-safety (see `serde_id`), consistent
253        // with the string ID accepted in the path and returned by reads.
254        Ok(()) => Json(serde_json::json!({
255            "message": "Point deleted",
256            "id": id.to_string()
257        }))
258        .into_response(),
259        Err(e) => auto_core_error_response(&e),
260    }
261}
262
263/// Maximum allowed batch size for scroll requests.
264const MAX_SCROLL_BATCH_SIZE: u32 = 10_000;
265
266/// Scroll through collection points with cursor-based pagination.
267#[utoipa::path(
268    post,
269    path = "/collections/{name}/points/scroll",
270    tag = "points",
271    params(("name" = String, Path, description = "Collection name")),
272    request_body = ScrollRequest,
273    responses(
274        (status = 200, description = "Scroll batch", body = ScrollResponse),
275        (status = 400, description = "Invalid request", body = ErrorResponse),
276        (status = 404, description = "Collection not found", body = ErrorResponse)
277    )
278)]
279pub async fn scroll_points(
280    State(state): State<Arc<AppState>>,
281    Path(name): Path<String>,
282    Json(req): Json<ScrollRequest>,
283) -> impl IntoResponse {
284    if req.batch_size == 0 || req.batch_size > MAX_SCROLL_BATCH_SIZE {
285        return error_response(
286            StatusCode::BAD_REQUEST,
287            "batch_size must be between 1 and 10000".to_string(),
288        );
289    }
290
291    let collection = match get_vector_collection_or_404(&state, &name) {
292        Ok(c) => c,
293        Err(resp) => return resp,
294    };
295
296    let filter = match parse_scroll_filter(&req.filter) {
297        Ok(f) => f,
298        Err(resp) => return resp,
299    };
300
301    let batch_size = req.batch_size as usize;
302    let cursor = req.cursor;
303
304    // scroll_batch is blocking (reads from storage).
305    let result = tokio::task::spawn_blocking(move || {
306        collection.scroll_batch(cursor, batch_size, filter.as_ref())
307    })
308    .await;
309
310    match result {
311        Ok(Ok(batch)) => build_scroll_response(batch),
312        Ok(Err(e)) => auto_core_error_response(&e),
313        Err(e) => error_response(
314            StatusCode::INTERNAL_SERVER_ERROR,
315            format!("Task panicked: {e}"),
316        ),
317    }
318}
319
320/// Parse the optional filter JSON into a core `Filter`.
321#[allow(clippy::result_large_err)]
322fn parse_scroll_filter(
323    filter_json: &Option<serde_json::Value>,
324) -> Result<Option<velesdb_core::Filter>, axum::response::Response> {
325    let Some(ref json) = filter_json else {
326        return Ok(None);
327    };
328    serde_json::from_value::<velesdb_core::Filter>(json.clone())
329        .map(Some)
330        .map_err(|e| error_response(StatusCode::BAD_REQUEST, format!("Invalid filter: {e}")))
331}
332
333/// Convert a core `ScrollBatch` into an HTTP JSON response.
334fn build_scroll_response(batch: velesdb_core::ScrollBatch) -> axum::response::Response {
335    let points: Vec<ScrollPoint> = batch
336        .points
337        .into_iter()
338        .map(|p| ScrollPoint {
339            id: p.id,
340            vector: p.vector,
341            payload: p.payload,
342        })
343        .collect();
344    Json(ScrollResponse {
345        next_cursor: batch.next_cursor,
346        points,
347    })
348    .into_response()
349}
350
351/// Maximum number of IDs in a single bulk delete request.
352const MAX_BULK_DELETE_SIZE: usize = 10_000;
353
354/// Request body for bulk point deletion.
355#[derive(serde::Deserialize, utoipa::ToSchema)]
356pub struct BulkDeleteRequest {
357    /// List of point IDs to delete.
358    #[serde(deserialize_with = "serde_id::deserialize_ids_from_string_or_number")]
359    #[cfg_attr(feature = "openapi", schema(schema_with = serde_id::ids_array_schema))]
360    pub ids: Vec<u64>,
361}
362
363/// Deletes multiple points by ID in a single request.
364///
365/// Accepts a JSON body with a list of point IDs. All IDs are passed to
366/// the underlying `Collection::delete(&[u64])` in one call, which is
367/// more efficient than individual deletions.
368///
369/// Returns the number of points that were requested for deletion.
370/// Points that do not exist are silently skipped (idempotent delete).
371///
372/// # Empty payload semantics
373///
374/// `{ "ids": [] }` is treated as a successful no-op: the response is
375/// `200 OK` with `deleted_count = 0`. This matches Kubernetes-style
376/// idempotent batch APIs and lets callers send empty batches without
377/// special-casing on the client side.
378///
379/// # Limits
380///
381/// Batches larger than `MAX_BULK_DELETE_SIZE` (10000) are rejected with
382/// `400 BAD_REQUEST`.
383#[utoipa::path(
384    post,
385    path = "/collections/{name}/points/delete",
386    tag = "points",
387    params(
388        ("name" = String, Path, description = "Collection name")
389    ),
390    request_body = BulkDeleteRequest,
391    responses(
392        (status = 200, description = "Points deleted", body = Object),
393        (status = 400, description = "Batch too large", body = ErrorResponse),
394        (status = 404, description = "Collection not found", body = ErrorResponse),
395        (status = 500, description = "Delete failed", body = ErrorResponse)
396    )
397)]
398pub async fn bulk_delete_points(
399    State(state): State<Arc<AppState>>,
400    Path(name): Path<String>,
401    Json(req): Json<BulkDeleteRequest>,
402) -> impl IntoResponse {
403    if req.ids.is_empty() {
404        return Json(serde_json::json!({
405            "message": "No points to delete",
406            "collection": name,
407            "deleted_count": 0
408        }))
409        .into_response();
410    }
411
412    if req.ids.len() > MAX_BULK_DELETE_SIZE {
413        return error_response(
414            StatusCode::BAD_REQUEST,
415            format!(
416                "Batch too large: {} IDs (max {MAX_BULK_DELETE_SIZE})",
417                req.ids.len()
418            ),
419        );
420    }
421
422    let collection = match get_vector_collection_or_404(&state, &name) {
423        Ok(c) => c,
424        Err(resp) => return resp,
425    };
426
427    let ids = req.ids;
428    let count = ids.len();
429    let coll_name = name.clone();
430
431    let result = tokio::task::spawn_blocking(move || collection.delete(&ids)).await;
432    match result {
433        Ok(Ok(())) => Json(serde_json::json!({
434            "message": "Points deleted",
435            "collection": coll_name,
436            "deleted_count": count
437        }))
438        .into_response(),
439        Ok(Err(e)) => auto_core_error_response(&e),
440        Err(join_err) => error_response(
441            StatusCode::INTERNAL_SERVER_ERROR,
442            format!("bulk_delete task panicked: {join_err}"),
443        ),
444    }
445}
446
447#[cfg(test)]
448mod tests {
449    use super::*;
450
451    #[test]
452    fn upsert_batch_constant_matches_expected_value() {
453        assert_eq!(MAX_UPSERT_BATCH_SIZE, 100_000);
454    }
455
456    #[test]
457    fn scroll_batch_constant_matches_expected_value() {
458        assert_eq!(MAX_SCROLL_BATCH_SIZE, 10_000);
459    }
460
461    #[test]
462    fn bulk_delete_batch_constant_matches_expected_value() {
463        assert_eq!(MAX_BULK_DELETE_SIZE, 10_000);
464    }
465
466    #[test]
467    fn upsert_batch_limit_is_larger_than_delete_limit() {
468        // Upsert is intentionally higher: ingestion workloads need larger batches.
469        assert!(MAX_UPSERT_BATCH_SIZE > MAX_BULK_DELETE_SIZE);
470    }
471}