feat(kernel): complete tree-first graph tasks 074-080
This commit is contained in:
@@ -0,0 +1,21 @@
|
||||
[package]
|
||||
name = "mnote-web"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
|
||||
[dependencies]
|
||||
axum = { version = "0.8", features = ["ws"] }
|
||||
bridge-runtime = { path = "../bridge-runtime" }
|
||||
core-protocol = { path = "../core-protocol" }
|
||||
futures-util = "0.3"
|
||||
reqwest = { version = "0.12", default-features = false, features = ["blocking", "json", "rustls-tls"] }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
tokio = { version = "1", features = ["macros", "rt-multi-thread", "net", "signal", "sync", "time"] }
|
||||
tower-http = { version = "0.6", features = ["trace"] }
|
||||
tracing = "0.1"
|
||||
tracing-subscriber = { version = "0.3", features = ["fmt"] }
|
||||
tower = "0.5"
|
||||
base64 = "0.22"
|
||||
@@ -0,0 +1,72 @@
|
||||
use crate::middleware::request_context::inject_request_context;
|
||||
use crate::routes::build_router;
|
||||
use axum::Router;
|
||||
use std::env;
|
||||
use std::sync::Arc;
|
||||
use tower_http::trace::TraceLayer;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct AppConfig {
|
||||
pub service_name: String,
|
||||
pub service_version: String,
|
||||
pub bind_addr: String,
|
||||
pub hermes_base_path: String,
|
||||
pub compat_next_base_path: String,
|
||||
pub convex_url: Option<String>,
|
||||
pub convex_admin_key: Option<String>,
|
||||
pub dev_user_id: String,
|
||||
pub dev_user_name: String,
|
||||
pub dev_user_email: String,
|
||||
}
|
||||
|
||||
impl AppConfig {
|
||||
pub fn from_env() -> Self {
|
||||
Self {
|
||||
service_name: env::var("MNOTE_WEB_SERVICE_NAME")
|
||||
.unwrap_or_else(|_| "mnote-web".into()),
|
||||
service_version: env::var("MNOTE_WEB_SERVICE_VERSION")
|
||||
.unwrap_or_else(|_| env!("CARGO_PKG_VERSION").into()),
|
||||
bind_addr: env::var("MNOTE_WEB_BIND")
|
||||
.unwrap_or_else(|_| "127.0.0.1:3104".into()),
|
||||
hermes_base_path: env::var("MNOTE_WEB_HERMES_BASE_PATH")
|
||||
.unwrap_or_else(|_| "/api/hermes".into()),
|
||||
compat_next_base_path: env::var("MNOTE_WEB_COMPAT_NEXT_BASE_PATH")
|
||||
.unwrap_or_else(|_| "/api/compat/next".into()),
|
||||
convex_url: env::var("CONVEX_SELF_HOSTED_URL")
|
||||
.ok()
|
||||
.or_else(|| env::var("NEXT_PUBLIC_CONVEX_URL").ok())
|
||||
.map(|value| value.trim().trim_end_matches('/').to_string())
|
||||
.filter(|value| !value.is_empty()),
|
||||
convex_admin_key: env::var("CONVEX_SELF_HOSTED_ADMIN_KEY")
|
||||
.ok()
|
||||
.map(|value| value.trim().to_string())
|
||||
.filter(|value| !value.is_empty()),
|
||||
dev_user_id: env::var("DEV_USER_ID").unwrap_or_else(|_| "dev-user".into()),
|
||||
dev_user_name: env::var("DEV_USER_NAME").unwrap_or_else(|_| "开发用户".into()),
|
||||
dev_user_email: env::var("DEV_USER_EMAIL").unwrap_or_else(|_| "dev@mnote.local".into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct AppState {
|
||||
config: Arc<AppConfig>,
|
||||
}
|
||||
|
||||
impl AppState {
|
||||
pub fn new(config: AppConfig) -> Self {
|
||||
Self {
|
||||
config: Arc::new(config),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn config(&self) -> &AppConfig {
|
||||
self.config.as_ref()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn build_app(state: AppState) -> Router {
|
||||
build_router(state)
|
||||
.layer(TraceLayer::new_for_http())
|
||||
.layer(axum::middleware::from_fn(inject_request_context))
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
use axum::http::{HeaderMap, HeaderName, HeaderValue, Method, Uri};
|
||||
use serde::Serialize;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
static REQUEST_COUNTER: AtomicU64 = AtomicU64::new(1);
|
||||
|
||||
const HEADER_REQUEST_ID: &str = "x-request-id";
|
||||
const HEADER_TRACE_ID: &str = "x-trace-id";
|
||||
const HEADER_TENANT_ID: &str = "x-mnote-tenant-id";
|
||||
const HEADER_WORKSPACE_ID: &str = "x-mnote-workspace-id";
|
||||
const HEADER_DEPLOYMENT_ID: &str = "x-mnote-deployment-id";
|
||||
const HEADER_PROJECT_ID: &str = "x-mnote-project-id";
|
||||
const HEADER_ACTOR_ID: &str = "x-mnote-actor-id";
|
||||
const HEADER_ACTOR_TYPE: &str = "x-mnote-actor-type";
|
||||
const HEADER_SESSION_ID: &str = "x-mnote-session-id";
|
||||
const HEADER_SOURCE_CHANNEL: &str = "x-mnote-source-channel";
|
||||
const HEADER_SOURCE_CLIENT: &str = "x-mnote-source-client";
|
||||
const HEADER_IDEMPOTENCY_KEY: &str = "x-idempotency-key";
|
||||
|
||||
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct TraceContext {
|
||||
pub request_id: String,
|
||||
pub trace_id: String,
|
||||
pub method: String,
|
||||
pub path: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AuthContext {
|
||||
pub authorization: Option<String>,
|
||||
pub actor_id: String,
|
||||
pub actor_type: String,
|
||||
pub session_id: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct WorkspaceContext {
|
||||
pub workspace_id: Option<String>,
|
||||
pub tenant_id: Option<String>,
|
||||
pub deployment_id: Option<String>,
|
||||
pub project_id: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SourceContext {
|
||||
pub channel: String,
|
||||
pub client: String,
|
||||
pub idempotency_key: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct RequestContext {
|
||||
pub trace: TraceContext,
|
||||
pub auth: AuthContext,
|
||||
pub workspace: WorkspaceContext,
|
||||
pub source: SourceContext,
|
||||
}
|
||||
|
||||
impl RequestContext {
|
||||
pub fn from_http_parts(method: &Method, uri: &Uri, headers: &HeaderMap) -> Self {
|
||||
let request_id = header_or_generated(headers, HEADER_REQUEST_ID, "req");
|
||||
let trace_id = header_or_generated(headers, HEADER_TRACE_ID, "trace");
|
||||
|
||||
Self {
|
||||
trace: TraceContext {
|
||||
request_id,
|
||||
trace_id,
|
||||
method: method.as_str().to_string(),
|
||||
path: uri.path().to_string(),
|
||||
},
|
||||
auth: AuthContext {
|
||||
authorization: header_value(headers, axum::http::header::AUTHORIZATION.as_str()),
|
||||
actor_id: header_value(headers, HEADER_ACTOR_ID)
|
||||
.unwrap_or_else(|| "anonymous".into()),
|
||||
actor_type: header_value(headers, HEADER_ACTOR_TYPE)
|
||||
.unwrap_or_else(|| "anonymous".into()),
|
||||
session_id: header_value(headers, HEADER_SESSION_ID),
|
||||
},
|
||||
workspace: WorkspaceContext {
|
||||
workspace_id: header_value(headers, HEADER_WORKSPACE_ID),
|
||||
tenant_id: header_value(headers, HEADER_TENANT_ID),
|
||||
deployment_id: header_value(headers, HEADER_DEPLOYMENT_ID),
|
||||
project_id: header_value(headers, HEADER_PROJECT_ID),
|
||||
},
|
||||
source: SourceContext {
|
||||
channel: header_value(headers, HEADER_SOURCE_CHANNEL)
|
||||
.unwrap_or_else(|| "http".into()),
|
||||
client: header_value(headers, HEADER_SOURCE_CLIENT)
|
||||
.unwrap_or_else(|| "mnote-web".into()),
|
||||
idempotency_key: header_value(headers, HEADER_IDEMPOTENCY_KEY),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub fn apply_response_headers(&self, headers: &mut HeaderMap) {
|
||||
insert_header(headers, HEADER_REQUEST_ID, &self.trace.request_id);
|
||||
insert_header(headers, HEADER_TRACE_ID, &self.trace.trace_id);
|
||||
if let Some(workspace_id) = &self.workspace.workspace_id {
|
||||
insert_header(headers, HEADER_WORKSPACE_ID, workspace_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn header_or_generated(headers: &HeaderMap, key: &str, prefix: &str) -> String {
|
||||
header_value(headers, key).unwrap_or_else(|| generate_id(prefix))
|
||||
}
|
||||
|
||||
fn header_value(headers: &HeaderMap, key: &str) -> Option<String> {
|
||||
headers
|
||||
.get(key)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty())
|
||||
.map(ToOwned::to_owned)
|
||||
}
|
||||
|
||||
fn generate_id(prefix: &str) -> String {
|
||||
let now = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_millis();
|
||||
let counter = REQUEST_COUNTER.fetch_add(1, Ordering::Relaxed);
|
||||
format!("{prefix}_{now}_{counter}")
|
||||
}
|
||||
|
||||
fn insert_header(headers: &mut HeaderMap, key: &str, value: &str) {
|
||||
let Ok(name) = HeaderName::from_lowercase(key.as_bytes()) else {
|
||||
return;
|
||||
};
|
||||
let Ok(value) = HeaderValue::from_str(value) else {
|
||||
return;
|
||||
};
|
||||
headers.insert(name, value);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn request_context_uses_headers_when_present() {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(HEADER_REQUEST_ID, HeaderValue::from_static("req_demo"));
|
||||
headers.insert(HEADER_TRACE_ID, HeaderValue::from_static("trace_demo"));
|
||||
headers.insert(HEADER_WORKSPACE_ID, HeaderValue::from_static("ws_demo"));
|
||||
headers.insert(HEADER_ACTOR_ID, HeaderValue::from_static("user_demo"));
|
||||
|
||||
let context = RequestContext::from_http_parts(
|
||||
&Method::POST,
|
||||
&"/api/hermes/bridge".parse::<Uri>().expect("uri"),
|
||||
&headers,
|
||||
);
|
||||
|
||||
assert_eq!(context.trace.request_id, "req_demo");
|
||||
assert_eq!(context.trace.trace_id, "trace_demo");
|
||||
assert_eq!(context.workspace.workspace_id.as_deref(), Some("ws_demo"));
|
||||
assert_eq!(context.auth.actor_id, "user_demo");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
use crate::context::RequestContext;
|
||||
use axum::http::StatusCode;
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use axum::Json;
|
||||
use serde::Serialize;
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ErrorBody {
|
||||
pub ok: bool,
|
||||
pub code: &'static str,
|
||||
pub message: String,
|
||||
pub request_id: Option<String>,
|
||||
pub trace_id: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct WebError {
|
||||
status: StatusCode,
|
||||
code: &'static str,
|
||||
message: String,
|
||||
request_context: Option<RequestContext>,
|
||||
}
|
||||
|
||||
impl WebError {
|
||||
pub fn new(status: StatusCode, code: &'static str, message: impl Into<String>) -> Self {
|
||||
Self {
|
||||
status,
|
||||
code,
|
||||
message: message.into(),
|
||||
request_context: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn bad_request(message: impl Into<String>) -> Self {
|
||||
Self::new(StatusCode::BAD_REQUEST, "bad_request", message)
|
||||
}
|
||||
|
||||
pub fn internal(message: impl Into<String>) -> Self {
|
||||
Self::new(StatusCode::INTERNAL_SERVER_ERROR, "internal_error", message)
|
||||
}
|
||||
|
||||
pub fn with_context(mut self, request_context: &RequestContext) -> Self {
|
||||
self.request_context = Some(request_context.clone());
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoResponse for WebError {
|
||||
fn into_response(self) -> Response {
|
||||
let body = ErrorBody {
|
||||
ok: false,
|
||||
code: self.code,
|
||||
message: self.message,
|
||||
request_id: self
|
||||
.request_context
|
||||
.as_ref()
|
||||
.map(|context| context.trace.request_id.clone()),
|
||||
trace_id: self
|
||||
.request_context
|
||||
.as_ref()
|
||||
.map(|context| context.trace.trace_id.clone()),
|
||||
};
|
||||
(self.status, Json(body)).into_response()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
pub mod app;
|
||||
pub mod context;
|
||||
pub mod error;
|
||||
pub mod middleware;
|
||||
pub mod routes;
|
||||
pub mod transport;
|
||||
|
||||
pub use app::{build_app, AppConfig, AppState};
|
||||
@@ -0,0 +1,25 @@
|
||||
use mnote_web::{build_app, AppConfig, AppState};
|
||||
use tokio::net::TcpListener;
|
||||
use tracing::info;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
init_tracing();
|
||||
|
||||
let config = AppConfig::from_env();
|
||||
let bind_addr = config.bind_addr.clone();
|
||||
let app = build_app(AppState::new(config));
|
||||
let listener = TcpListener::bind(&bind_addr).await?;
|
||||
|
||||
info!(bind_addr = %bind_addr, "mnote-web 最小骨架已启动");
|
||||
axum::serve(listener, app).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn init_tracing() {
|
||||
tracing_subscriber::fmt()
|
||||
.with_target(false)
|
||||
.compact()
|
||||
.try_init()
|
||||
.ok();
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
pub mod request_context;
|
||||
@@ -0,0 +1,17 @@
|
||||
use crate::context::RequestContext;
|
||||
use axum::extract::Request;
|
||||
use axum::middleware::Next;
|
||||
use axum::response::Response;
|
||||
|
||||
pub async fn inject_request_context(mut request: Request, next: Next) -> Response {
|
||||
let context = RequestContext::from_http_parts(
|
||||
request.method(),
|
||||
request.uri(),
|
||||
request.headers(),
|
||||
);
|
||||
request.extensions_mut().insert(context.clone());
|
||||
|
||||
let mut response = next.run(request).await;
|
||||
context.apply_response_headers(response.headers_mut());
|
||||
response
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
use crate::app::AppState;
|
||||
use crate::context::RequestContext;
|
||||
use axum::extract::{Extension, State};
|
||||
use axum::Json;
|
||||
use serde::Serialize;
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CompatBoundaryResponse {
|
||||
pub ok: bool,
|
||||
pub boundary: &'static str,
|
||||
pub compatibility: &'static str,
|
||||
pub request_id: String,
|
||||
pub trace_id: String,
|
||||
pub target: String,
|
||||
pub notes: Vec<&'static str>,
|
||||
}
|
||||
|
||||
pub async fn next_ai_agent_run(
|
||||
State(state): State<AppState>,
|
||||
Extension(context): Extension<RequestContext>,
|
||||
) -> Json<CompatBoundaryResponse> {
|
||||
Json(CompatBoundaryResponse {
|
||||
ok: true,
|
||||
boundary: "next_route_compat",
|
||||
compatibility: "placeholder",
|
||||
request_id: context.trace.request_id,
|
||||
trace_id: context.trace.trace_id,
|
||||
target: format!("{}/bridge", state.config().hermes_base_path),
|
||||
notes: vec![
|
||||
"当前保留 Next route 兼容边界,后续用于把 /api/ai-agent/run 收口到 Rust Web 层。",
|
||||
"此占位实现不复制业务裁决,只声明桥接目标与迁移方向。",
|
||||
],
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
use crate::app::AppState;
|
||||
use crate::context::RequestContext;
|
||||
use axum::extract::{Extension, State};
|
||||
use axum::Json;
|
||||
use serde::Serialize;
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct HealthResponse {
|
||||
pub ok: bool,
|
||||
pub service: String,
|
||||
pub version: String,
|
||||
pub request_id: String,
|
||||
pub trace_id: String,
|
||||
pub runtime: &'static str,
|
||||
}
|
||||
|
||||
pub async fn health(
|
||||
State(state): State<AppState>,
|
||||
Extension(context): Extension<RequestContext>,
|
||||
) -> Json<HealthResponse> {
|
||||
Json(HealthResponse {
|
||||
ok: true,
|
||||
service: state.config().service_name.clone(),
|
||||
version: state.config().service_version.clone(),
|
||||
request_id: context.trace.request_id,
|
||||
trace_id: context.trace.trace_id,
|
||||
runtime: "axum",
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
use crate::app::AppState;
|
||||
use crate::context::RequestContext;
|
||||
use crate::error::WebError;
|
||||
use axum::extract::{Extension, State};
|
||||
use axum::http::StatusCode;
|
||||
use axum::Json;
|
||||
use bridge_runtime::{
|
||||
build_failure_response, build_success_response, execute_runtime_input, execute_runtime_query,
|
||||
runtime_input_requests_result, RuntimeInput,
|
||||
};
|
||||
use serde::Serialize;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct HermesHealthResponse {
|
||||
pub ok: bool,
|
||||
pub service: String,
|
||||
pub bridge: &'static str,
|
||||
pub request_id: String,
|
||||
pub trace_id: String,
|
||||
}
|
||||
|
||||
pub async fn health(
|
||||
State(state): State<AppState>,
|
||||
Extension(context): Extension<RequestContext>,
|
||||
) -> Json<HermesHealthResponse> {
|
||||
Json(HermesHealthResponse {
|
||||
ok: true,
|
||||
service: state.config().service_name.clone(),
|
||||
bridge: "hermes",
|
||||
request_id: context.trace.request_id,
|
||||
trace_id: context.trace.trace_id,
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn bridge_runtime(
|
||||
Extension(context): Extension<RequestContext>,
|
||||
Json(runtime_input): Json<RuntimeInput>,
|
||||
) -> Result<(StatusCode, Json<Value>), WebError> {
|
||||
let payload = if runtime_input_requests_result(&runtime_input) {
|
||||
match execute_runtime_query(runtime_input) {
|
||||
Ok(result) => json!({
|
||||
"ok": true,
|
||||
"bridge": "hermes_runtime_result",
|
||||
"requestId": context.trace.request_id,
|
||||
"traceId": context.trace.trace_id,
|
||||
"result": result,
|
||||
}),
|
||||
Err(error) => {
|
||||
let failure = build_failure_response(error);
|
||||
return Ok((
|
||||
StatusCode::BAD_REQUEST,
|
||||
Json(serde_json::to_value(failure).expect("runtime failure 应可序列化")),
|
||||
));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
match execute_runtime_input(runtime_input) {
|
||||
Ok(plan) => {
|
||||
let success = build_success_response(plan);
|
||||
json!({
|
||||
"ok": success.ok,
|
||||
"bridge": "hermes_runtime_plan",
|
||||
"requestId": context.trace.request_id,
|
||||
"traceId": context.trace.trace_id,
|
||||
"plan": success.plan,
|
||||
})
|
||||
}
|
||||
Err(error) => {
|
||||
let failure = build_failure_response(error);
|
||||
return Ok((
|
||||
StatusCode::BAD_REQUEST,
|
||||
Json(serde_json::to_value(failure).expect("runtime failure 应可序列化")),
|
||||
));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Ok((StatusCode::OK, Json(payload)))
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
use crate::app::{AppConfig, AppState};
|
||||
use crate::context::RequestContext;
|
||||
use crate::error::WebError;
|
||||
use crate::transport::convex::execute_sidebar_dataset_query;
|
||||
use axum::extract::{Extension, Query, State};
|
||||
use axum::http::StatusCode;
|
||||
use axum::Json;
|
||||
use bridge_runtime::{
|
||||
execute_runtime_input, execute_runtime_query, RuntimeActorWire, RuntimeBridgeContextWire,
|
||||
RuntimeExecutionPlan, RuntimeInput, RuntimeQueryEnvelopeWire, RuntimeSourceWire,
|
||||
};
|
||||
use core_protocol::{KernelGraphDirection, KernelNodeType, KernelProjectionKind};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Value};
|
||||
use std::env;
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct KernelProjectionQuery {
|
||||
pub workspace_id: Option<String>,
|
||||
pub root_node_id: Option<String>,
|
||||
pub depth: Option<u32>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct KernelSubtreeQuery {
|
||||
pub workspace_id: Option<String>,
|
||||
pub root_node_id: String,
|
||||
pub depth: Option<u32>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct KernelEdgesQuery {
|
||||
pub workspace_id: Option<String>,
|
||||
pub node_id: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct KernelGraphQuery {
|
||||
pub workspace_id: Option<String>,
|
||||
pub start_node_id: String,
|
||||
pub max_depth: Option<u32>,
|
||||
}
|
||||
|
||||
fn runtime_context(context: &RequestContext) -> RuntimeBridgeContextWire {
|
||||
RuntimeBridgeContextWire {
|
||||
deployment_id: context.workspace.deployment_id.clone(),
|
||||
project_id: context.workspace.project_id.clone(),
|
||||
workspace_id: context.workspace.workspace_id.clone(),
|
||||
request_id: context.trace.request_id.clone(),
|
||||
trace_id: context.trace.trace_id.clone(),
|
||||
actor: RuntimeActorWire {
|
||||
actor_type: context.auth.actor_type.clone(),
|
||||
actor_id: context.auth.actor_id.clone(),
|
||||
session_id: context.auth.session_id.clone(),
|
||||
},
|
||||
source: RuntimeSourceWire {
|
||||
channel: context.source.channel.clone(),
|
||||
client: context.source.client.clone(),
|
||||
},
|
||||
tenant_id: context.workspace.tenant_id.clone(),
|
||||
auth_token: context.auth.authorization.clone(),
|
||||
idempotency_key: context.source.idempotency_key.clone(),
|
||||
validate_only: false,
|
||||
dry_run: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn build_sidebar_dataset_plan(
|
||||
config: &AppConfig,
|
||||
context: &RequestContext,
|
||||
workspace_id: &str,
|
||||
) -> Result<Value, WebError> {
|
||||
let runtime_input = RuntimeInput::Query {
|
||||
context: runtime_context(context),
|
||||
query: RuntimeQueryEnvelopeWire {
|
||||
name: "sidebar.dataset.list".into(),
|
||||
payload: json!({
|
||||
"workspaceId": workspace_id,
|
||||
}),
|
||||
},
|
||||
data: None,
|
||||
};
|
||||
let RuntimeExecutionPlan::Query(plan) = execute_runtime_input(runtime_input)
|
||||
.map_err(|error| WebError::bad_request(error.message).with_context(context))?
|
||||
else {
|
||||
return Err(WebError::internal("sidebar.dataset.list 未返回 query plan").with_context(context));
|
||||
};
|
||||
|
||||
let dataset = execute_sidebar_dataset_query(config, &plan)?;
|
||||
Ok(dataset)
|
||||
}
|
||||
|
||||
fn load_sidebar_dataset(
|
||||
config: &AppConfig,
|
||||
context: &RequestContext,
|
||||
workspace_id: Option<&str>,
|
||||
) -> Result<Value, WebError> {
|
||||
if let Ok(raw) = env::var("MNOTE_WEB_KERNEL_SIDEBAR_FIXTURE_JSON") {
|
||||
let trimmed = raw.trim();
|
||||
if !trimmed.is_empty() {
|
||||
return serde_json::from_str(trimmed).map_err(|error| {
|
||||
WebError::internal(format!("kernel fixture JSON 非法: {error}")).with_context(context)
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
let workspace_id = workspace_id
|
||||
.or(context.workspace.workspace_id.as_deref())
|
||||
.unwrap_or("ws_demo");
|
||||
build_sidebar_dataset_plan(config, context, workspace_id)
|
||||
}
|
||||
|
||||
fn execute_kernel_query(
|
||||
context: &RequestContext,
|
||||
query: RuntimeQueryEnvelopeWire,
|
||||
dataset: Value,
|
||||
) -> Result<Value, WebError> {
|
||||
execute_runtime_query(RuntimeInput::Query {
|
||||
context: runtime_context(context),
|
||||
query,
|
||||
data: Some(dataset),
|
||||
})
|
||||
.map_err(|error| WebError::bad_request(error.message).with_context(context))
|
||||
}
|
||||
|
||||
pub async fn project_sidebar(
|
||||
State(state): State<AppState>,
|
||||
Extension(context): Extension<RequestContext>,
|
||||
Query(query): Query<KernelProjectionQuery>,
|
||||
) -> Result<(StatusCode, Json<Value>), WebError> {
|
||||
let dataset = load_sidebar_dataset(state.config(), &context, query.workspace_id.as_deref())?;
|
||||
let result = execute_kernel_query(
|
||||
&context,
|
||||
RuntimeQueryEnvelopeWire {
|
||||
name: "kernel.project_view".into(),
|
||||
payload: json!({
|
||||
"projection": KernelProjectionKind::SidebarTree,
|
||||
"workspaceId": query.workspace_id,
|
||||
"rootNodeId": query.root_node_id,
|
||||
"depth": query.depth,
|
||||
"includeEdges": true,
|
||||
"includeContent": false,
|
||||
"nodeTypes": [KernelNodeType::Page],
|
||||
}),
|
||||
},
|
||||
dataset,
|
||||
)?;
|
||||
|
||||
Ok((StatusCode::OK, Json(json!({
|
||||
"ok": true,
|
||||
"requestId": context.trace.request_id,
|
||||
"traceId": context.trace.trace_id,
|
||||
"result": result,
|
||||
}))))
|
||||
}
|
||||
|
||||
pub async fn subtree(
|
||||
State(state): State<AppState>,
|
||||
Extension(context): Extension<RequestContext>,
|
||||
Query(query): Query<KernelSubtreeQuery>,
|
||||
) -> Result<(StatusCode, Json<Value>), WebError> {
|
||||
let dataset = load_sidebar_dataset(state.config(), &context, query.workspace_id.as_deref())?;
|
||||
let result = execute_kernel_query(
|
||||
&context,
|
||||
RuntimeQueryEnvelopeWire {
|
||||
name: "kernel.subtree.get".into(),
|
||||
payload: json!({
|
||||
"workspaceId": query.workspace_id,
|
||||
"rootNodeId": query.root_node_id,
|
||||
"depth": query.depth,
|
||||
"includeEdges": true,
|
||||
"nodeTypes": [KernelNodeType::Page],
|
||||
}),
|
||||
},
|
||||
dataset,
|
||||
)?;
|
||||
Ok((StatusCode::OK, Json(json!({
|
||||
"ok": true,
|
||||
"requestId": context.trace.request_id,
|
||||
"traceId": context.trace.trace_id,
|
||||
"result": result,
|
||||
}))))
|
||||
}
|
||||
|
||||
pub async fn edges(
|
||||
State(state): State<AppState>,
|
||||
Extension(context): Extension<RequestContext>,
|
||||
Query(query): Query<KernelEdgesQuery>,
|
||||
) -> Result<(StatusCode, Json<Value>), WebError> {
|
||||
let dataset = load_sidebar_dataset(state.config(), &context, query.workspace_id.as_deref())?;
|
||||
let result = execute_kernel_query(
|
||||
&context,
|
||||
RuntimeQueryEnvelopeWire {
|
||||
name: "kernel.edges.list".into(),
|
||||
payload: json!({
|
||||
"workspaceId": query.workspace_id,
|
||||
"nodeId": query.node_id,
|
||||
"direction": KernelGraphDirection::Both,
|
||||
}),
|
||||
},
|
||||
dataset,
|
||||
)?;
|
||||
Ok((StatusCode::OK, Json(json!({
|
||||
"ok": true,
|
||||
"requestId": context.trace.request_id,
|
||||
"traceId": context.trace.trace_id,
|
||||
"result": result,
|
||||
}))))
|
||||
}
|
||||
|
||||
pub async fn graph(
|
||||
State(state): State<AppState>,
|
||||
Extension(context): Extension<RequestContext>,
|
||||
Query(query): Query<KernelGraphQuery>,
|
||||
) -> Result<(StatusCode, Json<Value>), WebError> {
|
||||
let dataset = load_sidebar_dataset(state.config(), &context, query.workspace_id.as_deref())?;
|
||||
let result = execute_kernel_query(
|
||||
&context,
|
||||
RuntimeQueryEnvelopeWire {
|
||||
name: "kernel.graph.traverse".into(),
|
||||
payload: json!({
|
||||
"workspaceId": query.workspace_id,
|
||||
"startNodeId": query.start_node_id,
|
||||
"maxDepth": query.max_depth.unwrap_or(2),
|
||||
"edgeTypes": [],
|
||||
}),
|
||||
},
|
||||
dataset,
|
||||
)?;
|
||||
Ok((StatusCode::OK, Json(json!({
|
||||
"ok": true,
|
||||
"requestId": context.trace.request_id,
|
||||
"traceId": context.trace.trace_id,
|
||||
"result": result,
|
||||
}))))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::app::{build_app, AppConfig, AppState};
|
||||
use axum::body::Body;
|
||||
use axum::http::{Request, StatusCode};
|
||||
use tower::util::ServiceExt;
|
||||
|
||||
fn app() -> axum::Router {
|
||||
std::env::set_var(
|
||||
"MNOTE_WEB_KERNEL_SIDEBAR_FIXTURE_JSON",
|
||||
r#"{"documents":[{"id":"page_root","workspace_id":"ws_demo","title":"工作区首页","parent_id":null,"sort_order":0,"is_starred":true,"is_template":false,"created_at":"2026-04-16T00:00:00Z","updated_at":"2026-04-16T00:00:00Z"},{"id":"page_child","workspace_id":"ws_demo","title":"子页面","parent_id":"page_root","sort_order":1,"is_starred":false,"is_template":false,"created_at":"2026-04-16T00:00:00Z","updated_at":"2026-04-16T00:00:00Z"}]}"#,
|
||||
);
|
||||
build_app(AppState::new(AppConfig {
|
||||
service_name: "mnote-web".into(),
|
||||
service_version: "0.1.0".into(),
|
||||
bind_addr: "127.0.0.1:0".into(),
|
||||
hermes_base_path: "/api/hermes".into(),
|
||||
compat_next_base_path: "/api/compat/next".into(),
|
||||
convex_url: None,
|
||||
convex_admin_key: None,
|
||||
dev_user_id: "dev-user".into(),
|
||||
dev_user_name: "开发用户".into(),
|
||||
dev_user_email: "dev@mnote.local".into(),
|
||||
}))
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn kernel_projection_route_returns_sidebar_projection() {
|
||||
let response = app()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.uri("/api/kernel/projections/sidebar?rootNodeId=page_root")
|
||||
.body(Body::empty())
|
||||
.expect("request"),
|
||||
)
|
||||
.await
|
||||
.expect("response");
|
||||
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
mod compat;
|
||||
mod health;
|
||||
mod hermes;
|
||||
mod kernel;
|
||||
mod sse;
|
||||
mod ws;
|
||||
|
||||
use crate::app::AppState;
|
||||
use axum::routing::{get, post};
|
||||
use axum::Router;
|
||||
|
||||
pub fn build_router(state: AppState) -> Router {
|
||||
let hermes_base_path = state.config().hermes_base_path.clone();
|
||||
let compat_next_base_path = state.config().compat_next_base_path.clone();
|
||||
|
||||
Router::new()
|
||||
.route("/health", get(health::health))
|
||||
.route("/api/kernel/projections/sidebar", get(kernel::project_sidebar))
|
||||
.route("/api/kernel/subtree", get(kernel::subtree))
|
||||
.route("/api/kernel/edges", get(kernel::edges))
|
||||
.route("/api/kernel/graph", get(kernel::graph))
|
||||
.route("/api/stream/events", get(sse::events))
|
||||
.route("/api/realtime/ws", get(ws::socket))
|
||||
.nest(
|
||||
&hermes_base_path,
|
||||
Router::new()
|
||||
.route("/health", get(hermes::health))
|
||||
.route("/bridge", post(hermes::bridge_runtime)),
|
||||
)
|
||||
.nest(
|
||||
&compat_next_base_path,
|
||||
Router::new().route("/ai-agent/run", post(compat::next_ai_agent_run)),
|
||||
)
|
||||
.with_state(state)
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
use crate::context::RequestContext;
|
||||
use axum::extract::Extension;
|
||||
use axum::response::sse::{Event, KeepAlive, Sse};
|
||||
use futures_util::stream;
|
||||
use serde_json::json;
|
||||
use std::convert::Infallible;
|
||||
use std::time::Duration;
|
||||
|
||||
pub async fn events(
|
||||
Extension(context): Extension<RequestContext>,
|
||||
) -> Sse<impl futures_util::Stream<Item = Result<Event, Infallible>>> {
|
||||
let payload = json!({
|
||||
"kind": "sse_placeholder",
|
||||
"requestId": context.trace.request_id,
|
||||
"traceId": context.trace.trace_id,
|
||||
"workspaceId": context.workspace.workspace_id,
|
||||
"notes": [
|
||||
"当前为 task-062 最小骨架,后续在此对齐统一流式输出协议。",
|
||||
"此路由预留给 Hermes token/tool/client event 回流。"
|
||||
]
|
||||
});
|
||||
|
||||
let event = Event::default()
|
||||
.event("ready")
|
||||
.json_data(payload)
|
||||
.expect("SSE 占位事件必须可序列化");
|
||||
|
||||
Sse::new(stream::iter(vec![Ok(event)])).keep_alive(
|
||||
KeepAlive::new()
|
||||
.interval(Duration::from_secs(15))
|
||||
.text("keepalive"),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
use crate::context::RequestContext;
|
||||
use axum::extract::ws::{Message, WebSocket, WebSocketUpgrade};
|
||||
use axum::extract::Extension;
|
||||
use axum::response::Response;
|
||||
use futures_util::StreamExt;
|
||||
use serde_json::json;
|
||||
|
||||
pub async fn socket(
|
||||
ws: WebSocketUpgrade,
|
||||
Extension(context): Extension<RequestContext>,
|
||||
) -> Response {
|
||||
ws.on_upgrade(move |socket| handle_socket(socket, context))
|
||||
}
|
||||
|
||||
async fn handle_socket(mut socket: WebSocket, context: RequestContext) {
|
||||
let payload = json!({
|
||||
"kind": "ws_placeholder",
|
||||
"requestId": context.trace.request_id,
|
||||
"traceId": context.trace.trace_id,
|
||||
"workspaceId": context.workspace.workspace_id,
|
||||
"notes": [
|
||||
"当前为 task-062 最小骨架,后续可承接协作推送和运行态事件。"
|
||||
]
|
||||
});
|
||||
|
||||
let _ = socket
|
||||
.send(Message::Text(payload.to_string().into()))
|
||||
.await;
|
||||
|
||||
while let Some(message) = socket.next().await {
|
||||
let Ok(message) = message else {
|
||||
break;
|
||||
};
|
||||
|
||||
match message {
|
||||
Message::Text(text) => {
|
||||
let echo = json!({
|
||||
"kind": "ws_echo",
|
||||
"traceId": context.trace.trace_id,
|
||||
"text": text.to_string(),
|
||||
});
|
||||
if socket
|
||||
.send(Message::Text(echo.to_string().into()))
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
Message::Close(_) => break,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
pub mod convex;
|
||||
@@ -0,0 +1,127 @@
|
||||
use crate::app::AppConfig;
|
||||
use crate::error::WebError;
|
||||
use base64::engine::general_purpose::STANDARD;
|
||||
use base64::Engine;
|
||||
use bridge_runtime::RuntimeQueryExecutionPlan;
|
||||
use serde_json::{json, Value};
|
||||
use std::fs;
|
||||
use std::time::Duration;
|
||||
|
||||
fn read_env_or_dotenv(key: &str) -> Option<String> {
|
||||
if let Ok(value) = std::env::var(key) {
|
||||
let trimmed = value.trim().trim_matches('"').to_string();
|
||||
if !trimmed.is_empty() {
|
||||
return Some(trimmed);
|
||||
}
|
||||
}
|
||||
|
||||
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../../..")
|
||||
.join(".env.all");
|
||||
let content = fs::read_to_string(root).ok()?;
|
||||
for line in content.lines() {
|
||||
let line = line.trim_end_matches('\r');
|
||||
if line.starts_with('#') || line.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
let Some((k, v)) = line.split_once('=') else {
|
||||
continue;
|
||||
};
|
||||
if k.trim() != key {
|
||||
continue;
|
||||
}
|
||||
let trimmed = v.trim().trim_matches('"').to_string();
|
||||
if !trimmed.is_empty() {
|
||||
return Some(trimmed);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn build_authorization(config: &AppConfig) -> Result<String, WebError> {
|
||||
let admin_key = config
|
||||
.convex_admin_key
|
||||
.clone()
|
||||
.or_else(|| read_env_or_dotenv("CONVEX_SELF_HOSTED_ADMIN_KEY"))
|
||||
.ok_or_else(|| WebError::internal("缺少 CONVEX_SELF_HOSTED_ADMIN_KEY"))?;
|
||||
|
||||
let identity = json!({
|
||||
"subject": config.dev_user_id,
|
||||
"issuer": "https://mnote.local/dev-auth",
|
||||
"tokenIdentifier": format!("dev-user|{}", config.dev_user_id),
|
||||
"name": config.dev_user_name,
|
||||
"email": config.dev_user_email,
|
||||
});
|
||||
let encoded = STANDARD.encode(
|
||||
serde_json::to_string(&identity)
|
||||
.map_err(|error| WebError::internal(format!("开发用户身份序列化失败: {error}")))?,
|
||||
);
|
||||
|
||||
Ok(format!("Convex {admin_key}:{encoded}"))
|
||||
}
|
||||
|
||||
fn convex_url(config: &AppConfig) -> Result<String, WebError> {
|
||||
config
|
||||
.convex_url
|
||||
.clone()
|
||||
.or_else(|| read_env_or_dotenv("CONVEX_SELF_HOSTED_URL"))
|
||||
.or_else(|| read_env_or_dotenv("NEXT_PUBLIC_CONVEX_URL"))
|
||||
.map(|value| value.trim().trim_end_matches('/').to_string())
|
||||
.filter(|value| !value.is_empty())
|
||||
.ok_or_else(|| WebError::internal("缺少 CONVEX_SELF_HOSTED_URL / NEXT_PUBLIC_CONVEX_URL"))
|
||||
}
|
||||
|
||||
pub fn execute_sidebar_dataset_query(
|
||||
config: &AppConfig,
|
||||
plan: &RuntimeQueryExecutionPlan,
|
||||
) -> Result<Value, WebError> {
|
||||
if plan.function_name != "sidebar:datasetList" {
|
||||
return Err(WebError::bad_request(format!(
|
||||
"mnote-web transport 暂不支持 query: {}",
|
||||
plan.function_name
|
||||
)));
|
||||
}
|
||||
|
||||
let payload = json!({
|
||||
"path": plan.function_name,
|
||||
"format": "convex_encoded_json",
|
||||
"args": plan.args_json,
|
||||
});
|
||||
|
||||
let client = reqwest::blocking::Client::builder()
|
||||
.timeout(Duration::from_secs(20))
|
||||
.build()
|
||||
.map_err(|error| WebError::internal(format!("Convex HTTP 客户端创建失败: {error}")))?;
|
||||
|
||||
let response = client
|
||||
.post(format!("{}/api/query", convex_url(config)?))
|
||||
.header("Authorization", build_authorization(config)?)
|
||||
.header("Content-Type", "application/json")
|
||||
.header("Convex-Client", "mnote-web")
|
||||
.json(&payload)
|
||||
.send()
|
||||
.map_err(|error| WebError::internal(format!("Convex query 请求失败: {error}")))?;
|
||||
|
||||
let status = response.status();
|
||||
let body: Value = response
|
||||
.json()
|
||||
.map_err(|error| WebError::internal(format!("Convex 响应解析失败: {error}")))?;
|
||||
if !status.is_success() {
|
||||
let message = body
|
||||
.get("errorMessage")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("Convex query 失败");
|
||||
return Err(WebError::internal(message.to_string()));
|
||||
}
|
||||
|
||||
match body.get("status").and_then(Value::as_str) {
|
||||
Some("success") => Ok(body.get("value").cloned().unwrap_or(Value::Null)),
|
||||
Some("error") => Err(WebError::internal(
|
||||
body.get("errorMessage")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("Convex 返回 error")
|
||||
.to_string(),
|
||||
)),
|
||||
_ => Err(WebError::internal(format!("未知 Convex 响应: {body}"))),
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user