use std::any::Any;
use std::fs;
use std::time::Duration;
use ek_core::error::AskError;
use serde_json::{json, Value};
use crate::api::ApiPlugin;
use crate::profile;
use crate::proto::{self, RpcError, BUS_STOPPED, CONFIG_REJECTED};
const ASK_TIMEOUT: Duration = Duration::from_millis(1500);
pub fn dispatch(
api: &ApiPlugin,
method: &str,
params: &Value,
user: &str,
conn_id: u64,
) -> Result<Value, RpcError> {
match method {
"sys.info" => sys_info(api),
"sys.catalog" => sys_catalog(api),
"plugin.list" => plugin_list(api),
"plugin.catalog" => plugin_catalog(api),
"plugin.meta" => plugin_meta(api, params),
"plugin.start" => plugin_start(api, params, user),
"plugin.remove" => plugin_remove(api, params, user),
"plugin.restart" => plugin_restart(api, params, user),
"profile.get" => profile_get(api),
"profile.set" => profile_set(api, params, user),
"profile.activate" => profile_activate(api, params, user),
"cfg.list" => cfg_list(api),
"cfg.get" => cfg_get(api, params),
"cfg.schema" => cfg_schema(api, params),
"cfg.save" => cfg_save(api, params, user),
"cfg.delete" => cfg_delete(api, params, user),
"cfg.apply" => cfg_apply(api, params, user),
"secret.put" => secret_put(api, params, user),
"secret.state" => secret_state(params),
"log.tail" => log_tail(api, params),
"log.query" => log_query(api, params),
"audit.list" => audit_list(api, params),
"account.list" => account_list(api),
"account.add" => account_add(api, params, user),
"account.remove" => account_remove(api, params, user),
"account.test" => account_test(api, params),
"bundle.export" => bundle_export(api, params, user),
"bundle.import" => bundle_import(api, params, user),
"sub.subscribe" => sub_subscribe(api, params, conn_id),
"sub.unsubscribe" => sub_unsubscribe(api, params, conn_id),
"sub.list" => sub_list(api, conn_id),
"oms.orders" | "oms.trades" | "oms.positions" | "oms.accounts" | "oms.contracts"
| "oms.active_orders" => oms_query(api, method, params),
"oms.order" | "oms.trade" | "oms.position" | "oms.account" | "oms.contract" => {
oms_one(api, method, params)
}
"trade.check" => trade_check(api, params),
"trade.submit" => trade_submit(api, params, user),
"trade.cancel" => trade_cancel(api, params, user),
"dm.symbols" => dm_symbols(api),
"strategy.meta" => strategy_meta(api),
"strategy.settings" => strategy_settings(api, params),
"strategy.price" => strategy_price(api, params),
"strategy.resync" => strategy_resync(api),
"strategy.add" => strategy_add(api, params, user),
"strategy.init" => strategy_ask(
api,
"strategy.init",
ek_strategy::contract::InitReq::from(params_str(params, "name")?),
user,
),
"strategy.start" => strategy_ask(
api,
"strategy.start",
ek_strategy::contract::StartReq::from(params_str(params, "name")?),
user,
),
"strategy.pause" => strategy_ask(
api,
"strategy.pause",
ek_strategy::contract::PauseReq::from(params_str(params, "name")?),
user,
),
"strategy.resume" => strategy_ask(
api,
"strategy.resume",
ek_strategy::contract::ResumeReq::from(params_str(params, "name")?),
user,
),
"strategy.stop" => strategy_ask(
api,
"strategy.stop",
ek_strategy::contract::StopReq::from(params_str(params, "name")?),
user,
),
"strategy.remove" => strategy_ask(
api,
"strategy.remove",
ek_strategy::contract::RemoveReq::from(params_str(params, "name")?),
user,
),
"strategy.edit" => strategy_edit(api, params, user),
"strategy.start_all" => strategy_ask(
api,
"strategy.start_all",
ek_strategy::contract::StartAllReq,
user,
),
"strategy.stop_all" => strategy_ask(
api,
"strategy.stop_all",
ek_strategy::contract::StopAllReq,
user,
),
"strategy.set_engine" => strategy_set_engine(api, params, user),
"ctp.status" => ctp_status(api, params),
"ctp.credentials_state" => ctp_credentials(api, params),
"tq.klines" => tq_klines(api, params),
other => Err(RpcError::not_found(other)),
}
}
fn ctx(api: &ApiPlugin) -> Result<ek_core::context::PluginContext, RpcError> {
api.ctx()
.ok_or_else(|| RpcError::new(BUS_STOPPED, "宿主未就绪(插件尚未 on_init)"))
}
fn ask_service<Req, Res>(api: &ApiPlugin, svc: &str, req: Req) -> Result<Res, RpcError>
where
Req: Any + Send + Sync,
Res: Any + Send + Sync,
{
let c = ctx(api)?;
c.ask_service::<Req, Res>(svc, req, ASK_TIMEOUT)
.map_err(|e| map_ask(e, svc))
}
fn map_ask(e: AskError, svc: &str) -> RpcError {
match e {
AskError::UnknownService { .. } => RpcError::not_found(svc),
AskError::TargetGone { target } => {
RpcError::new(proto::TARGET_GONE, format!("目标不可达: {target}"))
}
AskError::Timeout { target, pending } => RpcError::new(
proto::TIMEOUT,
format!("目标超时: {target}(积压 {pending} 帧)"),
),
AskError::InvalidPayload { target } => {
RpcError::new(proto::INTERNAL_ERROR, format!("契约不匹配: {target}"))
}
AskError::BusStopped => RpcError::new(BUS_STOPPED, "总线已停"),
}
}
fn meta_of(api: &ApiPlugin, name: &str) -> Result<ek_station::wire::MetaRes, RpcError> {
ask_service::<ek_station::wire::MetaReq, ek_station::wire::MetaRes>(
api,
ek_station::wire::SVC_META,
ek_station::wire::MetaReq {
name: name.to_string(),
},
)
}
fn sys_info(api: &ApiPlugin) -> Result<Value, RpcError> {
let c = ctx(api)?;
let infos = c.plugins();
Ok(json!({
"ok": true,
"server": "ek-server",
"ver": crate::VERSION,
"profile": api.profile(),
"started_ms": api.started_ms(),
"uptime_ms": crate::server::now_ms().saturating_sub(api.started_ms()),
"plugins": infos.len(),
"conns": api.conns(),
"features": ["read"],
}))
}
fn sys_catalog(api: &ApiPlugin) -> Result<Value, RpcError> {
let c = ctx(api)?;
let mut infos = c.plugins();
infos.sort_by(|a, b| a.name.cmp(&b.name));
let mut services = Vec::new();
let mut total = 0usize;
for info in &infos {
if let Some(list) = c.services_of(&info.name) {
for d in list.iter() {
total += 1;
services.push(json!({
"plugin": info.name,
"service": d.id,
"version": info.version,
"doc": d.doc,
"req_type": d.req_type,
"res_type": d.res_type,
}));
}
}
}
Ok(json!({
"ok": true,
"count": total,
"plugins": infos.len(),
"services": services,
}))
}
fn plugin_list(api: &ApiPlugin) -> Result<Value, RpcError> {
let rows = ask_service::<ek_station::wire::ListReq, ek_station::wire::ListRes>(
api,
ek_station::wire::SVC_LIST,
ek_station::wire::ListReq,
)?;
let out: Vec<Value> = rows
.iter()
.map(|r| {
json!({
"name": r.name,
"version": r.version,
"state": r.state,
"deps": r.deps,
"spilled": r.spilled,
"panics": r.panics,
"pending": r.pending,
"peak": r.peak,
"soft_cap": r.soft_cap,
})
})
.collect();
Ok(json!({ "ok": true, "plugins": out }))
}
fn plugin_catalog(api: &ApiPlugin) -> Result<Value, RpcError> {
let rows = ask_service::<ek_station::wire::CatalogReq, ek_station::wire::CatalogRes>(
api,
ek_station::wire::SVC_CATALOG,
ek_station::wire::CatalogReq,
)?;
let out: Vec<Value> = rows
.iter()
.map(|r| json!({"name": r.name, "doc": r.doc, "named": r.named}))
.collect();
Ok(json!({ "ok": true, "factories": out }))
}
fn plugin_meta(api: &ApiPlugin, params: &Value) -> Result<Value, RpcError> {
let name = params
.get("name")
.and_then(Value::as_str)
.ok_or_else(|| RpcError::invalid_params("缺少 name"))?;
match meta_of(api, name)? {
ek_station::wire::MetaRes::Found {
name,
version,
kind,
state,
deps,
has_config,
ns,
config_fields,
config_view,
} => Ok(json!({
"ok": true,
"name": name,
"version": version,
"kind": kind,
"state": state,
"deps": deps,
"has_config": has_config,
"ns": ns,
"config_fields": config_fields.iter().map(field_json).collect::<Vec<_>>(),
"config_view": config_view.iter().map(|(k, v)| json!({"key": k, "value": v})).collect::<Vec<_>>(),
})),
ek_station::wire::MetaRes::NoSuchName { name } => {
Ok(json!({"ok": false, "reason": format!("无此插件: {name}")}))
}
}
}
fn field_json(f: &ek_core::cfg_face::ConfigField) -> Value {
use ek_core::cfg_face::ConfigKind;
let kind = match &f.kind {
ConfigKind::Int { min, max, unit } => {
json!({"kind": "int", "min": min, "max": max, "unit": unit})
}
ConfigKind::Float { min, max, unit } => {
json!({"kind": "float", "min": min, "max": max, "unit": unit})
}
ConfigKind::Bool => json!({"kind": "bool"}),
ConfigKind::Text { max_len } => json!({"kind": "text", "max_len": max_len}),
ConfigKind::CsvInt { min, max } => json!({"kind": "csv_int", "min": min, "max": max}),
ConfigKind::Enum { options } => json!({"kind": "enum", "options": options}),
ConfigKind::Secret => json!({"kind": "secret"}),
};
json!({
"key": f.key,
"label": f.label,
"kind": kind,
"default": f.default,
"help": f.help,
"needs_restart": f.needs_restart,
"group": f.group,
})
}
fn plugin_start(api: &ApiPlugin, params: &Value, user: &str) -> Result<Value, RpcError> {
let factory = params
.get("factory")
.and_then(Value::as_str)
.ok_or_else(|| RpcError::invalid_params("缺少 factory"))?;
let name = params
.get("name")
.and_then(Value::as_str)
.unwrap_or("")
.to_string();
let res = ask_service::<ek_station::wire::StartReq, ek_station::wire::StartRes>(
api,
ek_station::wire::SVC_START,
ek_station::wire::StartReq {
factory: factory.to_string(),
name: name.clone(),
},
)?;
match res {
ek_station::wire::StartRes::Started { name } => {
api.audit()
.log(user, "plugin.start", factory, true, &format!("name={name}"));
Ok(json!({"ok": true, "name": name}))
}
ek_station::wire::StartRes::Rejected { reason } => {
api.audit()
.log(user, "plugin.start", factory, false, &reason);
Ok(json!({"ok": false, "reason": reason}))
}
}
}
fn plugin_remove(api: &ApiPlugin, params: &Value, user: &str) -> Result<Value, RpcError> {
let name = params
.get("name")
.and_then(Value::as_str)
.ok_or_else(|| RpcError::invalid_params("缺少 name"))?;
let res = ask_service::<ek_station::wire::RemoveReq, ek_station::wire::RemoveRes>(
api,
ek_station::wire::SVC_REMOVE,
ek_station::wire::RemoveReq {
name: name.to_string(),
},
)?;
match res {
ek_station::wire::RemoveRes::Removed { name } => {
api.audit().log(user, "plugin.remove", &name, true, "");
Ok(json!({"ok": true, "name": name}))
}
ek_station::wire::RemoveRes::NoSuchName { name } => {
api.audit()
.log(user, "plugin.remove", &name, false, "no such name");
Ok(json!({"ok": false, "reason": format!("无此插件: {name}")}))
}
ek_station::wire::RemoveRes::Rejected { name, reason } => {
api.audit().log(user, "plugin.remove", &name, false, &reason);
Ok(json!({"ok": false, "name": name, "reason": reason}))
}
}
}
fn plugin_restart(api: &ApiPlugin, params: &Value, user: &str) -> Result<Value, RpcError> {
let name = params
.get("name")
.and_then(Value::as_str)
.ok_or_else(|| RpcError::invalid_params("缺少 name"))?;
let res = ask_service::<ek_station::wire::RestartReq, ek_station::wire::RestartRes>(
api,
ek_station::wire::SVC_RESTART,
ek_station::wire::RestartReq {
name: name.to_string(),
},
)?;
match res {
ek_station::wire::RestartRes::Restarted { name } => {
api.audit().log(user, "plugin.restart", &name, true, "");
Ok(json!({"ok": true, "name": name}))
}
ek_station::wire::RestartRes::NoSuchName { name } => {
api.audit()
.log(user, "plugin.restart", &name, false, "no such name");
Ok(json!({"ok": false, "reason": format!("无此插件: {name}")}))
}
ek_station::wire::RestartRes::Rejected { name, reason } => {
api.audit().log(user, "plugin.restart", &name, false, &reason);
Ok(json!({"ok": false, "name": name, "reason": reason}))
}
}
}
fn profile_get(api: &ApiPlugin) -> Result<Value, RpcError> {
let p = profile::read(api.store());
Ok(json!({
"ok": true,
"ns": profile::API_NS,
"profile": profile::to_json(&p),
}))
}
fn profile_set(api: &ApiPlugin, params: &Value, user: &str) -> Result<Value, RpcError> {
let p = profile::from_params(params).map_err(RpcError::invalid_params)?;
let map = profile::to_map(&p);
let res = ask_service::<ek_cfg::wire::SaveReq, ek_cfg::wire::SaveRes>(
api,
"cfg.save",
ek_cfg::wire::SaveReq {
ns: profile::API_NS.to_string(),
map,
},
)?;
if !res.ok {
api.audit()
.log(user, "profile.set", profile::API_NS, false, &res.msg);
return Err(RpcError::new(CONFIG_REJECTED, format!("落盘失败: {}", res.msg)));
}
api.audit().log(
user,
"profile.set",
profile::API_NS,
true,
&format!("plugins={}", p.plugins.len()),
);
Ok(json!({
"ok": true,
"ns": res.ns,
"warns": res.warns,
"profile": profile::to_json(&p),
}))
}
fn profile_activate(api: &ApiPlugin, params: &Value, user: &str) -> Result<Value, RpcError> {
let confirm = params
.get("confirm")
.and_then(Value::as_bool)
.unwrap_or(false);
if !confirm {
return Err(RpcError::new(
proto::CONFIRM_REQUIRED,
"危险操作:会中断运行中的插件;传 confirm:true 才执行",
));
}
let p = profile::read(api.store());
let c = ctx(api)?;
let running: Vec<String> = c.plugins().iter().map(|i| i.name.clone()).collect();
let mut started = Vec::new();
let mut removed = Vec::new();
let mut errors = Vec::new();
for factory in p.enabled() {
if running.iter().any(|n| n == &factory) {
continue;
}
match ask_service::<ek_station::wire::StartReq, ek_station::wire::StartRes>(
api,
ek_station::wire::SVC_START,
ek_station::wire::StartReq {
factory: factory.clone(),
name: String::new(),
},
) {
Ok(ek_station::wire::StartRes::Started { name }) => started.push(name),
Ok(ek_station::wire::StartRes::Rejected { reason }) => {
errors.push(json!({"factory": factory, "error": reason}));
}
Err(e) => errors.push(json!({"factory": factory, "error": e.to_string()})),
}
}
for name in running {
if name == "svctl" || name == "api" || name == "cfg" {
continue;
}
if !p.is_off(&name) {
continue;
}
match ask_service::<ek_station::wire::RemoveReq, ek_station::wire::RemoveRes>(
api,
ek_station::wire::SVC_REMOVE,
ek_station::wire::RemoveReq { name: name.clone() },
) {
Ok(ek_station::wire::RemoveRes::Removed { .. }) => removed.push(name),
Ok(_) => {}
Err(e) => errors.push(json!({"plugin": name, "error": e.to_string()})),
}
}
api.audit().log(
user,
"profile.activate",
profile::API_NS,
errors.is_empty(),
&format!("started={started:?} removed={removed:?}"),
);
Ok(json!({
"ok": errors.is_empty(),
"started": started,
"removed": removed,
"errors": errors,
}))
}
fn cfg_list(api: &ApiPlugin) -> Result<Value, RpcError> {
let names = api
.store()
.list_namespaces()
.map_err(|e| RpcError::new(CONFIG_REJECTED, format!("列配置段失败: {e}")))?;
Ok(json!({
"ok": true,
"root": api.store().root().display().to_string(),
"namespaces": names,
}))
}
fn cfg_get(api: &ApiPlugin, params: &Value) -> Result<Value, RpcError> {
let name = params
.get("plugin")
.and_then(Value::as_str)
.ok_or_else(|| RpcError::invalid_params("缺少 plugin"))?;
match meta_of(api, name)? {
ek_station::wire::MetaRes::Found {
name,
ns,
has_config,
config_fields,
config_view,
..
} => Ok(json!({
"ok": true,
"plugin": name,
"ns": ns,
"has_config": has_config,
"fields": config_fields.iter().map(field_json).collect::<Vec<_>>(),
"view": config_view.iter().map(|(k, v)| json!({"key": k, "value": v})).collect::<Vec<_>>(),
})),
ek_station::wire::MetaRes::NoSuchName { name } => {
Ok(json!({"ok": false, "reason": format!("无此插件: {name}")}))
}
}
}
fn cfg_schema(api: &ApiPlugin, params: &Value) -> Result<Value, RpcError> {
let name = params
.get("plugin")
.and_then(Value::as_str)
.ok_or_else(|| RpcError::invalid_params("缺少 plugin"))?;
match meta_of(api, name)? {
ek_station::wire::MetaRes::Found {
name,
ns,
has_config,
config_fields,
..
} => Ok(json!({
"ok": true,
"plugin": name,
"ns": ns,
"has_config": has_config,
"fields": config_fields.iter().map(field_json).collect::<Vec<_>>(),
})),
ek_station::wire::MetaRes::NoSuchName { name } => {
Ok(json!({"ok": false, "reason": format!("无此插件: {name}")}))
}
}
}
fn cfg_save(api: &ApiPlugin, params: &Value, user: &str) -> Result<Value, RpcError> {
let name = params
.get("plugin")
.and_then(Value::as_str)
.ok_or_else(|| RpcError::invalid_params("缺少 plugin"))?;
let values = params
.get("values")
.and_then(Value::as_object)
.ok_or_else(|| RpcError::invalid_params("缺少 values(键值对象)"))?;
let meta = meta_of(api, name)?;
let ek_station::wire::MetaRes::Found {
ns,
has_config,
config_fields,
..
} = meta
else {
return Ok(json!({"ok": false, "reason": format!("无此插件: {name}")}));
};
if !has_config {
return Ok(json!({"ok": false, "reason": format!("插件 {name} 无配置面(ns={ns})")}));
}
let mut pairs = ek_core::section::SectionMap::new(0);
for (k, v) in values {
let Some(raw) = v.as_str() else {
return Err(RpcError::invalid_params(format!("{k} 必须是字符串")));
};
let field = config_fields.iter().find(|f| &f.key == k);
if let Some(f) = field {
f.validate(raw)
.map_err(|e| RpcError::new(CONFIG_REJECTED, e))?;
}
let is_secret =
field.is_some_and(|f| matches!(&f.kind, ek_core::cfg_face::ConfigKind::Secret));
let fld = if is_secret {
let Some(rest) = raw.strip_prefix("secret://") else {
return Err(RpcError::new(
CONFIG_REJECTED,
format!("秘面键 {k} 只接受 secret:// 引用;明文密码请先调 secret.put"),
));
};
let sk = rest.rsplit('/').next().unwrap_or(k).to_string();
ek_core::section::Field::secret(sk)
} else {
ek_core::section::Field::plain(raw)
};
pairs = pairs.set(k.clone(), fld);
}
let res = ask_service::<ek_station::wire::ConfigApplyReq, ek_station::wire::ConfigApplyRes>(
api,
ek_station::wire::SVC_CONFIG,
ek_station::wire::ConfigApplyReq {
name: name.to_string(),
values: Some(pairs),
},
)?;
api.audit().log(
user,
"cfg.save",
&ns,
res.ok && res.saved,
&format!("keys={} deferred={:?} err={}", values.len(), res.deferred, res.error),
);
Ok(json!({
"ok": res.ok,
"ns": ns,
"saved": res.saved,
"adopted": res.adopted,
"deferred": res.deferred,
"error": res.error,
}))
}
fn cfg_delete(api: &ApiPlugin, params: &Value, user: &str) -> Result<Value, RpcError> {
let ns = params
.get("ns")
.and_then(Value::as_str)
.ok_or_else(|| RpcError::invalid_params("缺少 ns"))?;
let key = params
.get("key")
.and_then(Value::as_str)
.unwrap_or("")
.to_string();
let res = ask_service::<ek_cfg::wire::DeleteReq, ek_cfg::wire::DeleteRes>(
api,
"cfg.delete",
ek_cfg::wire::DeleteReq {
ns: ns.to_string(),
key: key.clone(),
},
)?;
api.audit().log(
user,
"cfg.delete",
ns,
res.ok,
&format!("key={key:?} removed_keys={}", res.removed_keys),
);
Ok(json!({
"ok": res.ok,
"ns": res.ns,
"removed_keys": res.removed_keys,
"removed_secrets": res.removed_secrets,
"msg": res.msg,
}))
}
fn cfg_apply(api: &ApiPlugin, params: &Value, user: &str) -> Result<Value, RpcError> {
let name = params
.get("plugin")
.and_then(Value::as_str)
.ok_or_else(|| RpcError::invalid_params("缺少 plugin"))?;
let res = ask_service::<ek_station::wire::ConfigApplyReq, ek_station::wire::ConfigApplyRes>(
api,
ek_station::wire::SVC_CONFIG,
ek_station::wire::ConfigApplyReq {
name: name.to_string(),
values: None,
},
)?;
api.audit().log(
user,
"cfg.apply",
name,
res.ok,
&format!("deferred={:?} err={}", res.deferred, res.error),
);
Ok(json!({
"ok": res.ok,
"saved": res.saved,
"adopted": res.adopted,
"deferred": res.deferred,
"error": res.error,
}))
}
fn secret_put(api: &ApiPlugin, params: &Value, user: &str) -> Result<Value, RpcError> {
let ns = params
.get("ns")
.and_then(Value::as_str)
.ok_or_else(|| RpcError::invalid_params("缺少 ns"))?;
let key = params
.get("key")
.and_then(Value::as_str)
.ok_or_else(|| RpcError::invalid_params("缺少 key"))?;
let value = params
.get("value")
.and_then(Value::as_str)
.ok_or_else(|| RpcError::invalid_params("缺少 value"))?;
let root = api.store().root().to_path_buf();
if ek_cfg::crypto::MasterKey::load(&root).is_err() {
ek_cfg::crypto::MasterKey::write_new(&root)
.map_err(|e| RpcError::new(CONFIG_REJECTED, format!("创建主密钥失败: {e}")))?;
}
ek_cfg::secret::register(ns, key, ek_cfg::secret::SecretValue::from_text(value))
.map_err(|e| RpcError::new(CONFIG_REJECTED, format!("写密库失败: {e}")))?;
let reference = format!("secret://ek/{ns}/{key}");
api.audit()
.log(user, "secret.put", &format!("{ns}/{key}"), true, "");
Ok(json!({"ok": true, "ref": reference}))
}
fn secret_state(params: &Value) -> Result<Value, RpcError> {
let ns = params
.get("ns")
.and_then(Value::as_str)
.ok_or_else(|| RpcError::invalid_params("缺少 ns"))?;
let key = params
.get("key")
.and_then(Value::as_str)
.ok_or_else(|| RpcError::invalid_params("缺少 key"))?;
let present = ek_cfg::secret::get_strict(ns, key)
.map_err(|e| RpcError::new(CONFIG_REJECTED, format!("读密库失败: {e}")))?
.is_some();
Ok(json!({
"ok": true,
"present": present,
"ref": format!("secret://ek/{ns}/{key}"),
}))
}
const DEFAULT_PAGE: usize = 200;
const MAX_PAGE: usize = 1000;
fn page(params: &Value) -> (usize, usize) {
let limit = params
.get("limit")
.and_then(Value::as_u64)
.unwrap_or(DEFAULT_PAGE as u64)
.clamp(1, MAX_PAGE as u64) as usize;
let offset = params.get("offset").and_then(Value::as_u64).unwrap_or(0) as usize;
(limit, offset)
}
fn page_out(rows: Vec<Value>, limit: usize, offset: usize) -> Value {
let total = rows.len();
let slice: Vec<Value> = rows.into_iter().skip(offset).take(limit).collect();
json!({"ok": true, "total": total, "limit": limit, "offset": offset, "rows": slice})
}
fn json_rows<T: serde::Serialize>(rows: Vec<T>) -> Vec<Value> {
rows.into_iter()
.filter_map(|r| serde_json::to_value(r).ok())
.collect()
}
fn filter_eq(rows: Vec<Value>, params: &Value, field: &str) -> Vec<Value> {
let Some(want) = params.get(field).and_then(Value::as_str) else {
return rows;
};
rows.into_iter()
.filter(|r| r.get(field).and_then(Value::as_str) == Some(want))
.collect()
}
fn oms_query(api: &ApiPlugin, method: &str, params: &Value) -> Result<Value, RpcError> {
let (limit, offset) = page(params);
let rows: Vec<Value> = match method {
"oms.orders" => {
let rows = ask_service::<ek_oms::plugin::GetAllOrdersReq, Vec<ek_data::OrderData>>(
api,
"oms.get_all_orders",
ek_oms::plugin::GetAllOrdersReq,
)?;
let rows = filter_eq(json_rows(rows), params, "gateway_name");
filter_eq(rows, params, "symbol")
}
"oms.trades" => {
let rows = ask_service::<ek_oms::plugin::GetAllTradesReq, Vec<ek_data::TradeData>>(
api,
"oms.get_all_trades",
ek_oms::plugin::GetAllTradesReq,
)?;
let rows = filter_eq(json_rows(rows), params, "gateway_name");
filter_eq(rows, params, "symbol")
}
"oms.positions" => {
let rows = ask_service::<ek_oms::plugin::GetAllPositionsReq, Vec<ek_data::PositionData>>(
api,
"oms.get_all_positions",
ek_oms::plugin::GetAllPositionsReq,
)?;
filter_eq(json_rows(rows), params, "symbol")
}
"oms.accounts" => {
let rows = ask_service::<ek_oms::plugin::GetAllAccountsReq, Vec<ek_data::AccountData>>(
api,
"oms.get_all_accounts",
ek_oms::plugin::GetAllAccountsReq,
)?;
filter_eq(json_rows(rows), params, "accountid")
}
"oms.contracts" => {
let rows = ask_service::<ek_oms::plugin::GetAllContractsReq, Vec<ek_data::ContractData>>(
api,
"oms.get_all_contracts",
ek_oms::plugin::GetAllContractsReq,
)?;
filter_eq(json_rows(rows), params, "symbol")
}
"oms.active_orders" => {
let en_symbol = params
.get("symbol")
.and_then(Value::as_str)
.map(str::to_string);
let rows = ask_service::<
ek_oms::plugin::GetAllActiveOrdersReq,
Vec<ek_data::OrderData>,
>(
api,
"oms.get_all_active_orders",
ek_oms::plugin::GetAllActiveOrdersReq { en_symbol },
)?;
json_rows(rows)
}
other => return Err(RpcError::not_found(other)),
};
Ok(page_out(rows, limit, offset))
}
fn oms_one(api: &ApiPlugin, method: &str, params: &Value) -> Result<Value, RpcError> {
let id = params
.get("id")
.and_then(Value::as_str)
.ok_or_else(|| RpcError::invalid_params("缺少 id"))?;
match method {
"oms.order" => {
let v = ask_service::<ek_oms::plugin::GetOrderReq, Option<ek_data::OrderData>>(
api,
"oms.get_order",
ek_oms::plugin::GetOrderReq {
en_orderid: id.to_string(),
},
)?;
let present = v.is_some();
Ok(json!({"ok": present, "row": v}))
}
"oms.trade" => {
let v = ask_service::<ek_oms::plugin::GetTradeReq, Option<ek_data::TradeData>>(
api,
"oms.get_trade",
ek_oms::plugin::GetTradeReq {
en_tradeid: id.to_string(),
},
)?;
let present = v.is_some();
Ok(json!({"ok": present, "row": v}))
}
"oms.position" => {
let v = ask_service::<ek_oms::plugin::GetPositionReq, Option<ek_data::PositionData>>(
api,
"oms.get_position",
ek_oms::plugin::GetPositionReq {
en_positionid: id.to_string(),
},
)?;
let present = v.is_some();
Ok(json!({"ok": present, "row": v}))
}
"oms.account" => {
let v = ask_service::<ek_oms::plugin::GetAccountReq, Option<ek_data::AccountData>>(
api,
"oms.get_account",
ek_oms::plugin::GetAccountReq {
en_accountid: Some(id.to_string()),
},
)?;
let present = v.is_some();
Ok(json!({"ok": present, "row": v}))
}
"oms.contract" => {
let v = ask_service::<ek_oms::plugin::GetContractReq, Option<ek_data::ContractData>>(
api,
"oms.get_contract",
ek_oms::plugin::GetContractReq {
en_symbol: id.to_string(),
},
)?;
let present = v.is_some();
Ok(json!({"ok": present, "row": v}))
}
other => Err(RpcError::not_found(other)),
}
}
const TRADE_CONFIRM: &str = "危险操作:会真实发单/撤单;传 confirm:true 才执行";
fn parse_order(params: &Value) -> Result<ek_data::OrderRequest, RpcError> {
let order = params
.get("order")
.ok_or_else(|| RpcError::invalid_params("缺少 order(OrderRequest 对象)"))?;
serde_json::from_value::<ek_data::OrderRequest>(order.clone())
.map_err(|e| RpcError::invalid_params(format!("order 非法: {e}")))
}
fn client_order_id(params: &Value) -> Option<String> {
params
.get("client_order_id")
.and_then(Value::as_str)
.filter(|s| !s.is_empty())
.map(str::to_string)
}
fn require_confirm(params: &Value) -> Result<(), RpcError> {
if params
.get("confirm")
.and_then(Value::as_bool)
.unwrap_or(false)
{
Ok(())
} else {
Err(RpcError::new(proto::CONFIRM_REQUIRED, TRADE_CONFIRM))
}
}
fn trade_check(api: &ApiPlugin, params: &Value) -> Result<Value, RpcError> {
let req = parse_order(params)?;
let gw = params.get("gateway").and_then(Value::as_str).unwrap_or("");
let key = client_order_id(params);
let dup = key.as_ref().and_then(|k| api.order_result(k));
Ok(json!({
"ok": true,
"order": serde_json::to_value(&req).unwrap_or(Value::Null),
"gateway": gw,
"client_order_id": key,
"duplicate": dup.is_some(),
"cached": dup,
}))
}
fn trade_submit(api: &ApiPlugin, params: &Value, user: &str) -> Result<Value, RpcError> {
require_confirm(params)?;
let req = parse_order(params)?;
let gw = params
.get("gateway")
.and_then(Value::as_str)
.filter(|s| !s.is_empty())
.ok_or_else(|| RpcError::invalid_params("缺少 gateway"))?;
let mode = match params.get("mode").and_then(Value::as_str).unwrap_or("auto") {
"auto" => ek_oms::LockMode::Auto,
"lock" => ek_oms::LockMode::Lock,
"net" => ek_oms::LockMode::Net,
"none" => ek_oms::LockMode::None,
other => {
return Err(RpcError::invalid_params(format!(
"mode 未知: {other}(auto|lock|net|none)"
)));
}
};
if req.volume <= 0.0 {
return Err(RpcError::invalid_params("volume 必须 > 0"));
}
let key = client_order_id(params);
if let Some(k) = &key
&& let Some(cached) = api.order_result(k)
{
api.audit()
.log(user, "trade.submit", gw, true, &format!("duplicate client_order_id={k}"));
return Ok(json!({"ok": true, "duplicate": true, "cached": cached}));
}
let rep = ask_service::<ek_oms::plugin::SubmitOrderReq, ek_oms::SubmitReply>(
api,
"oms.submit_order",
ek_oms::plugin::SubmitOrderReq {
req: req.clone(),
gateway_name: gw.to_string(),
mode,
},
)?;
let status = match rep.status {
ek_oms::SubmitStatus::Sent => "Sent",
ek_oms::SubmitStatus::Partial => "Partial",
ek_oms::SubmitStatus::Rejected => "Rejected",
};
let legs: Vec<Value> = rep
.legs
.iter()
.map(|l| {
json!({
"ok": l.ok,
"en_orderid": l.en_orderid,
"reason": l.reason,
"leg": serde_json::to_value(&l.req).unwrap_or(Value::Null),
})
})
.collect();
let ok = status != "Rejected";
let leg_count = legs.len();
let out = json!({
"ok": ok,
"status": status,
"parent_id": rep.parent_id,
"legs": legs,
});
if let Some(k) = key {
api.store_order_result(k, out.clone());
}
api.audit().log(
user,
"trade.submit",
gw,
ok,
&format!("parent={} status={status} legs={leg_count}", rep.parent_id),
);
Ok(out)
}
fn trade_cancel(api: &ApiPlugin, params: &Value, user: &str) -> Result<Value, RpcError> {
require_confirm(params)?;
let gw = params
.get("gateway")
.and_then(Value::as_str)
.filter(|s| !s.is_empty())
.ok_or_else(|| RpcError::invalid_params("缺少 gateway"))?;
let id = params
.get("id")
.and_then(Value::as_str)
.filter(|s| !s.is_empty())
.ok_or_else(|| RpcError::invalid_params("缺少 id(网关委托号)"))?;
let rep = ask_service::<ek_oms::plugin::OmsCancelOrderReq, ek_oms::plugin::OmsCancelReply>(
api,
"oms.cancel_order",
ek_oms::plugin::OmsCancelOrderReq {
en_orderid: id.to_string(),
gateway_name: gw.to_string(),
},
)?;
api.audit()
.log(user, "trade.cancel", gw, rep.ok, &format!("id={id}"));
Ok(json!({"ok": rep.ok, "msg": rep.msg}))
}
fn dm_symbols(api: &ApiPlugin) -> Result<Value, RpcError> {
let syms = ask_service::<ek_dm::SymbolsReq, Vec<(i64, Vec<(String, usize)>)>>(
api,
"dm.symbols",
ek_dm::SymbolsReq,
)?;
let intervals: Vec<Value> = syms
.iter()
.map(|(iv, list)| {
json!({
"interval": iv,
"symbols": list
.iter()
.map(|(s, n)| json!({"symbol": s, "rows": n}))
.collect::<Vec<_>>(),
})
})
.collect();
Ok(json!({"ok": true, "intervals": intervals}))
}
fn strategy_meta(api: &ApiPlugin) -> Result<Value, RpcError> {
let metas = ask_service::<ek_strategy::contract::StrategyMetaReq, Vec<ek_strategy::strategy::StrategyMeta>>(
api,
"strategy.meta",
ek_strategy::contract::StrategyMetaReq,
)?;
Ok(json!({
"ok": true,
"strategies": metas.iter().map(crate::event_json::meta_json).collect::<Vec<_>>(),
}))
}
fn strategy_settings(api: &ApiPlugin, params: &Value) -> Result<Value, RpcError> {
let name = params
.get("name")
.and_then(Value::as_str)
.ok_or_else(|| RpcError::invalid_params("缺少 name"))?;
let res = ask_service::<ek_strategy::contract::NameReq, ek_strategy::contract::SettingsRes>(
api,
"strategy.get_settings",
ek_strategy::contract::NameReq {
name: name.to_string(),
},
)?;
Ok(json!({
"ok": true,
"class_name": res.class_name,
"params": res.params.iter().map(|(k, v)| json!({"key": k, "value": v})).collect::<Vec<_>>(),
}))
}
fn strategy_price(api: &ApiPlugin, params: &Value) -> Result<Value, RpcError> {
let symbol = params
.get("symbol")
.and_then(Value::as_str)
.ok_or_else(|| RpcError::invalid_params("缺少 symbol"))?;
let res = ask_service::<ek_strategy::contract::PriceSymbolReq, ek_strategy::contract::PriceRes>(
api,
"strategy.get_price",
ek_strategy::contract::PriceSymbolReq {
symbol: symbol.to_string(),
},
)?;
Ok(json!({"ok": true, "price": res.price}))
}
fn strategy_resync(api: &ApiPlugin) -> Result<Value, RpcError> {
let res = ask_service::<ek_strategy::contract::ResyncReq, ek_strategy::contract::Reply>(
api,
"strategy.resync",
ek_strategy::contract::ResyncReq,
)?;
Ok(json!({"ok": res.ok, "msg": res.msg}))
}
fn params_str<'a>(params: &'a Value, key: &str) -> Result<&'a str, RpcError> {
params
.get(key)
.and_then(Value::as_str)
.ok_or_else(|| RpcError::invalid_params(format!("缺少 {key}")))
}
fn params_pairs(params: &Value) -> Result<Vec<(String, String)>, RpcError> {
let obj = params
.get("params")
.and_then(Value::as_object)
.ok_or_else(|| RpcError::invalid_params("缺少 params(键值对象)"))?;
let mut out = Vec::with_capacity(obj.len());
for (k, v) in obj {
let s = v
.as_str()
.ok_or_else(|| RpcError::invalid_params(format!("参数 {k} 必须是字符串(展示值)")))?;
out.push((k.clone(), s.to_string()));
}
Ok(out)
}
fn strategy_ask<Req>(
api: &ApiPlugin,
svc: &str,
req: Req,
user: &str,
) -> Result<Value, RpcError>
where
Req: Any + Send + Sync,
{
let rep = ask_service::<Req, ek_strategy::contract::Reply>(api, svc, req)?;
api.audit().log(user, svc, "strategy", rep.ok, "");
Ok(json!({"ok": rep.ok, "msg": rep.msg}))
}
fn strategy_add(api: &ApiPlugin, params: &Value, user: &str) -> Result<Value, RpcError> {
let req = ek_strategy::contract::AddReq {
class_name: params_str(params, "class_name")?.to_string(),
name: params_str(params, "name")?.to_string(),
params: params_pairs(params)?,
};
strategy_ask(api, "strategy.add", req, user)
}
fn strategy_edit(api: &ApiPlugin, params: &Value, user: &str) -> Result<Value, RpcError> {
let req = ek_strategy::contract::EditReq {
name: params_str(params, "name")?.to_string(),
params: params_pairs(params)?,
};
strategy_ask(api, "strategy.edit", req, user)
}
fn strategy_set_engine(api: &ApiPlugin, params: &Value, user: &str) -> Result<Value, RpcError> {
let req = ek_strategy::contract::SetEngineReq {
trade_gateway: params
.get("trade_gateway")
.and_then(Value::as_str)
.unwrap_or("")
.to_string(),
md_gateway: params
.get("md_gateway")
.and_then(Value::as_str)
.unwrap_or("")
.to_string(),
};
strategy_ask(api, "strategy.set_engine", req, user)
}
fn ctp_status(api: &ApiPlugin, params: &Value) -> Result<Value, RpcError> {
let gw = params
.get("gateway")
.and_then(Value::as_str)
.ok_or_else(|| RpcError::invalid_params("缺少 gateway"))?;
let st = ask_service::<ek_ctp::plugin::StatusReq, ek_ctp::plugin::GatewayStatus>(
api,
&format!("{gw}.status"),
ek_ctp::plugin::StatusReq,
)?;
let mut out = crate::event_json::status_json(&st);
if let Value::Object(ref mut o) = out {
o.insert("ok".to_string(), Value::Bool(true));
}
Ok(out)
}
fn ctp_credentials(api: &ApiPlugin, params: &Value) -> Result<Value, RpcError> {
let gw = params
.get("gateway")
.and_then(Value::as_str)
.ok_or_else(|| RpcError::invalid_params("缺少 gateway"))?;
let list = ask_service::<ek_ctp::plugin::CredentialStateReq, Vec<ek_ctp::plugin::CredentialEntry>>(
api,
&format!("{gw}.credentials_state"),
ek_ctp::plugin::CredentialStateReq,
)?;
Ok(json!({
"ok": true,
"fields": list
.iter()
.map(|e| json!({"field": e.field, "state": e.state, "ref_key": e.ref_key}))
.collect::<Vec<_>>(),
}))
}
fn tq_klines(api: &ApiPlugin, params: &Value) -> Result<Value, RpcError> {
use ek_tq::klines::{FetchMode, KlinesReply, KlinesReq, RangeSpec};
let gw = params
.get("gateway")
.and_then(Value::as_str)
.ok_or_else(|| RpcError::invalid_params("缺少 gateway"))?;
let symbol = params
.get("symbol")
.and_then(Value::as_str)
.ok_or_else(|| RpcError::invalid_params("缺少 symbol"))?;
let interval_secs = params
.get("interval_secs")
.and_then(Value::as_i64)
.ok_or_else(|| RpcError::invalid_params("缺少 interval_secs"))?;
let raw = params.get("raw").and_then(Value::as_bool).unwrap_or(false);
let max_rows = params.get("max_rows").and_then(Value::as_u64);
let start_ns = params.get("start_ns").and_then(Value::as_i64);
let end_ns = params.get("end_ns").and_then(Value::as_i64);
let count = params
.get("count")
.and_then(Value::as_u64)
.unwrap_or(100)
.clamp(1, 100_000) as u32;
let range = match (start_ns, end_ns) {
(Some(s), Some(e)) => RangeSpec::Range {
start_ns: s,
end_ns: e,
},
_ => RangeSpec::Length { count, end_ns },
};
let rep = ask_service::<KlinesReq, KlinesReply>(
api,
&format!("{gw}.klines"),
KlinesReq {
symbol: symbol.to_string(),
raw,
interval_secs,
range,
max_rows,
},
)?;
let mode: FetchMode = rep.mode;
Ok(json!({
"ok": true,
"mode": mode.as_str(),
"covered": [rep.covered.0, rep.covered.1],
"truncated": rep.truncated,
"rows": rep.rows,
}))
}
fn field_view(f: &ek_core::Field, ns: &str) -> Value {
match f {
ek_core::Field::Plain(v) => json!({"kind": "plain", "value": v}),
ek_core::Field::Secret { key } => json!({"kind": "secret", "ref": format!("secret://ek/{ns}/{key}")}),
}
}
fn section_json(map: &ek_core::SectionMap, ns: &str) -> Value {
let mut out = serde_json::Map::new();
for (k, f) in map.iter() {
out.insert(k.to_string(), field_view(f, ns));
}
Value::Object(out)
}
fn account_list(api: &ApiPlugin) -> Result<Value, RpcError> {
let taken = ek_station::accounts::taken_accounts(api.store())
.map_err(|e| RpcError::new(CONFIG_REJECTED, e))?;
let mut rows = Vec::with_capacity(taken.len());
for (gw, broker, user, td) in taken {
let ns = format!("ctp.{gw}");
let fields = match api.store().load(&ns) {
Ok(ek_cfg::LoadOutcome::Loaded { map, .. }) => section_json(&map, &ns),
_ => Value::Null,
};
rows.push(json!({
"gateway": gw,
"broker": broker,
"user": user,
"td_addr": td,
"fields": fields,
}));
}
Ok(json!({"ok": true, "accounts": rows}))
}
fn account_add(api: &ApiPlugin, params: &Value, user: &str) -> Result<Value, RpcError> {
let get = |k: &str| -> String {
params
.get(k)
.and_then(Value::as_str)
.unwrap_or("")
.to_string()
};
let spec = ek_station::accounts::AcctSpec {
broker_id: get("broker_id"),
user: get("user"),
td_addr: get("td_addr"),
md_addr: get("md_addr"),
app_id: get("app_id"),
auth_code: get("auth_code"),
classes: get("classes"),
md_user: get("md_user"),
md_password: params
.get("md_password")
.and_then(Value::as_str)
.map(str::to_string),
};
let password = params
.get("password")
.and_then(Value::as_str)
.ok_or_else(|| RpcError::invalid_params("缺少 password"))?;
let root = api.store().root().to_path_buf();
if ek_cfg::crypto::MasterKey::load(&root).is_err() {
ek_cfg::crypto::MasterKey::write_new(&root)
.map_err(|e| RpcError::new(CONFIG_REJECTED, format!("创建主密钥失败: {e}")))?;
}
let gw = ek_station::accounts::write_account(api.store(), &spec, password)
.map_err(|e| RpcError::new(CONFIG_REJECTED, e))?;
api.audit()
.log(user, "account.add", &gw, true, "saved=ctp.<gw>");
Ok(json!({"ok": true, "gateway": gw, "ns": format!("ctp.{gw}")}))
}
fn account_remove(api: &ApiPlugin, params: &Value, user: &str) -> Result<Value, RpcError> {
let gw = params
.get("gateway")
.and_then(Value::as_str)
.ok_or_else(|| RpcError::invalid_params("缺少 gateway"))?;
ek_station::accounts::purge_account_archive(api.store(), gw)
.map_err(|e| RpcError::new(CONFIG_REJECTED, e))?;
api.audit().log(user, "account.remove", gw, true, "");
Ok(json!({"ok": true, "gateway": gw}))
}
fn account_test(api: &ApiPlugin, params: &Value) -> Result<Value, RpcError> {
let gw = params
.get("gateway")
.and_then(Value::as_str)
.ok_or_else(|| RpcError::invalid_params("缺少 gateway"))?;
let ns = format!("ctp.{gw}");
let map = match api.store().load(&ns) {
Ok(ek_cfg::LoadOutcome::Loaded { map, .. }) => map,
_ => {
return Ok(json!({"ok": false, "gateway": gw, "reason": format!("无此账户档 {ns}")}));
}
};
let required = ["broker_id", "td_addr", "td_user", "td_app_id", "td_auth_code", "td_password"];
let missing: Vec<&str> = required
.iter()
.filter(|k| map.get_plain(k).is_none() && map.get(k).is_none())
.copied()
.collect();
let creds = if let Some(ctx) = api.ctx() {
ctx.plugins().iter().any(|p| p.name == gw)
} else {
false
};
Ok(json!({
"ok": missing.is_empty(),
"gateway": gw,
"missing": missing,
"attached": creds,
"note": if creds {
"网关已装配:连通性请查 ctp.status / credentials_state"
} else {
"网关未装配:本检查只验档完整性;连通性需装配 ctp 网关后经 ctp.status 验证"
},
}))
}
fn bundles_dir() -> std::path::PathBuf {
crate::args::data_dir().join("bundles")
}
fn safe_bundle_name(name: &str) -> Result<String, RpcError> {
let name = name.trim();
if name.is_empty()
|| name.contains('/')
|| name.contains('\\')
|| name.contains("..")
|| name.contains(':')
{
return Err(RpcError::invalid_params("bundle name 非法"));
}
Ok(name.to_string())
}
fn bundle_export(api: &ApiPlugin, params: &Value, user: &str) -> Result<Value, RpcError> {
let name = safe_bundle_name(
params
.get("name")
.and_then(Value::as_str)
.ok_or_else(|| RpcError::invalid_params("缺少 name"))?,
)?;
let mut sections = serde_json::Map::new();
for ns in api
.store()
.list_namespaces()
.map_err(|e| RpcError::new(CONFIG_REJECTED, format!("列段失败: {e}")))?
{
if ns.starts_with("ctp.") || ns == profile::API_NS {
if let Ok(ek_cfg::LoadOutcome::Loaded { map, .. }) = api.store().load(&ns) {
sections.insert(ns.clone(), section_json(&map, &ns));
}
}
}
let dir = bundles_dir();
std::fs::create_dir_all(&dir)
.map_err(|e| RpcError::new(CONFIG_REJECTED, format!("目录创建失败: {e}")))?;
let path = dir.join(format!("{name}.json"));
let doc = json!({
"ek_bundle": 1,
"exported_ms": crate::server::now_ms(),
"sections": sections,
});
std::fs::write(&path, serde_json::to_vec_pretty(&doc).unwrap_or_default())
.map_err(|e| RpcError::new(CONFIG_REJECTED, format!("写包失败: {e}")))?;
api.audit()
.log(user, "bundle.export", &name, true, &format!("sections={}", doc["sections"].as_object().map_or(0, serde_json::Map::len)));
Ok(json!({
"ok": true,
"name": name,
"path": path.display().to_string(),
"sections": doc["sections"].as_object().map_or(0, serde_json::Map::len),
"has_plaintext_secrets": false,
}))
}
fn bundle_import(api: &ApiPlugin, params: &Value, user: &str) -> Result<Value, RpcError> {
let name = safe_bundle_name(
params
.get("name")
.and_then(Value::as_str)
.ok_or_else(|| RpcError::invalid_params("缺少 name"))?,
)?;
let path = bundles_dir().join(format!("{name}.json"));
let text = std::fs::read_to_string(&path)
.map_err(|e| RpcError::new(CONFIG_REJECTED, format!("读包失败 {}: {e}", path.display())))?;
let doc: Value = serde_json::from_str(&text)
.map_err(|e| RpcError::new(CONFIG_REJECTED, format!("包格式非法: {e}")))?;
let Some(sections) = doc.get("sections").and_then(Value::as_object) else {
return Err(RpcError::new(CONFIG_REJECTED, "包缺少 sections"));
};
let mut imported = Vec::new();
let mut need_credentials = Vec::new();
for (ns, fields) in sections {
let Some(obj) = fields.as_object() else { continue };
let mut map = ek_core::SectionMap::new(1);
let mut has_secret = false;
for (k, v) in obj {
match v.get("kind").and_then(Value::as_str) {
Some("plain") => {
if let Some(val) = v.get("value").and_then(Value::as_str) {
map = map.set(k.clone(), ek_core::Field::plain(val));
}
}
Some("secret") => {
has_secret = true;
let key = v
.get("ref")
.and_then(Value::as_str)
.and_then(|r| r.rsplit('/').next())
.unwrap_or(k)
.to_string();
map = map.set(k.clone(), ek_core::Field::secret(key));
}
_ => {}
}
}
api.store()
.save(ns, &map)
.map_err(|e| RpcError::new(CONFIG_REJECTED, format!("落盘 {ns} 失败: {e}")))?;
imported.push(ns.clone());
if has_secret {
need_credentials.push(ns.clone());
}
}
api.audit().log(
user,
"bundle.import",
&name,
true,
&format!("sections={} need_creds={}", imported.len(), need_credentials.len()),
);
Ok(json!({
"ok": true,
"name": name,
"imported": imported,
"need_credentials": need_credentials,
"note": "秘面只留引用串;本机没有对应密库值时需用 secret.put 重新录入",
}))
}
fn log_query(api: &ApiPlugin, params: &Value) -> Result<Value, RpcError> {
let dir = api
.log_path()
.parent()
.map_or_else(|| std::path::PathBuf::from("."), std::path::Path::to_path_buf);
let (y, m, d) = crate::util::today_utc();
let date = params
.get("date")
.and_then(Value::as_str)
.map(str::to_string)
.unwrap_or_else(|| format!("{y:04}{m:02}{d:02}"));
let path = dir.join(format!("ek-server-{date}.log"));
query_lines(&path, params)
}
fn audit_list(api: &ApiPlugin, params: &Value) -> Result<Value, RpcError> {
let dir = api
.log_path()
.parent()
.map_or_else(|| std::path::PathBuf::from("."), std::path::Path::to_path_buf);
let (y, m, d) = crate::util::today_utc();
let date = params
.get("date")
.and_then(Value::as_str)
.map(str::to_string)
.unwrap_or_else(|| format!("{y:04}{m:02}{d:02}"));
let path = dir.join(format!("audit-{date}.log"));
query_lines(&path, params)
}
fn query_lines(path: &std::path::Path, params: &Value) -> Result<Value, RpcError> {
let (limit, offset) = page(params);
let text = std::fs::read_to_string(path).unwrap_or_default();
let lines: Vec<&str> = text.lines().collect();
let total = lines.len();
let start = offset.min(total);
let end = (offset + limit).min(total);
Ok(json!({
"ok": true,
"file": path.display().to_string(),
"total": total,
"limit": limit,
"offset": offset,
"lines": &lines[start..end],
}))
}
fn topic_list(params: &Value) -> Result<Vec<String>, RpcError> {
let arr = params
.get("topics")
.and_then(Value::as_array)
.ok_or_else(|| RpcError::invalid_params("缺少 topics(字符串数组)"))?;
let mut out = Vec::with_capacity(arr.len());
for v in arr {
let Some(t) = v.as_str() else {
return Err(RpcError::invalid_params("topics 元素必须是字符串"));
};
out.push(t.to_string());
}
Ok(out)
}
fn sub_subscribe(api: &ApiPlugin, params: &Value, conn_id: u64) -> Result<Value, RpcError> {
let want = topic_list(params)?;
let mut ok = Vec::new();
let mut unknown = Vec::new();
for t in want {
if crate::hub::is_topic(&t) {
ok.push(t);
} else {
unknown.push(t);
}
}
let cur = api.hub().subscribe(conn_id, &ok);
Ok(json!({"ok": true, "topics": cur, "unknown": unknown}))
}
fn sub_unsubscribe(api: &ApiPlugin, params: &Value, conn_id: u64) -> Result<Value, RpcError> {
let want = topic_list(params)?;
let cur = api.hub().unsubscribe(conn_id, &want);
Ok(json!({"ok": true, "topics": cur}))
}
fn sub_list(api: &ApiPlugin, conn_id: u64) -> Result<Value, RpcError> {
let mut available: Vec<&str> = crate::hub::EV_TOPICS.to_vec();
available.push(crate::hub::TOPIC_STATUS);
Ok(json!({
"ok": true,
"topics": api.hub().topics(conn_id),
"available": available,
}))
}
fn log_tail(api: &ApiPlugin, params: &Value) -> Result<Value, RpcError> {
let n = params
.get("n")
.and_then(Value::as_u64)
.unwrap_or(20)
.clamp(1, 1000) as usize;
let path = api.log_path();
let text = fs::read_to_string(&path).unwrap_or_default();
let lines: Vec<&str> = text.lines().collect();
let start = lines.len().saturating_sub(n);
Ok(json!({
"ok": true,
"file": path.display().to_string(),
"total": lines.len(),
"lines": &lines[start..],
}))
}