First batch of smart stuff

This commit is contained in:
2025-12-25 23:53:12 +00:00
parent 4cb398869d
commit 58de25e5bc
34 changed files with 2974 additions and 74 deletions

View File

@@ -1,3 +1,5 @@
#[cfg(feature = "smart-features")]
use notes_infra::factory::{EmbeddingProvider, VectorProvider};
use std::env;
/// Server configuration
@@ -9,6 +11,11 @@ pub struct Config {
pub session_secret: String,
pub cors_allowed_origins: Vec<String>,
pub allow_registration: bool,
#[cfg(feature = "smart-features")]
pub embedding_provider: EmbeddingProvider,
#[cfg(feature = "smart-features")]
pub vector_provider: VectorProvider,
pub broker_url: String,
}
impl Default for Config {
@@ -21,6 +28,14 @@ impl Default for Config {
.to_string(),
cors_allowed_origins: vec!["http://localhost:5173".to_string()],
allow_registration: true,
#[cfg(feature = "smart-features")]
embedding_provider: EmbeddingProvider::FastEmbed,
#[cfg(feature = "smart-features")]
vector_provider: VectorProvider::Qdrant {
url: "http://localhost:6334".to_string(),
collection: "notes".to_string(),
},
broker_url: "nats://localhost:4222".to_string(),
}
}
}
@@ -56,6 +71,24 @@ impl Config {
.map(|s| s.to_lowercase() == "true")
.unwrap_or(true);
#[cfg(feature = "smart-features")]
let embedding_provider = match env::var("EMBEDDING_PROVIDER").unwrap_or_default().as_str() {
// Future: "ollama" => EmbeddingProvider::Ollama(...),
_ => EmbeddingProvider::FastEmbed,
};
#[cfg(feature = "smart-features")]
let vector_provider = match env::var("VECTOR_PROVIDER").unwrap_or_default().as_str() {
// Future: "postgres" => ...
_ => VectorProvider::Qdrant {
url: env::var("QDRANT_URL").unwrap_or_else(|_| "http://localhost:6334".to_string()),
collection: env::var("QDRANT_COLLECTION").unwrap_or_else(|_| "notes".to_string()),
},
};
let broker_url =
env::var("BROKER_URL").unwrap_or_else(|_| "nats://localhost:4222".to_string());
Self {
host,
port,
@@ -63,6 +96,11 @@ impl Config {
session_secret,
cors_allowed_origins,
allow_registration,
#[cfg(feature = "smart-features")]
embedding_provider,
#[cfg(feature = "smart-features")]
vector_provider,
broker_url,
}
}
}

View File

