velesdb-server 5.0.0

REST API server for VelesDB vector database
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
//! Graph HTTP handlers for VelesDB REST API.
//!
//! All graph operations are routed through `AppState.db.get_graph_collection()`.
//! No separate GraphService state — graph data persists via GraphCollection/GraphEngine.
//!
//! Extended handlers (parity endpoints) live in [`super::handlers_extended`].

use std::sync::Arc;

use axum::{
    extract::{Path, Query, State},
    http::StatusCode,
    response::IntoResponse,
    Json,
};
use velesdb_core::collection::graph::{GraphEdge, TraversalConfig};
use velesdb_core::observer::QueryOperationKind;

use crate::handlers::helpers::{auto_core_error_response, run_blocking, run_blocking_typed};
use crate::types::ErrorResponse;
use crate::AppState;

use super::types::{
    AddEdgeRequest, AddEdgesBatchRequest, AddEdgesBatchResponse, DegreeResponse, EdgeQueryParams,
    EdgeResponse, EdgesResponse, TraversalStats, TraverseRequest, TraverseResponse,
};

/// Shared graph preamble: record metric and resolve collection.
///
/// Mirrors [`super::super::search::search_preamble`] for graph handlers.
/// `GraphCollection` does not expose guard rails, so only the metrics
/// recording and collection resolution steps are performed.
#[allow(clippy::result_large_err)]
pub(super) fn graph_preamble(
    state: &AppState,
    name: &str,
) -> Result<velesdb_core::GraphCollection, (StatusCode, Json<ErrorResponse>)> {
    state.onboarding_metrics.record_graph_request();
    get_graph_collection_or_404(state, name)
}

/// Resolves a `GraphCollection` by name.
///
/// # Returns
///
/// * `Ok(collection)` if a graph collection with this name exists.
/// * `Err(404 Not Found)` if no collection with this name exists.
/// * `Err(409 Conflict)` if a collection exists with this name but is not
///   a graph collection (type mismatch with vector or metadata collection).
///
/// # Contract
///
/// This function previously auto-created a schemaless graph collection
/// on first use. That behaviour is retired (F-05): a missing graph
/// collection now yields a 404 response instead of being created
/// silently. Callers must issue `POST /collections` with
/// `collection_type = "graph"` before targeting graph endpoints.
pub(super) fn get_graph_collection_or_404(
    state: &AppState,
    name: &str,
) -> Result<velesdb_core::GraphCollection, (StatusCode, Json<ErrorResponse>)> {
    if let Some(c) = state.db.get_graph_collection(name) {
        return Ok(c);
    }

    // Check if a non-graph collection exists with this name (type mismatch → 409).
    if state.db.get_vector_collection(name).is_some()
        || state.db.get_metadata_collection(name).is_some()
    {
        return Err((
            StatusCode::CONFLICT,
            Json(ErrorResponse {
                error: format!(
                    "Collection '{name}' exists but is not a graph collection. \
                     Use /collections/{name}/graph only on graph-typed collections.",
                ),
                code: None,
            }),
        ));
    }

    // PR #586 Devin fix: propagate `VELES-002 CollectionNotFound` so
    // typed-error clients surface `CollectionNotFoundError` instead of
    // a status-derived `'NOT_FOUND'` string. The "create it first"
    // hint stays in the message for human operators.
    let err = velesdb_core::Error::CollectionNotFound(name.to_string());
    Err((
        StatusCode::NOT_FOUND,
        Json(ErrorResponse {
            error: format!(
                "{err}. Create it first with \
                 POST /collections and collection_type = \"graph\".",
            ),
            code: Some(err.code().to_string()),
        }),
    ))
}

/// Shared graph preamble for **read** operations: resolves the collection via
/// [`graph_preamble`], then routes the read through the control-plane gate
/// (CORE-2). Graph reads have no metadata-filter channel to narrow, so a
/// denied or scope-narrowed decision refuses the request (fail closed)
/// rather than running it unfiltered.
///
/// Mirrors the gate `MATCH` (`handlers::match_query`) and embedding
/// [`super::handlers_extended::graph_search`] already apply — centralized
/// here so every plain REST graph read is governed the same way instead of
/// each handler wiring the check individually.
#[allow(clippy::result_large_err)]
pub(super) fn graph_read_preamble(
    state: &AppState,
    name: &str,
    operation: QueryOperationKind,
) -> Result<velesdb_core::GraphCollection, (StatusCode, Json<ErrorResponse>)> {
    let coll = graph_preamble(state, name)?;
    match state.db.authorize_read(name, operation, None, None) {
        Ok(None) => Ok(coll),
        Ok(Some(_)) | Err(_) => Err((
            StatusCode::FORBIDDEN,
            Json(ErrorResponse {
                error: "Read denied by governance policy".to_string(),
                code: None,
            }),
        )),
    }
}

