1pub 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
36fn 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 if let Some(sv_input) = sparse_vector {
55 let sv = sv_input.into_sparse_vector()?;
56 result.insert(String::new(), sv);
57 }
58
59 if let Some(named) = sparse_vectors {
61 merge_named_sparse_vectors(named, &mut result)?;
62 }
63
64 Ok(Some(result))
65}
66
67fn 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
91const MAX_UPSERT_BATCH_SIZE: usize = 100_000;
98
99#[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 let result = tokio::task::spawn_blocking(move || collection.upsert_bulk(&points)).await;
144
145 upsert_result_to_response(&state, &name, result)
146}
147
148pub(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 #[allow(deprecated)]
164 state.db.notify_upsert(name, inserted);
165 Json(serde_json::json!({
166 "message": "Points upserted",
167 "count": inserted
168 }))
169 .into_response()
170 }
171 Ok(Err(e)) => auto_core_error_response(&e),
172 Err(e) => error_response(
173 StatusCode::INTERNAL_SERVER_ERROR,
174 format!("Task panicked: {e}"),
175 ),
176 }
177}
178
179fn build_points_from_request(req: UpsertPointsRequest) -> Result<Vec<Point>, String> {
181 let mut points: Vec<Point> = Vec::with_capacity(req.points.len());
182 for p in req.points {
183 let sparse = convert_sparse_inputs(p.sparse_vector, p.sparse_vectors)?;
184 let mut point = Point::new(p.id, p.vector, p.payload);
185 point.sparse_vectors = sparse;
186 points.push(point);
187 }
188 Ok(points)
189}
190
191#[utoipa::path(
193 get,
194 path = "/collections/{name}/points/{id}",
195 tag = "points",
196 params(
197 ("name" = String, Path, description = "Collection name"),
198 ("id" = String, Path, description = "Point ID (u64 as a string; precision-safe above 2^53-1)", pattern = "^[0-9]+$")
199 ),
200 responses(
201 (status = 200, description = "Point found", body = Object),
202 (status = 404, description = "Point or collection not found", body = ErrorResponse)
203 )
204)]
205pub async fn get_point(
206 State(state): State<Arc<AppState>>,
207 Path((name, id)): Path<(String, u64)>,
208) -> impl IntoResponse {
209 let collection = match get_vector_collection_or_404(&state, &name) {
210 Ok(c) => c,
211 Err(resp) => return resp,
212 };
213
214 let points = collection.get(&[id]);
215
216 match points.into_iter().next().flatten() {
217 Some(point) => Json(serde_json::json!({
220 "id": point.id.to_string(),
221 "vector": point.vector,
222 "payload": point.payload
223 }))
224 .into_response(),
225 None => auto_core_error_response(&velesdb_core::Error::PointNotFound(id)),
229 }
230}
231
232#[utoipa::path(
234 delete,
235 path = "/collections/{name}/points/{id}",
236 tag = "points",
237 params(
238 ("name" = String, Path, description = "Collection name"),
239 ("id" = String, Path, description = "Point ID (u64 as a string; precision-safe above 2^53-1)", pattern = "^[0-9]+$")
240 ),
241 responses(
242 (status = 200, description = "Point deleted", body = Object),
243 (status = 404, description = "Point or collection not found", body = ErrorResponse)
244 )
245)]
246pub async fn delete_point(
247 State(state): State<Arc<AppState>>,
248 Path((name, id)): Path<(String, u64)>,
249) -> impl IntoResponse {
250 let collection = match get_vector_collection_or_404(&state, &name) {
251 Ok(c) => c,
252 Err(resp) => return resp,
253 };
254
255 match collection.delete(&[id]) {
256 Ok(()) => Json(serde_json::json!({
259 "message": "Point deleted",
260 "id": id.to_string()
261 }))
262 .into_response(),
263 Err(e) => auto_core_error_response(&e),
264 }
265}
266
267const MAX_SCROLL_BATCH_SIZE: u32 = 10_000;
269
270#[utoipa::path(
272 post,
273 path = "/collections/{name}/points/scroll",
274 tag = "points",
275 params(("name" = String, Path, description = "Collection name")),
276 request_body = ScrollRequest,
277 responses(
278 (status = 200, description = "Scroll batch", body = ScrollResponse),
279 (status = 400, description = "Invalid request", body = ErrorResponse),
280 (status = 404, description = "Collection not found", body = ErrorResponse)
281 )
282)]
283pub async fn scroll_points(
284 State(state): State<Arc<AppState>>,
285 Path(name): Path<String>,
286 Json(req): Json<ScrollRequest>,
287) -> impl IntoResponse {
288 if req.batch_size == 0 || req.batch_size > MAX_SCROLL_BATCH_SIZE {
289 return error_response(
290 StatusCode::BAD_REQUEST,
291 "batch_size must be between 1 and 10000".to_string(),
292 );
293 }
294
295 let collection = match get_vector_collection_or_404(&state, &name) {
296 Ok(c) => c,
297 Err(resp) => return resp,
298 };
299
300 let filter = match parse_scroll_filter(&req.filter) {
301 Ok(f) => f,
302 Err(resp) => return resp,
303 };
304
305 let batch_size = req.batch_size as usize;
306 let cursor = req.cursor;
307
308 let result = tokio::task::spawn_blocking(move || {
310 collection.scroll_batch(cursor, batch_size, filter.as_ref())
311 })
312 .await;
313
314 match result {
315 Ok(Ok(batch)) => build_scroll_response(batch),
316 Ok(Err(e)) => auto_core_error_response(&e),
317 Err(e) => error_response(
318 StatusCode::INTERNAL_SERVER_ERROR,
319 format!("Task panicked: {e}"),
320 ),
321 }
322}
323
324#[allow(clippy::result_large_err)]
326fn parse_scroll_filter(
327 filter_json: &Option<serde_json::Value>,
328) -> Result<Option<velesdb_core::Filter>, axum::response::Response> {
329 let Some(ref json) = filter_json else {
330 return Ok(None);
331 };
332 serde_json::from_value::<velesdb_core::Filter>(json.clone())
333 .map(Some)
334 .map_err(|e| error_response(StatusCode::BAD_REQUEST, format!("Invalid filter: {e}")))
335}
336
337fn build_scroll_response(batch: velesdb_core::ScrollBatch) -> axum::response::Response {
339 let points: Vec<ScrollPoint> = batch
340 .points
341 .into_iter()
342 .map(|p| ScrollPoint {
343 id: p.id,
344 vector: p.vector,
345 payload: p.payload,
346 })
347 .collect();
348 Json(ScrollResponse {
349 next_cursor: batch.next_cursor,
350 points,
351 })
352 .into_response()
353}
354
355const MAX_BULK_DELETE_SIZE: usize = 10_000;
357
358#[derive(serde::Deserialize, utoipa::ToSchema)]
360pub struct BulkDeleteRequest {
361 #[serde(deserialize_with = "serde_id::deserialize_ids_from_string_or_number")]
363 #[cfg_attr(feature = "openapi", schema(schema_with = serde_id::ids_array_schema))]
364 pub ids: Vec<u64>,
365}
366
367#[utoipa::path(
388 post,
389 path = "/collections/{name}/points/delete",
390 tag = "points",
391 params(
392 ("name" = String, Path, description = "Collection name")
393 ),
394 request_body = BulkDeleteRequest,
395 responses(
396 (status = 200, description = "Points deleted", body = Object),
397 (status = 400, description = "Batch too large", body = ErrorResponse),
398 (status = 404, description = "Collection not found", body = ErrorResponse),
399 (status = 500, description = "Delete failed", body = ErrorResponse)
400 )
401)]
402pub async fn bulk_delete_points(
403 State(state): State<Arc<AppState>>,
404 Path(name): Path<String>,
405 Json(req): Json<BulkDeleteRequest>,
406) -> impl IntoResponse {
407 if req.ids.is_empty() {
408 return Json(serde_json::json!({
409 "message": "No points to delete",
410 "collection": name,
411 "deleted_count": 0
412 }))
413 .into_response();
414 }
415
416 if req.ids.len() > MAX_BULK_DELETE_SIZE {
417 return error_response(
418 StatusCode::BAD_REQUEST,
419 format!(
420 "Batch too large: {} IDs (max {MAX_BULK_DELETE_SIZE})",
421 req.ids.len()
422 ),
423 );
424 }
425
426 let collection = match get_vector_collection_or_404(&state, &name) {
427 Ok(c) => c,
428 Err(resp) => return resp,
429 };
430
431 let ids = req.ids;
432 let count = ids.len();
433 let coll_name = name.clone();
434
435 let result = tokio::task::spawn_blocking(move || collection.delete(&ids)).await;
436 match result {
437 Ok(Ok(())) => Json(serde_json::json!({
438 "message": "Points deleted",
439 "collection": coll_name,
440 "deleted_count": count
441 }))
442 .into_response(),
443 Ok(Err(e)) => auto_core_error_response(&e),
444 Err(join_err) => error_response(
445 StatusCode::INTERNAL_SERVER_ERROR,
446 format!("bulk_delete task panicked: {join_err}"),
447 ),
448 }
449}
450
451#[cfg(test)]
452mod tests {
453 use super::*;
454
455 #[test]
456 fn upsert_batch_constant_matches_expected_value() {
457 assert_eq!(MAX_UPSERT_BATCH_SIZE, 100_000);
458 }
459
460 #[test]
461 fn scroll_batch_constant_matches_expected_value() {
462 assert_eq!(MAX_SCROLL_BATCH_SIZE, 10_000);
463 }
464
465 #[test]
466 fn bulk_delete_batch_constant_matches_expected_value() {
467 assert_eq!(MAX_BULK_DELETE_SIZE, 10_000);
468 }
469
470 #[test]
471 fn upsert_batch_limit_is_larger_than_delete_limit() {
472 assert!(MAX_UPSERT_BATCH_SIZE > MAX_BULK_DELETE_SIZE);
474 }
475}