Repository navigation
Expand file tree
/
Copy pathapi.rs
More file actions
250 lines (239 loc) · 7.01 KB
/
Copy pathapi.rs
File metadata and controls
250 lines (239 loc) · 7.01 KB
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
/// Rust guideline compliant 2026-06-17
use crate::embedding::FastEmbedProvider;
use crate::index::{Index, SearchMode};
use crate::okf::OkfDocumentBuilder;
use crate::schema::{
DeleteRequest, DocumentInput, SearchModeRequest, SearchRequest, SearchResponse, StatusResponse,
};
use axum::extract::State;
use axum::http::StatusCode;
use axum::routing::{get, post};
use axum::{Json, Router};
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use utoipa::OpenApi;
/// Shared HTTP API state.
#[derive(Clone)]
pub struct ApiState {
pub index: Arc<Mutex<Index>>,
}
/// Builds the HTTP router.
pub fn router(state: ApiState) -> Router {
Router::new()
.route("/health", get(health))
.route("/openapi.json", get(openapi_json))
.route("/search", post(search))
.route("/documents", post(index_documents))
.route("/documents/update", post(update_documents))
.route("/documents/delete", post(delete_documents))
.with_state(state)
}
#[utoipa::path(
get,
path = "/health",
responses(
(status = 200, description = "Service is ready", body = StatusResponse)
)
)]
pub async fn health() -> (StatusCode, Json<StatusResponse>) {
(
StatusCode::OK,
Json(StatusResponse {
status: "ok".to_string(),
}),
)
}
#[utoipa::path(
get,
path = "/openapi.json",
responses(
(status = 200, description = "OpenAPI schema")
)
)]
pub async fn openapi_json() -> (StatusCode, Json<serde_json::Value>) {
let doc = crate::openapi::ApiDoc::openapi();
let body = serde_json::to_value(doc).unwrap_or_else(|_| serde_json::json!({}));
(StatusCode::OK, Json(body))
}
#[utoipa::path(
post,
path = "/search",
request_body = SearchRequest,
responses(
(status = 200, description = "Search results", body = SearchResponse)
)
)]
pub async fn search(
State(state): State<ApiState>,
Json(req): Json<SearchRequest>,
) -> Result<Json<SearchResponse>, (StatusCode, Json<StatusResponse>)> {
let mode = match req.mode.unwrap_or(SearchModeRequest::Hybrid) {
SearchModeRequest::Lexical => SearchMode::Lexical,
SearchModeRequest::Vector => SearchMode::Vector,
SearchModeRequest::Hybrid => SearchMode::Hybrid,
};
let index = state.index.lock().map_err(|_| {
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(StatusResponse {
status: "index lock poisoned".to_string(),
}),
)
})?;
let top_k = req.top_k.unwrap_or(10);
let offset = req.offset.unwrap_or(0);
let (results, plan, total_hits) = index
.search_advanced(&req.query, mode, top_k, offset, req.filter.as_ref())
.map_err(|err| {
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(StatusResponse {
status: err.to_string(),
}),
)
})?;
Ok(Json(SearchResponse {
results,
plan,
total_hits,
offset,
top_k,
}))
}
fn build_document(doc: DocumentInput) -> crate::okf::OkfDocument {
let mut builder = OkfDocumentBuilder::new(
PathBuf::from(&doc.bundle_path),
PathBuf::from(&doc.file_path),
)
.body(doc.body);
for (k, v) in doc.frontmatter {
builder = builder.frontmatter_value(k, v);
}
builder.build()
}
#[utoipa::path(
post,
path = "/documents",
request_body = Vec<DocumentInput>,
responses(
(status = 200, description = "Documents indexed", body = StatusResponse)
)
)]
pub async fn index_documents(
State(state): State<ApiState>,
Json(docs): Json<Vec<DocumentInput>>,
) -> Result<Json<StatusResponse>, (StatusCode, Json<StatusResponse>)> {
let built = docs.into_iter().map(build_document).collect::<Vec<_>>();
let mut index = state.index.lock().map_err(|_| {
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(StatusResponse {
status: "index lock poisoned".to_string(),
}),
)
})?;
index.index_documents(built).map_err(|err| {
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(StatusResponse {
status: err.to_string(),
}),
)
})?;
Ok(Json(StatusResponse {
status: "ok".to_string(),
}))
}
#[utoipa::path(
post,
path = "/documents/update",
request_body = Vec<DocumentInput>,
responses(
(status = 200, description = "Documents updated", body = StatusResponse)
)
)]
pub async fn update_documents(
State(state): State<ApiState>,
Json(docs): Json<Vec<DocumentInput>>,
) -> Result<Json<StatusResponse>, (StatusCode, Json<StatusResponse>)> {
let built = docs.into_iter().map(build_document).collect::<Vec<_>>();
let mut index = state.index.lock().map_err(|_| {
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(StatusResponse {
status: "index lock poisoned".to_string(),
}),
)
})?;
index.update_documents(built).map_err(|err| {
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(StatusResponse {
status: err.to_string(),
}),
)
})?;
Ok(Json(StatusResponse {
status: "ok".to_string(),
}))
}
#[utoipa::path(
post,
path = "/documents/delete",
request_body = DeleteRequest,
responses(
(status = 200, description = "Documents deleted", body = StatusResponse)
)
)]
pub async fn delete_documents(
State(state): State<ApiState>,
Json(req): Json<DeleteRequest>,
) -> Result<Json<StatusResponse>, (StatusCode, Json<StatusResponse>)> {
let mut index = state.index.lock().map_err(|_| {
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(StatusResponse {
status: "index lock poisoned".to_string(),
}),
)
})?;
if !req.logical_keys.is_empty() {
index
.delete_logical_keys(&req.logical_keys)
.map_err(|err| {
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(StatusResponse {
status: err.to_string(),
}),
)
})?;
}
if !req.doc_ids.is_empty() {
index.delete_doc_ids(&req.doc_ids).map_err(|err| {
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(StatusResponse {
status: err.to_string(),
}),
)
})?;
}
Ok(Json(StatusResponse {
status: "ok".to_string(),
}))
}
/// Runs the HTTP API server.
pub async fn serve(index: Index, bind: String) -> anyhow::Result<()> {
let state = ApiState {
index: Arc::new(Mutex::new(index)),
};
let app = router(state);
let listener = tokio::net::TcpListener::bind(bind).await?;
axum::serve(listener, app).await?;
Ok(())
}
/// Creates the default FastEmbed provider.
pub fn default_provider() -> anyhow::Result<FastEmbedProvider> {
FastEmbedProvider::new_default()
}