/// Get edges from a collection's graph filtered by label.
#[utoipa::path(
    get,
    path = "/collections/{name}/graph/edges",
    params(("name" = String, Path, description = "Collection name"), EdgeQueryParams),
    responses(
        (status = 200, description = "Edges retrieved successfully", body = EdgesResponse),
        (status = 400, description = "Missing required 'label' query parameter", body = ErrorResponse),
        (status = 404, description = "Collection not found", body = ErrorResponse),
        (status = 500, description = "Internal server error", body = ErrorResponse)
    ),
    tag = "graph"
)]
pub async fn get_edges(
    Path(name): Path<String>,
    Query(params): Query<EdgeQueryParams>,
    State(state): State<Arc<AppState>>,
) -> Result<Json<EdgesResponse>, (StatusCode, Json<ErrorResponse>)> {
    let label = params.label.ok_or_else(|| {
        (
            StatusCode::BAD_REQUEST,
            Json(ErrorResponse {
                error: "Query parameter 'label' is required. Listing all edges requires pagination (not yet implemented).".to_string(),
                code: None,
            }),
        )
    })?;

    let coll = graph_read_preamble(&state, &name, QueryOperationKind::GraphTraversal)?;

    // Edge listing takes graph store locks — run it on the blocking pool.
    let raw_edges = run_blocking_typed(move || coll.get_edges(Some(&label))).await?;

    let edges: Vec<EdgeResponse> = raw_edges
        .into_iter()
        .map(|e| EdgeResponse {
            id: e.id(),
            source: e.source(),
            target: e.target(),
            label: e.label().to_string(),
            properties: serde_json::to_value(e.properties()).unwrap_or_default(),
        })
        .collect();

    let count = edges.len();
    Ok(Json(EdgesResponse { edges, count }))
}

/// The write-result match [`add_edge`] and [`add_edges_batch`] share: the
/// blocking-pool outcome routed through `auto_core_error_response` (so e.g.
/// `EdgeExists` surfaces as 409 + VELES-019, never a 500 string), success
/// shaped by the caller. One copy, so the two handlers cannot drift on the
/// error route.
fn created_or_core_error<T>(
    outcome: Result<Result<T, velesdb_core::Error>, axum::response::Response>,
    success: impl FnOnce(T) -> axum::response::Response,
) -> axum::response::Response {
    match outcome {
        Ok(Ok(value)) => success(value),
        Ok(Err(e)) => auto_core_error_response(&e),
        Err(resp) => resp,
    }
}

/// Add an edge to a collection's graph.
#[utoipa::path(
    post,
    path = "/collections/{name}/graph/edges",
    request_body = AddEdgeRequest,
    responses(
        (status = 201, description = "Edge added successfully"),
        (status = 400, description = "Invalid request", body = ErrorResponse),
        (status = 404, description = "Collection not found, or source/target node has no stored payload (VELES-022 NodeNotFound)", body = ErrorResponse),
        (status = 500, description = "Internal server error", body = ErrorResponse)
    ),
    tag = "graph"
)]
pub async fn add_edge(
    Path(name): Path<String>,
    State(state): State<Arc<AppState>>,
    Json(request): Json<AddEdgeRequest>,
) -> axum::response::Response {
    let edge = match build_edge(request) {
        Ok(e) => e,
        Err(resp) => return resp.into_response(),
    };

    let coll = match graph_preamble(&state, &name) {
        Ok(c) => c,
        Err(resp) => return resp.into_response(),
    };

    // Edge insertion takes write locks and persists — run it on the blocking
    // pool. Route the core error through `auto_core_error_response` so e.g.
    // `EdgeExists` surfaces as 409 + VELES-019 instead of a generic 500 string.
    created_or_core_error(run_blocking(move || coll.add_edge(edge)).await, |()| {
        StatusCode::CREATED.into_response()
    })
}

/// Converts an [`AddEdgeRequest`] into a core [`GraphEdge`], validating the
/// properties shape and edge fields. Shared by [`add_edge`] and
/// [`add_edges_batch`].
#[allow(clippy::result_large_err)]
fn build_edge(request: AddEdgeRequest) -> Result<GraphEdge, (StatusCode, Json<ErrorResponse>)> {
    let properties: std::collections::HashMap<String, serde_json::Value> = match request.properties
    {
        serde_json::Value::Object(map) => map.into_iter().collect(),
        serde_json::Value::Null => std::collections::HashMap::new(),
        _ => {
            return Err((
                StatusCode::BAD_REQUEST,
                Json(ErrorResponse {
                    error: "Properties must be an object or null".to_string(),
                    code: None,
                }),
            ));
        }
    };

    let edge = GraphEdge::new(request.id, request.source, request.target, &request.label)
        .map_err(|e| {
            (
                StatusCode::BAD_REQUEST,
                Json(ErrorResponse {
                    error: format!("Invalid edge: {e}"),
                    code: None,
                }),
            )
        })?
        .with_properties(properties);
    Ok(edge)
}

