Repository navigation
Expand file tree
/
Copy pathapi.rs
More file actions
138 lines (120 loc) · 5.1 KB
/
Copy pathapi.rs
File metadata and controls
138 lines (120 loc) · 5.1 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
use axum::{
extract::{Path, Query, State},
http::StatusCode,
response::{IntoResponse, Json},
routing::get,
Router,
};
use serde::Deserialize;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use tower_http::cors::CorsLayer;
use crate::store::MemoryStore;
use crate::types::{MemoryInput, MemoryKind};
#[derive(Clone)]
struct AppState {
store: Arc<Mutex<MemoryStore>>,
}
/// Runs `f` against the store on a blocking-pool thread, so a query doesn't stall the
/// async executor (rusqlite is synchronous — every handler here does real disk I/O).
async fn with_store<F, R>(state: &AppState, f: F) -> R
where
F: FnOnce(&MemoryStore) -> R + Send + 'static,
R: Send + 'static,
{
let store = state.store.clone();
tokio::task::spawn_blocking(move || {
let guard = store.lock().unwrap_or_else(|e| e.into_inner());
f(&guard)
})
.await
.expect("blocking task panicked")
}
pub async fn serve_api(project_dir: PathBuf, port: u16) {
let store = MemoryStore::open_in_project(&project_dir)
.expect("Failed to open memory store. Run `pmem init` first.");
let state = AppState { store: Arc::new(Mutex::new(store)) };
let app = Router::new()
.route("/api/health", get(|| async { Json(serde_json::json!({"status": "ok"})) }))
.route("/api/memories", get(list_memories).post(add_memory))
.route("/api/memories/{id}", get(get_memory).put(update_memory).delete(delete_memory))
.route("/api/search", get(search_memories))
.route("/api/stats", get(stats))
.route("/api/tags", get(tags))
.layer(CorsLayer::permissive())
.with_state(state);
let host = std::env::var("PMEM_HOST").unwrap_or_else(|_| "127.0.0.1".to_string());
let addr = format!("{host}:{port}");
println!(" REST API: http://{addr}/api");
let listener = tokio::net::TcpListener::bind(&addr)
.await
.expect("Failed to bind port");
axum::serve(listener, app).await.expect("Server failed");
}
#[derive(Deserialize)]
struct ListParams {
kind: Option<String>,
limit: Option<usize>,
}
async fn list_memories(State(state): State<AppState>, Query(p): Query<ListParams>) -> impl IntoResponse {
let kind = p.kind.and_then(|k| k.parse::<MemoryKind>().ok());
let limit = p.limit.unwrap_or(50);
match with_store(&state, move |store| store.list(kind, limit)).await {
Ok(memories) => Json(memories).into_response(),
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
}
}
async fn get_memory(State(state): State<AppState>, Path(id): Path<String>) -> impl IntoResponse {
match with_store(&state, move |store| store.get(&id)).await {
Ok(Some(m)) => Json(m).into_response(),
Ok(None) => (StatusCode::NOT_FOUND, "memory not found").into_response(),
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
}
}
async fn add_memory(State(state): State<AppState>, Json(input): Json<MemoryInput>) -> impl IntoResponse {
match with_store(&state, move |store| store.add(input)).await {
Ok(m) => (StatusCode::CREATED, Json(m)).into_response(),
Err(e) => (StatusCode::BAD_REQUEST, e.to_string()).into_response(),
}
}
async fn update_memory(State(state): State<AppState>, Path(id): Path<String>, Json(input): Json<MemoryInput>) -> impl IntoResponse {
match with_store(&state, move |store| store.update(&id, input)).await {
Ok(Some(m)) => Json(m).into_response(),
Ok(None) => (StatusCode::NOT_FOUND, "memory not found").into_response(),
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
}
}
async fn delete_memory(State(state): State<AppState>, Path(id): Path<String>) -> impl IntoResponse {
match with_store(&state, move |store| store.delete(&id)).await {
Ok(true) => StatusCode::NO_CONTENT.into_response(),
Ok(false) => (StatusCode::NOT_FOUND, "memory not found").into_response(),
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
}
}
#[derive(Deserialize)]
struct SearchParams {
q: String,
limit: Option<usize>,
}
async fn search_memories(State(state): State<AppState>, Query(p): Query<SearchParams>) -> impl IntoResponse {
let limit = p.limit.unwrap_or(10);
match with_store(&state, move |store| store.fuzzy_search(&p.q, limit)).await {
Ok(results) => Json(results).into_response(),
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
}
}
async fn stats(State(state): State<AppState>) -> impl IntoResponse {
Json(with_store(&state, |store| {
let count = store.count().unwrap_or(0);
let by_kind = store.count_by_kind().unwrap_or_default();
let tags = store.list_tags().unwrap_or_default();
serde_json::json!({
"total": count,
"by_kind": by_kind.iter().map(|(k, c)| (k.to_string(), c)).collect::<Vec<_>>(),
"tags": tags,
})
}).await)
}
async fn tags(State(state): State<AppState>) -> impl IntoResponse {
Json(with_store(&state, |store| store.list_tags().unwrap_or_default()).await)
}