@@ -172,3 +172,23 @@ impl From<notes_domain::NoteVersion> for NoteVersionResponse {
pub struct ConfigResponse {
pub allow_registration: bool,
}
/// Note Link response DTO
#[derive(Debug, Serialize)]
pub struct NoteLinkResponse {
pub source_note_id: Uuid,
pub target_note_id: Uuid,
pub score: f32,
pub created_at: DateTime<Utc>,
}
impl From<notes_domain::entities::NoteLink> for NoteLinkResponse {
fn from(link: notes_domain::entities::NoteLink) -> Self {
Self {
source_note_id: link.source_note_id,
target_note_id: link.target_note_id,
score: link.score,
created_at: link.created_at,
}
}
}

View File

@@ -55,7 +55,9 @@ impl IntoResponse for ApiError {
DomainError::Unauthorized(_) => StatusCode::FORBIDDEN,
DomainError::RepositoryError(_) => StatusCode::INTERNAL_SERVER_ERROR,
DomainError::RepositoryError(_) | DomainError::InfrastructureError(_) => {
StatusCode::INTERNAL_SERVER_ERROR
}
};
(

View File

@@ -43,6 +43,8 @@ async fn main() -> anyhow::Result<()> {
tracing::info!("Connecting to database: {}", config.database_url);
let db_config = DatabaseConfig::new(&config.database_url);
#[cfg(feature = "smart-features")]
use notes_infra::factory::build_link_repository;
use notes_infra::factory::{
build_database_pool, build_note_repository, build_session_store, build_tag_repository,
build_user_repository,
@@ -52,7 +54,6 @@ async fn main() -> anyhow::Result<()> {
.map_err(|e| anyhow::anyhow!(e))?;
// Run migrations
// The factory/infra layer abstracts the database type
if let Err(e) = run_migrations(&pool).await {
tracing::warn!(
"Migration error (might be expected if not implemented for this DB): {}",
@@ -73,6 +74,10 @@ async fn main() -> anyhow::Result<()> {
let user_repo = build_user_repository(&pool)
.await
.map_err(|e| anyhow::anyhow!(e))?;
#[cfg(feature = "smart-features")]
let link_repo = build_link_repository(&pool)
.await
.map_err(|e| anyhow::anyhow!(e))?;
// Create services
use notes_domain::{NoteService, TagService, UserService};
@@ -80,14 +85,28 @@ async fn main() -> anyhow::Result<()> {
let tag_service = Arc::new(TagService::new(tag_repo.clone()));
let user_service = Arc::new(UserService::new(user_repo.clone()));
// Connect to NATS
// Connect to NATS
#[cfg(feature = "smart-features")]
let nats_client = {
tracing::info!("Connecting to NATS: {}", config.broker_url);
async_nats::connect(&config.broker_url)
.await
.map_err(|e| anyhow::anyhow!("NATS connection failed: {}", e))?
};
// Create application state
let state = AppState::new(
note_repo,
tag_repo,
user_repo.clone(),
#[cfg(feature = "smart-features")]
link_repo,
note_service,
tag_service,
user_service,
#[cfg(feature = "smart-features")]
nats_client,
config.clone(),
);
@@ -108,10 +127,8 @@ async fn main() -> anyhow::Result<()> {
.with_secure(false) // Set to true in production with HTTPS
.with_expiry(Expiry::OnInactivity(Duration::seconds(60 * 60 * 24 * 7))); // 7 days
// Auth layer
let auth_layer = AuthManagerLayerBuilder::new(backend, session_layer).build();
// Parse CORS origins
let mut cors = CorsLayer::new()
.allow_methods([
axum::http::Method::GET,
@@ -127,7 +144,6 @@ async fn main() -> anyhow::Result<()> {
])
.allow_credentials(true);
// Add allowed origins
let mut allowed_origins = Vec::new();
for origin in &config.cors_allowed_origins {
tracing::debug!("Allowing CORS origin: {}", origin);
@@ -142,7 +158,6 @@ async fn main() -> anyhow::Result<()> {
cors = cors.allow_origin(allowed_origins);
}
// Build the application
let app = Router::new()
.nest("/api/v1", routes::api_v1_router())
.layer(auth_layer)
@@ -150,7 +165,6 @@ async fn main() -> anyhow::Result<()> {
.layer(TraceLayer::new_for_http())
.with_state(state);
// Start the server
let addr = format!("{}:{}", config.host, config.port);
let listener = tokio::net::TcpListener::bind(&addr).await?;

View File

@@ -15,7 +15,7 @@ use crate::state::AppState;
/// Create the API v1 router
pub fn api_v1_router() -> Router<AppState> {
Router::new()
let router = Router::new()
// Auth routes
.route("/auth/register", post(auth::register))
.route("/auth/login", post(auth::login))
@@ -29,7 +29,12 @@ pub fn api_v1_router() -> Router<AppState> {
.patch(notes::update_note)
.delete(notes::delete_note),
)
.route("/notes/{id}/versions", get(notes::list_note_versions))
.route("/notes/{id}/versions", get(notes::list_note_versions));
#[cfg(feature = "smart-features")]
let router = router.route("/notes/{id}/related", get(notes::get_related_notes));
router
// Search route
.route("/search", get(notes::search_notes))
// Import/Export routes

View File

@@ -82,6 +82,21 @@ pub async fn create_note(
let note = state.note_service.create_note(domain_req).await?;
// Publish event
#[cfg(feature = "smart-features")]
{
let payload = serde_json::to_vec(&note).unwrap_or_default();
if let Err(e) = state
.nats_client
.publish("notes.updated", payload.into())
.await
{
tracing::error!("Failed to publish notes.updated event: {}", e);
} else {
tracing::info!("Published notes.updated event for note {}", note.id);
}
}
Ok((StatusCode::CREATED, Json(NoteResponse::from(note))))
}
@@ -137,6 +152,21 @@ pub async fn update_note(
let note = state.note_service.update_note(domain_req).await?;
// Publish event
#[cfg(feature = "smart-features")]
{
let payload = serde_json::to_vec(&note).unwrap_or_default();
if let Err(e) = state
.nats_client
.publish("notes.updated", payload.into())
.await
{
tracing::error!("Failed to publish notes.updated event: {}", e);
} else {
tracing::info!("Published notes.updated event for note {}", note.id);
}
}
Ok(Json(NoteResponse::from(note)))
}
@@ -160,7 +190,7 @@ pub async fn delete_note(
}
/// Search notes
/// GET /api/v1/search
/// GET /api/v1/notes/search
pub async fn search_notes(
State(state): State<AppState>,
auth: AuthSession<AuthBackend>,
@@ -201,3 +231,33 @@ pub async fn list_note_versions(
Ok(Json(response))
}
/// Get related notes
/// GET /api/v1/notes/:id/related
/// Get related notes
/// GET /api/v1/notes/:id/related
#[cfg(feature = "smart-features")]
pub async fn get_related_notes(
State(state): State<AppState>,
auth: AuthSession<AuthBackend>,
Path(id): Path<Uuid>,
) -> ApiResult<Json<Vec<crate::dto::NoteLinkResponse>>> {
let user = auth
.user
.ok_or(ApiError::Domain(notes_domain::DomainError::Unauthorized(
"Login required".to_string(),
)))?;
let user_id = user.id();
// Verify access to the source note
state.note_service.get_note(id, user_id).await?;
// Get links
let links = state.link_repo.get_links_for_note(id).await?;
let response: Vec<crate::dto::NoteLinkResponse> = links
.into_iter()
.map(crate::dto::NoteLinkResponse::from)
.collect();
Ok(Json(response))
}

View File

@@ -11,9 +11,13 @@ pub struct AppState {
pub note_repo: Arc<dyn NoteRepository>,
pub tag_repo: Arc<dyn TagRepository>,
pub user_repo: Arc<dyn UserRepository>,
#[cfg(feature = "smart-features")]
pub link_repo: Arc<dyn notes_domain::ports::LinkRepository>,
pub note_service: Arc<NoteService>,
pub tag_service: Arc<TagService>,
pub user_service: Arc<UserService>,
#[cfg(feature = "smart-features")]
pub nats_client: async_nats::Client,
pub config: Config,
}
@@ -22,18 +26,24 @@ impl AppState {
note_repo: Arc<dyn NoteRepository>,
tag_repo: Arc<dyn TagRepository>,
user_repo: Arc<dyn UserRepository>,
#[cfg(feature = "smart-features")] link_repo: Arc<dyn notes_domain::ports::LinkRepository>,
note_service: Arc<NoteService>,
tag_service: Arc<TagService>,
user_service: Arc<UserService>,
#[cfg(feature = "smart-features")] nats_client: async_nats::Client,
config: Config,
) -> Self {
Self {
note_repo,
tag_repo,
user_repo,
#[cfg(feature = "smart-features")]
link_repo,
note_service,
tag_service,
user_service,
#[cfg(feature = "smart-features")]
nats_client,
config,
}
}