128 lines
4.3 KiB
Rust
128 lines
4.3 KiB
Rust
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}"))),
|
||
|
|
}
|
||
|
|
}
|