feat: add async item service wrapper

Co-authored-by: aider (openai/andrew/openrouter/google/gemini-2.5-pro) <aider@aider.chat>
This commit is contained in:
Andrew Phillips
2025-08-25 12:37:18 -03:00
parent 7b2fb257eb
commit 7700026d87
3 changed files with 95 additions and 1 deletions

View File

@@ -0,0 +1,93 @@
use crate::core::error::CoreError;
use crate::core::item_service::ItemService;
use crate::core::types::{ItemWithContent, ItemWithMeta};
use rusqlite::Connection;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
use tokio::sync::Mutex;
/// An asynchronous wrapper around the `ItemService` for use in async contexts like the web server.
/// It uses `tokio::task::spawn_blocking` to run synchronous database and filesystem operations
/// on a dedicated thread pool, preventing them from blocking the async runtime.
#[allow(dead_code)]
pub struct AsyncItemService {
data_path: PathBuf,
db: Arc<Mutex<Connection>>,
}
#[allow(dead_code)]
impl AsyncItemService {
pub fn new(data_path: PathBuf, db: Arc<Mutex<Connection>>) -> Self {
Self { data_path, db }
}
pub async fn get_item(&self, id: i64) -> Result<ItemWithMeta, CoreError> {
let data_path = self.data_path.clone();
let conn = self.db.lock().await;
tokio::task::spawn_blocking(move || {
let item_service = ItemService::new(data_path);
item_service.get_item(&conn, id)
})
.await
.unwrap() // Propagate panics from spawn_blocking
}
pub async fn get_item_content(&self, id: i64) -> Result<ItemWithContent, CoreError> {
let data_path = self.data_path.clone();
let conn = self.db.lock().await;
tokio::task::spawn_blocking(move || {
let item_service = ItemService::new(data_path);
item_service.get_item_content(&conn, id)
})
.await
.unwrap()
}
pub async fn find_item(
&self,
ids: Vec<i64>,
tags: Vec<String>,
meta: HashMap<String, String>,
) -> Result<ItemWithMeta, CoreError> {
let data_path = self.data_path.clone();
let conn = self.db.lock().await;
tokio::task::spawn_blocking(move || {
let item_service = ItemService::new(data_path);
item_service.find_item(&conn, &ids, &tags, &meta)
})
.await
.unwrap()
}
pub async fn list_items(
&self,
tags: Vec<String>,
meta: HashMap<String, String>,
) -> Result<Vec<ItemWithMeta>, CoreError> {
let data_path = self.data_path.clone();
let conn = self.db.lock().await;
tokio::task::spawn_blocking(move || {
let item_service = ItemService::new(data_path);
item_service.list_items(&conn, &tags, &meta)
})
.await
.unwrap()
}
pub async fn delete_item(&self, id: i64) -> Result<(), CoreError> {
let data_path = self.data_path.clone();
let mut conn = self.db.lock().await;
tokio::task::spawn_blocking(move || {
let item_service = ItemService::new(data_path);
item_service.delete_item(&mut conn, id)
})
.await
.unwrap()
}
}

View File

@@ -1,3 +1,4 @@
pub mod async_item_service;
pub mod compression_service;
pub mod error;
pub mod item_service;