/// Add multiple edges to a collection's graph in one batched operation.
#[utoipa::path(
    post,
    path = "/collections/{name}/graph/edges/batch",
    request_body = AddEdgesBatchRequest,
    responses(
        (status = 201, description = "Edges added successfully", body = AddEdgesBatchResponse),
        (status = 400, description = "Invalid request", body = ErrorResponse),
        (status = 404, description = "Collection not found, or a source/target node has no stored payload (VELES-022 NodeNotFound) — the whole batch is rejected", body = ErrorResponse),
        (status = 500, description = "Internal server error", body = ErrorResponse)
    ),
    tag = "graph"
)]
pub async fn add_edges_batch(
    Path(name): Path<String>,
    State(state): State<Arc<AppState>>,
    Json(request): Json<AddEdgesBatchRequest>,
) -> axum::response::Response {
    let edges = match request
        .edges
        .into_iter()
        .map(build_edge)
        .collect::<Result<Vec<_>, _>>()
    {
        Ok(edges) => edges,
        Err(resp) => return resp.into_response(),
    };

    let coll = match graph_preamble(&state, &name) {
        Ok(c) => c,
        Err(resp) => return resp.into_response(),
    };

    // Batch edge insertion takes write locks and persists — run it on the
    // blocking pool. Route the core error through `auto_core_error_response`
    // so e.g. `EdgeExists` surfaces as 409 + VELES-019 instead of a 500 string.
    created_or_core_error(
        run_blocking(move || coll.add_edges_batch(edges)).await,
        |added| (StatusCode::CREATED, Json(AddEdgesBatchResponse { added })).into_response(),
    )
}

/// Traverse the graph using BFS or DFS from a source node.
#[utoipa::path(
    post,
    path = "/collections/{name}/graph/traverse",
    request_body = TraverseRequest,
    responses(
        (status = 200, description = "Traversal completed successfully", body = TraverseResponse),
        (status = 400, description = "Invalid request", body = ErrorResponse),
        (status = 404, description = "Collection not found", body = ErrorResponse),
        (status = 500, description = "Internal server error", body = ErrorResponse)
    ),
    tag = "graph"
)]
pub async fn traverse_graph(
    Path(name): Path<String>,
    State(state): State<Arc<AppState>>,
    Json(request): Json<TraverseRequest>,
) -> Result<Json<TraverseResponse>, (StatusCode, Json<ErrorResponse>)> {
    let coll = graph_read_preamble(&state, &name, QueryOperationKind::GraphTraversal)?;

    let use_bfs = match request.strategy.to_lowercase().as_str() {
        "bfs" => true,
        "dfs" => false,
        _ => {
            return Err((
                StatusCode::BAD_REQUEST,
                Json(ErrorResponse {
                    error: format!(
                        "Invalid strategy '{}'. Use 'bfs' or 'dfs'.",
                        request.strategy
                    ),
                    code: None,
                }),
            ));
        }
    };

    let limit = request.limit;
    let source = request.source;
    let config = TraversalConfig::with_range(1, request.max_depth)
        .with_limit(limit)
        .with_rel_types(request.rel_types);

    // Traversal is synchronous, lock-taking core code — run it on the
    // blocking pool so the async workers stay responsive.
    let raw_results = run_blocking_typed(move || {
        if use_bfs {
            coll.traverse_bfs(source, &config)
        } else {
            coll.traverse_dfs(source, &config)
        }
    })
    .await?;

    let results: Vec<super::types::TraversalResultItem> = raw_results
        .into_iter()
        .map(|r| super::types::TraversalResultItem {
            target_id: r.target_id,
            depth: r.depth,
            path: r.path,
        })
        .collect();

    let depth_reached = results.iter().map(|r| r.depth).max().unwrap_or(0);
    let visited = results.len();
    let has_more = visited >= limit;

    Ok(Json(TraverseResponse {
        results,
        has_more,
        stats: TraversalStats {
            visited,
            depth_reached,
        },
    }))
}

/// Get the degree (in and out) of a specific node.
#[utoipa::path(
    get,
    path = "/collections/{name}/graph/nodes/{node_id}/degree",
    params(
        ("name" = String, Path, description = "Collection name"),
        ("node_id" = String, Path, description = "Node ID (u64 as a string; precision-safe above 2^53-1)", pattern = "^[0-9]+$")
    ),
    responses(
        (status = 200, description = "Degree retrieved successfully", body = DegreeResponse),
        (status = 404, description = "Collection not found", body = ErrorResponse),
        (status = 500, description = "Internal server error", body = ErrorResponse)
    ),
    tag = "graph"
)]
pub async fn get_node_degree(
    Path((name, node_id)): Path<(String, u64)>,
    State(state): State<Arc<AppState>>,
) -> Result<Json<DegreeResponse>, (StatusCode, Json<ErrorResponse>)> {
    let coll = graph_read_preamble(&state, &name, QueryOperationKind::GraphTraversal)?;
    // Degree lookup takes edge-store shard locks — run it on the blocking pool.
    let (in_degree, out_degree) = run_blocking_typed(move || coll.node_degree(node_id)).await?;
    Ok(Json(DegreeResponse {
        in_degree,
        out_degree,
    }))
}