feat(kernel): finish phase3 bridge cutover and phase4 tree projection
- add generic mnote-web query transport and bridge routes for workspace/request/trace - route sidebar compat traffic through mnote-web and tighten fixture fallback to dev/test - unify sidebar/page tree/file tree/picker consumers on page_tree projection - sync phase3/phase4 checklist, breakdown docs, and harness progress state
This commit is contained in:
@@ -14,6 +14,7 @@ pub struct AppConfig {
|
||||
pub compat_next_base_path: String,
|
||||
pub convex_url: Option<String>,
|
||||
pub convex_admin_key: Option<String>,
|
||||
pub allow_dev_fixtures: bool,
|
||||
pub dev_user_id: String,
|
||||
pub dev_user_name: String,
|
||||
pub dev_user_email: String,
|
||||
@@ -22,12 +23,10 @@ pub struct AppConfig {
|
||||
impl AppConfig {
|
||||
pub fn from_env() -> Self {
|
||||
Self {
|
||||
service_name: env::var("MNOTE_WEB_SERVICE_NAME")
|
||||
.unwrap_or_else(|_| "mnote-web".into()),
|
||||
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()),
|
||||
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")
|
||||
@@ -41,6 +40,10 @@ impl AppConfig {
|
||||
.ok()
|
||||
.map(|value| value.trim().to_string())
|
||||
.filter(|value| !value.is_empty()),
|
||||
allow_dev_fixtures: env::var("MNOTE_WEB_ALLOW_DEV_FIXTURES")
|
||||
.ok()
|
||||
.map(|value| matches!(value.trim(), "1" | "true" | "TRUE" | "yes" | "YES"))
|
||||
.unwrap_or(false),
|
||||
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()),
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use crate::context::RequestContext;
|
||||
use axum::http::StatusCode;
|
||||
use axum::http::{HeaderName, HeaderValue};
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use axum::Json;
|
||||
use serde::Serialize;
|
||||
@@ -20,6 +21,7 @@ pub struct WebError {
|
||||
code: &'static str,
|
||||
message: String,
|
||||
request_context: Option<RequestContext>,
|
||||
headers: Vec<(&'static str, String)>,
|
||||
}
|
||||
|
||||
impl WebError {
|
||||
@@ -29,6 +31,7 @@ impl WebError {
|
||||
code,
|
||||
message: message.into(),
|
||||
request_context: None,
|
||||
headers: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,14 +39,35 @@ impl WebError {
|
||||
Self::new(StatusCode::BAD_REQUEST, "bad_request", message)
|
||||
}
|
||||
|
||||
pub fn bad_request_code(code: &'static str, message: impl Into<String>) -> Self {
|
||||
Self::new(StatusCode::BAD_REQUEST, code, message)
|
||||
}
|
||||
|
||||
pub fn internal(message: impl Into<String>) -> Self {
|
||||
Self::new(StatusCode::INTERNAL_SERVER_ERROR, "internal_error", message)
|
||||
}
|
||||
|
||||
pub fn bad_gateway_code(code: &'static str, message: impl Into<String>) -> Self {
|
||||
Self::new(StatusCode::BAD_GATEWAY, code, message)
|
||||
}
|
||||
|
||||
pub fn service_unavailable_code(code: &'static str, message: impl Into<String>) -> Self {
|
||||
Self::new(StatusCode::SERVICE_UNAVAILABLE, code, message)
|
||||
}
|
||||
|
||||
pub fn gateway_timeout_code(code: &'static str, message: impl Into<String>) -> Self {
|
||||
Self::new(StatusCode::GATEWAY_TIMEOUT, code, message)
|
||||
}
|
||||
|
||||
pub fn with_context(mut self, request_context: &RequestContext) -> Self {
|
||||
self.request_context = Some(request_context.clone());
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_header(mut self, name: &'static str, value: impl Into<String>) -> Self {
|
||||
self.headers.push((name, value.into()));
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoResponse for WebError {
|
||||
@@ -61,6 +85,21 @@ impl IntoResponse for WebError {
|
||||
.as_ref()
|
||||
.map(|context| context.trace.trace_id.clone()),
|
||||
};
|
||||
(self.status, Json(body)).into_response()
|
||||
let mut response = (self.status, Json(body)).into_response();
|
||||
if let Ok(name) = HeaderName::from_lowercase(b"x-error-code") {
|
||||
if let Ok(value) = HeaderValue::from_str(self.code) {
|
||||
response.headers_mut().insert(name, value);
|
||||
}
|
||||
}
|
||||
for (name, value) in self.headers {
|
||||
let Ok(header_name) = HeaderName::from_lowercase(name.as_bytes()) else {
|
||||
continue;
|
||||
};
|
||||
let Ok(header_value) = HeaderValue::from_str(&value) else {
|
||||
continue;
|
||||
};
|
||||
response.headers_mut().insert(header_name, header_value);
|
||||
}
|
||||
response
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,191 @@
|
||||
use crate::app::{AppConfig, AppState};
|
||||
use crate::context::RequestContext;
|
||||
use crate::error::WebError;
|
||||
use crate::routes::query_support::{
|
||||
execute_runtime_query_via_convex, resolve_effective_workspace_id,
|
||||
};
|
||||
use axum::extract::{Extension, Query, State};
|
||||
use axum::http::StatusCode;
|
||||
use axum::Json;
|
||||
use bridge_runtime::RuntimeQueryEnvelopeWire;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct BridgeWorkspaceQuery {
|
||||
pub workspace_id: Option<String>,
|
||||
pub limit: Option<u32>,
|
||||
pub cursor: Option<String>,
|
||||
pub command_status: Option<String>,
|
||||
pub event_status: Option<String>,
|
||||
pub target_page_id: Option<String>,
|
||||
pub target_block_id: Option<String>,
|
||||
pub aggregate_type: Option<String>,
|
||||
pub aggregate_id: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct BridgeRequestQuery {
|
||||
pub workspace_id: Option<String>,
|
||||
pub request_id: String,
|
||||
pub command_id: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct BridgeTraceQuery {
|
||||
pub workspace_id: Option<String>,
|
||||
pub trace_id: String,
|
||||
pub command_id: Option<String>,
|
||||
}
|
||||
|
||||
fn ok_response(context: &RequestContext, result: Value) -> (StatusCode, Json<Value>) {
|
||||
(
|
||||
StatusCode::OK,
|
||||
Json(json!({
|
||||
"ok": true,
|
||||
"requestId": context.trace.request_id,
|
||||
"traceId": context.trace.trace_id,
|
||||
"result": result,
|
||||
})),
|
||||
)
|
||||
}
|
||||
|
||||
fn workspace_query_payload(
|
||||
workspace_id: &str,
|
||||
query: &BridgeWorkspaceQuery,
|
||||
) -> RuntimeQueryEnvelopeWire {
|
||||
RuntimeQueryEnvelopeWire {
|
||||
name: "bridge.workspace.overview".into(),
|
||||
payload: json!({
|
||||
"workspaceId": workspace_id,
|
||||
"limit": query.limit.unwrap_or(50),
|
||||
"cursor": query.cursor,
|
||||
"commandStatus": query.command_status,
|
||||
"eventStatus": query.event_status,
|
||||
"targetPageId": query.target_page_id,
|
||||
"targetBlockId": query.target_block_id,
|
||||
"aggregateType": query.aggregate_type,
|
||||
"aggregateId": query.aggregate_id,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn execute_bridge_query(
|
||||
config: &AppConfig,
|
||||
context: &RequestContext,
|
||||
workspace_id: &str,
|
||||
query: RuntimeQueryEnvelopeWire,
|
||||
) -> Result<Value, WebError> {
|
||||
execute_runtime_query_via_convex(config, context, Some(workspace_id), query)
|
||||
}
|
||||
|
||||
pub async fn workspace(
|
||||
State(state): State<AppState>,
|
||||
Extension(context): Extension<RequestContext>,
|
||||
Query(query): Query<BridgeWorkspaceQuery>,
|
||||
) -> Result<(StatusCode, Json<Value>), WebError> {
|
||||
let effective_workspace_id =
|
||||
resolve_effective_workspace_id(&context, query.workspace_id.as_deref(), true)?
|
||||
.expect("workspace_required 已确保存在");
|
||||
let result = execute_bridge_query(
|
||||
state.config(),
|
||||
&context,
|
||||
&effective_workspace_id,
|
||||
workspace_query_payload(&effective_workspace_id, &query),
|
||||
)?;
|
||||
Ok(ok_response(&context, result))
|
||||
}
|
||||
|
||||
pub async fn request(
|
||||
State(state): State<AppState>,
|
||||
Extension(context): Extension<RequestContext>,
|
||||
Query(query): Query<BridgeRequestQuery>,
|
||||
) -> Result<(StatusCode, Json<Value>), WebError> {
|
||||
let effective_workspace_id =
|
||||
resolve_effective_workspace_id(&context, query.workspace_id.as_deref(), true)?
|
||||
.expect("workspace_required 已确保存在");
|
||||
let result = execute_bridge_query(
|
||||
state.config(),
|
||||
&context,
|
||||
&effective_workspace_id,
|
||||
RuntimeQueryEnvelopeWire {
|
||||
name: "bridge.request.get".into(),
|
||||
payload: json!({
|
||||
"workspaceId": effective_workspace_id,
|
||||
"requestId": query.request_id,
|
||||
"commandId": query.command_id,
|
||||
}),
|
||||
},
|
||||
)?;
|
||||
Ok(ok_response(&context, result))
|
||||
}
|
||||
|
||||
pub async fn trace(
|
||||
State(state): State<AppState>,
|
||||
Extension(context): Extension<RequestContext>,
|
||||
Query(query): Query<BridgeTraceQuery>,
|
||||
) -> Result<(StatusCode, Json<Value>), WebError> {
|
||||
let effective_workspace_id =
|
||||
resolve_effective_workspace_id(&context, query.workspace_id.as_deref(), true)?
|
||||
.expect("workspace_required 已确保存在");
|
||||
let result = execute_bridge_query(
|
||||
state.config(),
|
||||
&context,
|
||||
&effective_workspace_id,
|
||||
RuntimeQueryEnvelopeWire {
|
||||
name: "bridge.trace.get".into(),
|
||||
payload: json!({
|
||||
"workspaceId": effective_workspace_id,
|
||||
"traceId": query.trace_id,
|
||||
"commandId": query.command_id,
|
||||
}),
|
||||
},
|
||||
)?;
|
||||
Ok(ok_response(&context, 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_QUERY_FIXTURES_JSON",
|
||||
r#"{"sidebar:datasetList":{"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"}]},"bridgeLogs:listWorkspaceOverview":{"workspace_id":"ws_demo","command_logs":[{"command_id":"cmd_1","request_id":"req_1","status":"applied","created_at":"2026-04-16T00:00:00Z"}],"domain_events":[{"command_id":"cmd_1","status":"published","created_at":"2026-04-16T00:00:00Z"}],"next_cursor":null,"has_more":false,"filters":{"command_status":null,"event_status":null,"target_page_id":null,"target_block_id":null,"aggregate_type":null,"aggregate_id":null},"generated_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,
|
||||
allow_dev_fixtures: true,
|
||||
dev_user_id: "dev-user".into(),
|
||||
dev_user_name: "开发用户".into(),
|
||||
dev_user_email: "dev@mnote.local".into(),
|
||||
}))
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn bridge_workspace_route_returns_runtime_result() {
|
||||
let response = app()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.uri("/api/bridge/workspace?workspaceId=ws_demo")
|
||||
.body(Body::empty())
|
||||
.expect("request"),
|
||||
)
|
||||
.await
|
||||
.expect("response");
|
||||
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,18 @@
|
||||
use crate::app::AppState;
|
||||
use crate::context::RequestContext;
|
||||
use crate::error::WebError;
|
||||
use crate::routes::query_support::{
|
||||
execute_runtime_query_against_data, fetch_query_data_via_convex, resolve_effective_workspace_id,
|
||||
};
|
||||
use axum::extract::Query;
|
||||
use axum::extract::{Extension, State};
|
||||
use axum::http::StatusCode;
|
||||
use axum::Json;
|
||||
use bridge_runtime::RuntimeQueryEnvelopeWire;
|
||||
use core_protocol::{KernelNodeType, KernelProjectionKind};
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -16,6 +26,12 @@ pub struct CompatBoundaryResponse {
|
||||
pub notes: Vec<&'static str>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CompatSidebarQuery {
|
||||
pub workspace_id: Option<String>,
|
||||
}
|
||||
|
||||
pub async fn next_ai_agent_run(
|
||||
State(state): State<AppState>,
|
||||
Extension(context): Extension<RequestContext>,
|
||||
@@ -33,3 +49,103 @@ pub async fn next_ai_agent_run(
|
||||
],
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn next_sidebar(
|
||||
State(state): State<AppState>,
|
||||
Extension(context): Extension<RequestContext>,
|
||||
Query(query): Query<CompatSidebarQuery>,
|
||||
) -> Result<(StatusCode, Json<Value>), WebError> {
|
||||
let effective_workspace_id =
|
||||
resolve_effective_workspace_id(&context, query.workspace_id.as_deref(), true)?
|
||||
.expect("workspace_required 已确保存在");
|
||||
|
||||
let dataset = fetch_query_data_via_convex(
|
||||
state.config(),
|
||||
&context,
|
||||
Some(&effective_workspace_id),
|
||||
RuntimeQueryEnvelopeWire {
|
||||
name: "sidebar.dataset.list".into(),
|
||||
payload: json!({
|
||||
"workspaceId": effective_workspace_id,
|
||||
}),
|
||||
},
|
||||
)?;
|
||||
let projection = execute_runtime_query_against_data(
|
||||
&context,
|
||||
Some(&effective_workspace_id),
|
||||
RuntimeQueryEnvelopeWire {
|
||||
name: "kernel.project_view".into(),
|
||||
payload: json!({
|
||||
"projection": KernelProjectionKind::SidebarTree,
|
||||
"workspaceId": effective_workspace_id,
|
||||
"includeEdges": true,
|
||||
"includeContent": false,
|
||||
"nodeTypes": [KernelNodeType::Page],
|
||||
}),
|
||||
},
|
||||
dataset.clone(),
|
||||
)?;
|
||||
|
||||
let mut dataset_object = dataset.as_object().cloned().ok_or_else(|| {
|
||||
WebError::bad_gateway_code("convex_bad_response", "sidebar.dataset.list 返回值不是对象")
|
||||
.with_context(&context)
|
||||
.with_header("x-error-phase", "compat_sidebar_shape")
|
||||
.with_header("x-upstream-service", "convex")
|
||||
})?;
|
||||
dataset_object.insert("kernel_sidebar_projection".into(), projection);
|
||||
|
||||
Ok((
|
||||
StatusCode::OK,
|
||||
Json(json!({
|
||||
"ok": true,
|
||||
"boundary": "next_sidebar_compat",
|
||||
"requestId": context.trace.request_id,
|
||||
"traceId": context.trace.trace_id,
|
||||
"workspaceId": effective_workspace_id,
|
||||
"result": Value::Object(dataset_object),
|
||||
})),
|
||||
))
|
||||
}
|
||||
|
||||
#[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_QUERY_FIXTURES_JSON",
|
||||
r#"{"sidebar:datasetList":{"active_workspace_id":"ws_demo","workspaces":[],"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"}],"trashed_documents":[],"media_assets":[],"trashed_media_assets":[],"mindmap_assets":[],"trashed_mindmap_assets":[],"table_assets":[],"trashed_table_assets":[],"mindmap_docs":[],"mindmap_asset_children":{}},"bridgeLogs:listWorkspaceOverview":{"workspace_id":"ws_demo","command_logs":[],"domain_events":[],"next_cursor":null,"has_more":false,"filters":{"command_status":null,"event_status":null,"target_page_id":null,"target_block_id":null,"aggregate_type":null,"aggregate_id":null},"generated_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,
|
||||
allow_dev_fixtures: true,
|
||||
dev_user_id: "dev-user".into(),
|
||||
dev_user_name: "开发用户".into(),
|
||||
dev_user_email: "dev@mnote.local".into(),
|
||||
}))
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn compat_sidebar_route_returns_dataset_and_projection() {
|
||||
let response = app()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.uri("/api/compat/next/sidebar?workspaceId=ws_demo")
|
||||
.body(Body::empty())
|
||||
.expect("request"),
|
||||
)
|
||||
.await
|
||||
.expect("response");
|
||||
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,18 +1,16 @@
|
||||
use crate::app::{AppConfig, AppState};
|
||||
use crate::context::RequestContext;
|
||||
use crate::error::WebError;
|
||||
use crate::transport::convex::execute_sidebar_dataset_query;
|
||||
use crate::routes::query_support::{
|
||||
execute_runtime_query_against_data, fetch_query_data_via_convex, resolve_effective_workspace_id,
|
||||
};
|
||||
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 bridge_runtime::RuntimeQueryEnvelopeWire;
|
||||
use core_protocol::{KernelGraphDirection, KernelNodeType, KernelProjectionKind};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Value};
|
||||
use std::env;
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -45,86 +43,47 @@ pub struct KernelGraphQuery {
|
||||
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 sidebar_dataset_query(workspace_id: &str) -> RuntimeQueryEnvelopeWire {
|
||||
RuntimeQueryEnvelopeWire {
|
||||
name: "sidebar.dataset.list".into(),
|
||||
payload: json!({
|
||||
"workspaceId": workspace_id,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
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>,
|
||||
workspace_id: &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)
|
||||
fetch_query_data_via_convex(
|
||||
config,
|
||||
context,
|
||||
Some(workspace_id),
|
||||
sidebar_dataset_query(workspace_id),
|
||||
)
|
||||
}
|
||||
|
||||
fn execute_kernel_query(
|
||||
context: &RequestContext,
|
||||
workspace_id: &str,
|
||||
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))
|
||||
execute_runtime_query_against_data(context, Some(workspace_id), query, dataset)
|
||||
}
|
||||
|
||||
fn ok_response(context: &RequestContext, result: Value) -> (StatusCode, Json<Value>) {
|
||||
(
|
||||
StatusCode::OK,
|
||||
Json(json!({
|
||||
"ok": true,
|
||||
"requestId": context.trace.request_id,
|
||||
"traceId": context.trace.trace_id,
|
||||
"result": result,
|
||||
})),
|
||||
)
|
||||
}
|
||||
|
||||
pub async fn project_sidebar(
|
||||
@@ -132,14 +91,18 @@ pub async fn project_sidebar(
|
||||
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 effective_workspace_id =
|
||||
resolve_effective_workspace_id(&context, query.workspace_id.as_deref(), true)?
|
||||
.expect("workspace_required 已确保存在");
|
||||
let dataset = load_sidebar_dataset(state.config(), &context, &effective_workspace_id)?;
|
||||
let result = execute_kernel_query(
|
||||
&context,
|
||||
&effective_workspace_id,
|
||||
RuntimeQueryEnvelopeWire {
|
||||
name: "kernel.project_view".into(),
|
||||
payload: json!({
|
||||
"projection": KernelProjectionKind::SidebarTree,
|
||||
"workspaceId": query.workspace_id,
|
||||
"workspaceId": effective_workspace_id,
|
||||
"rootNodeId": query.root_node_id,
|
||||
"depth": query.depth,
|
||||
"includeEdges": true,
|
||||
@@ -150,12 +113,7 @@ pub async fn project_sidebar(
|
||||
dataset,
|
||||
)?;
|
||||
|
||||
Ok((StatusCode::OK, Json(json!({
|
||||
"ok": true,
|
||||
"requestId": context.trace.request_id,
|
||||
"traceId": context.trace.trace_id,
|
||||
"result": result,
|
||||
}))))
|
||||
Ok(ok_response(&context, result))
|
||||
}
|
||||
|
||||
pub async fn subtree(
|
||||
@@ -163,13 +121,17 @@ pub async fn subtree(
|
||||
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 effective_workspace_id =
|
||||
resolve_effective_workspace_id(&context, query.workspace_id.as_deref(), true)?
|
||||
.expect("workspace_required 已确保存在");
|
||||
let dataset = load_sidebar_dataset(state.config(), &context, &effective_workspace_id)?;
|
||||
let result = execute_kernel_query(
|
||||
&context,
|
||||
&effective_workspace_id,
|
||||
RuntimeQueryEnvelopeWire {
|
||||
name: "kernel.subtree.get".into(),
|
||||
payload: json!({
|
||||
"workspaceId": query.workspace_id,
|
||||
"workspaceId": effective_workspace_id,
|
||||
"rootNodeId": query.root_node_id,
|
||||
"depth": query.depth,
|
||||
"includeEdges": true,
|
||||
@@ -178,12 +140,7 @@ pub async fn subtree(
|
||||
},
|
||||
dataset,
|
||||
)?;
|
||||
Ok((StatusCode::OK, Json(json!({
|
||||
"ok": true,
|
||||
"requestId": context.trace.request_id,
|
||||
"traceId": context.trace.trace_id,
|
||||
"result": result,
|
||||
}))))
|
||||
Ok(ok_response(&context, result))
|
||||
}
|
||||
|
||||
pub async fn edges(
|
||||
@@ -191,25 +148,24 @@ pub async fn edges(
|
||||
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 effective_workspace_id =
|
||||
resolve_effective_workspace_id(&context, query.workspace_id.as_deref(), true)?
|
||||
.expect("workspace_required 已确保存在");
|
||||
let dataset = load_sidebar_dataset(state.config(), &context, &effective_workspace_id)?;
|
||||
let result = execute_kernel_query(
|
||||
&context,
|
||||
&effective_workspace_id,
|
||||
RuntimeQueryEnvelopeWire {
|
||||
name: "kernel.edges.list".into(),
|
||||
payload: json!({
|
||||
"workspaceId": query.workspace_id,
|
||||
"workspaceId": effective_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,
|
||||
}))))
|
||||
Ok(ok_response(&context, result))
|
||||
}
|
||||
|
||||
pub async fn graph(
|
||||
@@ -217,13 +173,17 @@ pub async fn graph(
|
||||
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 effective_workspace_id =
|
||||
resolve_effective_workspace_id(&context, query.workspace_id.as_deref(), true)?
|
||||
.expect("workspace_required 已确保存在");
|
||||
let dataset = load_sidebar_dataset(state.config(), &context, &effective_workspace_id)?;
|
||||
let result = execute_kernel_query(
|
||||
&context,
|
||||
&effective_workspace_id,
|
||||
RuntimeQueryEnvelopeWire {
|
||||
name: "kernel.graph.traverse".into(),
|
||||
payload: json!({
|
||||
"workspaceId": query.workspace_id,
|
||||
"workspaceId": effective_workspace_id,
|
||||
"startNodeId": query.start_node_id,
|
||||
"maxDepth": query.max_depth.unwrap_or(2),
|
||||
"edgeTypes": [],
|
||||
@@ -231,12 +191,7 @@ pub async fn graph(
|
||||
},
|
||||
dataset,
|
||||
)?;
|
||||
Ok((StatusCode::OK, Json(json!({
|
||||
"ok": true,
|
||||
"requestId": context.trace.request_id,
|
||||
"traceId": context.trace.trace_id,
|
||||
"result": result,
|
||||
}))))
|
||||
Ok(ok_response(&context, result))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -248,8 +203,8 @@ mod tests {
|
||||
|
||||
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"}]}"#,
|
||||
"MNOTE_WEB_QUERY_FIXTURES_JSON",
|
||||
r#"{"sidebar:datasetList":{"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"}]},"bridgeLogs:listWorkspaceOverview":{"workspace_id":"ws_demo","command_logs":[{"command_id":"cmd_1","request_id":"req_1","status":"applied","created_at":"2026-04-16T00:00:00Z"}],"domain_events":[{"command_id":"cmd_1","status":"published","created_at":"2026-04-16T00:00:00Z"}],"next_cursor":null,"has_more":false,"filters":{"command_status":null,"event_status":null,"target_page_id":null,"target_block_id":null,"aggregate_type":null,"aggregate_id":null},"generated_at":"2026-04-16T00:00:00Z"}}"#,
|
||||
);
|
||||
build_app(AppState::new(AppConfig {
|
||||
service_name: "mnote-web".into(),
|
||||
@@ -259,6 +214,7 @@ mod tests {
|
||||
compat_next_base_path: "/api/compat/next".into(),
|
||||
convex_url: None,
|
||||
convex_admin_key: None,
|
||||
allow_dev_fixtures: true,
|
||||
dev_user_id: "dev-user".into(),
|
||||
dev_user_name: "开发用户".into(),
|
||||
dev_user_email: "dev@mnote.local".into(),
|
||||
@@ -270,7 +226,7 @@ mod tests {
|
||||
let response = app()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.uri("/api/kernel/projections/sidebar?rootNodeId=page_root")
|
||||
.uri("/api/kernel/projections/sidebar?workspaceId=ws_demo&rootNodeId=page_root")
|
||||
.body(Body::empty())
|
||||
.expect("request"),
|
||||
)
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
mod bridge;
|
||||
mod compat;
|
||||
mod health;
|
||||
mod hermes;
|
||||
mod kernel;
|
||||
mod query_support;
|
||||
mod sse;
|
||||
mod ws;
|
||||
|
||||
@@ -15,10 +17,16 @@ pub fn build_router(state: AppState) -> Router {
|
||||
|
||||
Router::new()
|
||||
.route("/health", get(health::health))
|
||||
.route("/api/kernel/projections/sidebar", get(kernel::project_sidebar))
|
||||
.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/bridge/workspace", get(bridge::workspace))
|
||||
.route("/api/bridge/request", get(bridge::request))
|
||||
.route("/api/bridge/trace", get(bridge::trace))
|
||||
.route("/api/stream/events", get(sse::events))
|
||||
.route("/api/realtime/ws", get(ws::socket))
|
||||
.nest(
|
||||
@@ -29,7 +37,9 @@ pub fn build_router(state: AppState) -> Router {
|
||||
)
|
||||
.nest(
|
||||
&compat_next_base_path,
|
||||
Router::new().route("/ai-agent/run", post(compat::next_ai_agent_run)),
|
||||
Router::new()
|
||||
.route("/ai-agent/run", post(compat::next_ai_agent_run))
|
||||
.route("/sidebar", get(compat::next_sidebar)),
|
||||
)
|
||||
.with_state(state)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
use crate::app::AppConfig;
|
||||
use crate::context::RequestContext;
|
||||
use crate::error::WebError;
|
||||
use crate::transport::convex::execute_convex_query_plan;
|
||||
use bridge_runtime::{
|
||||
execute_runtime_input, execute_runtime_query, RuntimeActorWire, RuntimeBridgeContextWire,
|
||||
RuntimeExecutionPlan, RuntimeInput, RuntimeQueryEnvelopeWire, RuntimeQueryExecutionPlan,
|
||||
RuntimeSourceWire,
|
||||
};
|
||||
use serde_json::Value;
|
||||
|
||||
pub fn resolve_effective_workspace_id(
|
||||
context: &RequestContext,
|
||||
query_workspace_id: Option<&str>,
|
||||
require_workspace: bool,
|
||||
) -> Result<Option<String>, WebError> {
|
||||
let query_workspace_id = query_workspace_id
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty());
|
||||
let header_workspace_id = context
|
||||
.workspace
|
||||
.workspace_id
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty());
|
||||
|
||||
if let (Some(query_id), Some(header_id)) = (query_workspace_id, header_workspace_id) {
|
||||
if query_id != header_id {
|
||||
return Err(WebError::bad_request_code(
|
||||
"workspace_context_conflict",
|
||||
format!("workspaceId 参数与请求头中的 workspace 不一致: {query_id} != {header_id}"),
|
||||
)
|
||||
.with_context(context)
|
||||
.with_header("x-error-phase", "workspace_resolve"));
|
||||
}
|
||||
}
|
||||
|
||||
let effective_workspace_id = query_workspace_id.or(header_workspace_id);
|
||||
if require_workspace && effective_workspace_id.is_none() {
|
||||
return Err(WebError::bad_request_code(
|
||||
"workspace_required",
|
||||
"缺少 workspaceId,请在 query 或请求头中提供有效工作区",
|
||||
)
|
||||
.with_context(context)
|
||||
.with_header("x-error-phase", "workspace_resolve"));
|
||||
}
|
||||
|
||||
Ok(effective_workspace_id.map(ToOwned::to_owned))
|
||||
}
|
||||
|
||||
pub fn runtime_context(
|
||||
context: &RequestContext,
|
||||
effective_workspace_id: Option<&str>,
|
||||
) -> RuntimeBridgeContextWire {
|
||||
RuntimeBridgeContextWire {
|
||||
deployment_id: context.workspace.deployment_id.clone(),
|
||||
project_id: context.workspace.project_id.clone(),
|
||||
workspace_id: effective_workspace_id
|
||||
.map(ToOwned::to_owned)
|
||||
.or_else(|| 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,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn build_runtime_query_plan(
|
||||
context: &RequestContext,
|
||||
effective_workspace_id: Option<&str>,
|
||||
query: RuntimeQueryEnvelopeWire,
|
||||
) -> Result<RuntimeQueryExecutionPlan, WebError> {
|
||||
let runtime_input = RuntimeInput::Query {
|
||||
context: runtime_context(context, effective_workspace_id),
|
||||
query,
|
||||
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("runtime query 未返回 query plan").with_context(context));
|
||||
};
|
||||
|
||||
Ok(plan)
|
||||
}
|
||||
|
||||
pub fn fetch_query_data_via_convex(
|
||||
config: &AppConfig,
|
||||
context: &RequestContext,
|
||||
effective_workspace_id: Option<&str>,
|
||||
query: RuntimeQueryEnvelopeWire,
|
||||
) -> Result<Value, WebError> {
|
||||
let plan = build_runtime_query_plan(context, effective_workspace_id, query)?;
|
||||
execute_convex_query_plan(config, context, &plan)
|
||||
}
|
||||
|
||||
pub fn execute_runtime_query_against_data(
|
||||
context: &RequestContext,
|
||||
effective_workspace_id: Option<&str>,
|
||||
query: RuntimeQueryEnvelopeWire,
|
||||
data: Value,
|
||||
) -> Result<Value, WebError> {
|
||||
execute_runtime_query(RuntimeInput::Query {
|
||||
context: runtime_context(context, effective_workspace_id),
|
||||
query,
|
||||
data: Some(data),
|
||||
})
|
||||
.map_err(|error| WebError::bad_request(error.message).with_context(context))
|
||||
}
|
||||
|
||||
pub fn execute_runtime_query_via_convex(
|
||||
config: &AppConfig,
|
||||
context: &RequestContext,
|
||||
effective_workspace_id: Option<&str>,
|
||||
query: RuntimeQueryEnvelopeWire,
|
||||
) -> Result<Value, WebError> {
|
||||
let data = fetch_query_data_via_convex(config, context, effective_workspace_id, query.clone())?;
|
||||
execute_runtime_query_against_data(context, effective_workspace_id, query, data)
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
use crate::app::AppConfig;
|
||||
use crate::context::RequestContext;
|
||||
use crate::error::WebError;
|
||||
use base64::engine::general_purpose::STANDARD;
|
||||
use base64::Engine;
|
||||
@@ -7,6 +8,12 @@ use serde_json::{json, Value};
|
||||
use std::fs;
|
||||
use std::time::Duration;
|
||||
|
||||
const HEADER_REQUEST_ID: &str = "x-request-id";
|
||||
const HEADER_TRACE_ID: &str = "x-trace-id";
|
||||
const HEADER_WORKSPACE_ID: &str = "x-mnote-workspace-id";
|
||||
const HEADER_SOURCE_CHANNEL: &str = "x-mnote-source-channel";
|
||||
const HEADER_SOURCE_CLIENT: &str = "x-mnote-source-client";
|
||||
|
||||
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();
|
||||
@@ -38,12 +45,30 @@ fn read_env_or_dotenv(key: &str) -> Option<String> {
|
||||
None
|
||||
}
|
||||
|
||||
fn build_authorization(config: &AppConfig) -> Result<String, WebError> {
|
||||
fn build_authorization(config: &AppConfig, context: &RequestContext) -> Result<String, WebError> {
|
||||
if let Some(authorization) = context
|
||||
.auth
|
||||
.authorization
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty())
|
||||
{
|
||||
return Ok(authorization.to_string());
|
||||
}
|
||||
|
||||
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"))?;
|
||||
.ok_or_else(|| {
|
||||
WebError::service_unavailable_code(
|
||||
"convex_config_missing",
|
||||
"缺少 CONVEX_SELF_HOSTED_ADMIN_KEY,且请求未携带 Authorization",
|
||||
)
|
||||
.with_context(context)
|
||||
.with_header("x-error-phase", "convex_auth")
|
||||
.with_header("x-upstream-service", "convex")
|
||||
})?;
|
||||
|
||||
let identity = json!({
|
||||
"subject": config.dev_user_id,
|
||||
@@ -60,7 +85,7 @@ fn build_authorization(config: &AppConfig) -> Result<String, WebError> {
|
||||
Ok(format!("Convex {admin_key}:{encoded}"))
|
||||
}
|
||||
|
||||
fn convex_url(config: &AppConfig) -> Result<String, WebError> {
|
||||
fn convex_url(config: &AppConfig, context: &RequestContext) -> Result<String, WebError> {
|
||||
config
|
||||
.convex_url
|
||||
.clone()
|
||||
@@ -68,18 +93,62 @@ fn convex_url(config: &AppConfig) -> Result<String, WebError> {
|
||||
.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"))
|
||||
.ok_or_else(|| {
|
||||
WebError::service_unavailable_code(
|
||||
"convex_config_missing",
|
||||
"缺少 CONVEX_SELF_HOSTED_URL / NEXT_PUBLIC_CONVEX_URL",
|
||||
)
|
||||
.with_context(context)
|
||||
.with_header("x-error-phase", "convex_url")
|
||||
.with_header("x-upstream-service", "convex")
|
||||
})
|
||||
}
|
||||
|
||||
pub fn execute_sidebar_dataset_query(
|
||||
fn load_query_fixture(
|
||||
config: &AppConfig,
|
||||
context: &RequestContext,
|
||||
plan: &RuntimeQueryExecutionPlan,
|
||||
) -> Result<Option<Value>, WebError> {
|
||||
if !config.allow_dev_fixtures {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let Ok(raw) = std::env::var("MNOTE_WEB_QUERY_FIXTURES_JSON") else {
|
||||
return Ok(None);
|
||||
};
|
||||
let trimmed = raw.trim();
|
||||
if trimmed.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let fixtures: Value = serde_json::from_str(trimmed).map_err(|error| {
|
||||
WebError::internal(format!("MNOTE_WEB_QUERY_FIXTURES_JSON 非法: {error}"))
|
||||
.with_context(context)
|
||||
.with_header("x-error-phase", "fixture_parse")
|
||||
})?;
|
||||
|
||||
Ok(fixtures
|
||||
.as_object()
|
||||
.and_then(|map| map.get(plan.function_name.as_str()))
|
||||
.cloned())
|
||||
}
|
||||
|
||||
pub fn execute_convex_query_plan(
|
||||
config: &AppConfig,
|
||||
context: &RequestContext,
|
||||
plan: &RuntimeQueryExecutionPlan,
|
||||
) -> Result<Value, WebError> {
|
||||
if plan.function_name != "sidebar:datasetList" {
|
||||
return Err(WebError::bad_request(format!(
|
||||
"mnote-web transport 暂不支持 query: {}",
|
||||
plan.function_name
|
||||
)));
|
||||
if plan.function_name.trim().is_empty() || plan.function_name.ends_with(":unknown") {
|
||||
return Err(WebError::bad_request_code(
|
||||
"transport_query_unsupported",
|
||||
format!("mnote-web transport 暂不支持 query: {}", plan.function_name),
|
||||
)
|
||||
.with_context(context)
|
||||
.with_header("x-error-phase", "plan_validation"));
|
||||
}
|
||||
|
||||
if let Some(fixture) = load_query_fixture(config, context, plan)? {
|
||||
return Ok(fixture);
|
||||
}
|
||||
|
||||
let payload = json!({
|
||||
@@ -91,37 +160,99 @@ pub fn execute_sidebar_dataset_query(
|
||||
let client = reqwest::blocking::Client::builder()
|
||||
.timeout(Duration::from_secs(20))
|
||||
.build()
|
||||
.map_err(|error| WebError::internal(format!("Convex HTTP 客户端创建失败: {error}")))?;
|
||||
.map_err(|error| {
|
||||
WebError::internal(format!("Convex HTTP 客户端创建失败: {error}"))
|
||||
.with_context(context)
|
||||
.with_header("x-error-phase", "client_build")
|
||||
.with_header("x-upstream-service", "convex")
|
||||
})?;
|
||||
|
||||
let response = client
|
||||
.post(format!("{}/api/query", convex_url(config)?))
|
||||
.header("Authorization", build_authorization(config)?)
|
||||
let mut request = client
|
||||
.post(format!("{}/api/query", convex_url(config, context)?))
|
||||
.header("Authorization", build_authorization(config, context)?)
|
||||
.header("Content-Type", "application/json")
|
||||
.header("Convex-Client", "mnote-web")
|
||||
.json(&payload)
|
||||
.send()
|
||||
.map_err(|error| WebError::internal(format!("Convex query 请求失败: {error}")))?;
|
||||
.header(HEADER_REQUEST_ID, &context.trace.request_id)
|
||||
.header(HEADER_TRACE_ID, &context.trace.trace_id)
|
||||
.header(HEADER_SOURCE_CHANNEL, context.source.channel.as_str())
|
||||
.header(HEADER_SOURCE_CLIENT, context.source.client.as_str())
|
||||
.json(&payload);
|
||||
|
||||
if let Some(workspace_id) = plan
|
||||
.workspace_id
|
||||
.as_deref()
|
||||
.or(context.workspace.workspace_id.as_deref())
|
||||
{
|
||||
request = request.header(HEADER_WORKSPACE_ID, workspace_id);
|
||||
}
|
||||
|
||||
let response = request.send().map_err(|error| {
|
||||
let base = if error.is_timeout() {
|
||||
WebError::gateway_timeout_code("convex_timeout", format!("Convex query 超时: {error}"))
|
||||
} else {
|
||||
WebError::service_unavailable_code(
|
||||
"convex_unavailable",
|
||||
format!("Convex query 请求失败: {error}"),
|
||||
)
|
||||
};
|
||||
base.with_context(context)
|
||||
.with_header("x-error-phase", "query_send")
|
||||
.with_header("x-upstream-service", "convex")
|
||||
})?;
|
||||
|
||||
let status = response.status();
|
||||
let body: Value = response
|
||||
.json()
|
||||
.map_err(|error| WebError::internal(format!("Convex 响应解析失败: {error}")))?;
|
||||
let body: Value = response.json().map_err(|error| {
|
||||
WebError::bad_gateway_code(
|
||||
"convex_bad_response",
|
||||
format!("Convex 响应解析失败: {error}"),
|
||||
)
|
||||
.with_context(context)
|
||||
.with_header("x-error-phase", "query_decode")
|
||||
.with_header("x-upstream-service", "convex")
|
||||
.with_header("x-upstream-status", status.as_u16().to_string())
|
||||
})?;
|
||||
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()));
|
||||
return Err(
|
||||
WebError::bad_gateway_code("convex_upstream_error", message.to_string())
|
||||
.with_context(context)
|
||||
.with_header("x-error-phase", "query_status")
|
||||
.with_header("x-upstream-service", "convex")
|
||||
.with_header("x-upstream-status", status.as_u16().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(
|
||||
Some("error") => Err(WebError::bad_gateway_code(
|
||||
"convex_upstream_error",
|
||||
body.get("errorMessage")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("Convex 返回 error")
|
||||
.to_string(),
|
||||
)),
|
||||
_ => Err(WebError::internal(format!("未知 Convex 响应: {body}"))),
|
||||
)
|
||||
.with_context(context)
|
||||
.with_header("x-error-phase", "query_payload")
|
||||
.with_header("x-upstream-service", "convex")
|
||||
.with_header("x-upstream-status", status.as_u16().to_string())),
|
||||
_ => Err(WebError::bad_gateway_code(
|
||||
"convex_bad_response",
|
||||
format!("未知 Convex 响应: {body}"),
|
||||
)
|
||||
.with_context(context)
|
||||
.with_header("x-error-phase", "query_payload")
|
||||
.with_header("x-upstream-service", "convex")
|
||||
.with_header("x-upstream-status", status.as_u16().to_string())),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn execute_sidebar_dataset_query(
|
||||
config: &AppConfig,
|
||||
context: &RequestContext,
|
||||
plan: &RuntimeQueryExecutionPlan,
|
||||
) -> Result<Value, WebError> {
|
||||
execute_convex_query_plan(config, context, plan)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user