Skip to main content

ServerState

Struct ServerState 

Source
pub struct ServerState {
Show 15 fields inner: Arc<Mutex<Inner>>, enable_trading: bool, allow_real_trading: bool, key_store: Arc<KeyStore>, authed_key: Option<Arc<KeyRecord>>, opend_rest_url: Option<String>, opend_api_key: Option<String>, trade_pwd_account: Option<String>, counters: Arc<RuntimeCounters>, push_subscribers: Arc<Mutex<HashMap<String, PushSubscriber>>>, modern_push_slots: Arc<Semaphore>, connect_gate: Arc<Mutex<()>>, purge_task_spawns: Arc<AtomicU64>, push_reregister_failures: Arc<AtomicU64>, push_registration_dirty: Arc<AtomicBool>,
}
Expand description

MCP server 运行时状态

Fields§

§inner: Arc<Mutex<Inner>>

Inner 共享可变状态(gateway 地址 + 懒加载的 [FutuClient])

§enable_trading: bool

是否启用交易写工具(place/modify/cancel)。默认 false。旧开关,仅当 key_store.is_configured() == false 时生效。

§allow_real_trading: bool

是否允许对 real 环境下单。默认 false。旧开关,同上。

§key_store: Arc<KeyStore>

keys.json 加载的 KeyStore。is_configured() 为 true 时走 scope 授权模式。

§authed_key: Option<Arc<KeyRecord>>

调用方传入的 API Key 对应的记录;None 表示未提供 key。

§opend_rest_url: Option<String>§opend_api_key: Option<String>§trade_pwd_account: Option<String>

交易密码所属登录账号。用于 futu_unlock_trade 从账号级 keychain trade-password.<login-account> 读取密码;None 时走 legacy/global/env 兼容路径。

§counters: Arc<RuntimeCounters>

限额运行时(日累计计数器)

§push_subscribers: Arc<Mutex<HashMap<String, PushSubscriber>>>

v1.4.38 Phase 5: MCP push 订阅者注册表(session_uuid → subscriber)。 futu_sub_acc_push 工具在 HTTP 模式下调用时注册当前 session,daemon push 到 MCP 后按 acc_id filter 向注册的 peer 发 notify_logging_message(server-initiated notification)。

§modern_push_slots: Arc<Semaphore>

Modern resources retain bounded queues for up to 4h. A semaphore makes handle cardinality admission atomic and lets the tool fail before any daemon side effect. The fixed local limit is a memory-safety boundary, not backend/config data; raise it only after measuring worst-case push payload memory and concurrent client demand.

§connect_gate: Arc<Mutex<()>>

issue #54:gateway 重连单飞门。建连期间持有(不持 inner 锁),并发 caller 在此排队,拿到门后复检缓存直接复用赢家结果 → 一次断连只开一条新 TCP。

§purge_task_spawns: Arc<AtomicU64>

陈旧订阅者 purge task 已 spawn 次数;compare_exchange(0, 1) 保证整个 ServerState 生命周期只 spawn 一次(重连不重复 spawn)。

§push_reregister_failures: Arc<AtomicU64>

issue #54 Reviewer M-5: gateway 重连后 TRD_SUB_ACC_PUSH 重注册失败次数。 失败只记日志 + 计数,不阻塞工具调用;调用方需重新 futu_sub_acc_push

§push_registration_dirty: Arc<AtomicBool>

issue #54 Reviewer I-2: set when the post-reconnect push re-registration failed; the next client() that finds a live connection retries once.

Implementations§

Source§

impl ServerState

Source

pub async fn reserve_modern_push_handle( &self, ) -> Result<Arc<OwnedSemaphorePermit>, String>

Source

pub async fn register_push_subscriber_with_owner( &self, delivery: PushDeliveryTarget, acc_ids: HashSet<u64>, owner_key_id: Option<String>, allowed_acc_ids_snapshot: Option<HashSet<u64>>, allowed_markets_snapshot: Option<HashSet<String>>, legacy_service_owner: Option<Weak<()>>, ) -> Result<String, String>

v1.4.38 Phase 5: 注册当前 session 接收指定 acc_id 的 push。返回 session UUID(调用方存着,后续可 unregister)。

v1.4.38: 已 wire 到 futu_sub_acc_push tool。tool 被调用时拿到 RequestContext.peeracc_ids 从工具 args 解析,注册完成后 state.rs 的 push drain loop 会按 acc_ids filter 转 notify 给该 peer。 v1.4.103 (codex 50 F5 / 53 F2 / 58 F3 — B7) + (codex 50 F6 / 53 F4 — B8): 注册当前 session 接收指定 acc_id 的 push。

Authorization fields are supplied from one already-approved immutable caller snapshot. This method never re-resolves plaintext after a daemon await, avoiding identity/scope drift between authorization and insert.

Source

async fn remove_legacy_push_subscribers_for_service( &self, owner: &Weak<()>, ) -> usize

Source

pub async fn unregister_push_subscriber_with_owner_check( &self, session_id: &str, caller_key_id: Option<&str>, ) -> Result<bool, String>

v1.4.103 (codex 50 F6 / 53 F4 — B8): unsub session ownership check.

行为:

  • 无 caller_key_id (legacy / stdio): 退化为旧行为 (任何 caller 可 unsub).
  • 有 caller_key_id + subscriber.owner_key_id 匹配: 删除, 返 Ok(true).
  • 有 caller_key_id + subscriber.owner_key_id 不匹配: 拒绝, 返 Err(reason) — 防其他 caller 拿可见 session_id 强制 unsub.
  • session_id 不存在: 返 Ok(false) (idempotent, 不报错).
  • subscriber.owner_key_id = None (legacy 注册): 退化为旧行为 — 任何 caller 可 unsub (向后兼容).
Source

pub async fn modern_resources_for_caller( &self, caller_key_id: &str, caller_allowed_acc_ids: Option<&HashSet<u64>>, caller_allowed_markets: Option<&HashSet<String>>, ) -> Vec<Resource>

Source

fn modern_resource_for_caller( subscriber: &PushSubscriber, caller_key_id: &str, caller_allowed_acc_ids: Option<&HashSet<u64>>, caller_allowed_markets: Option<&HashSet<String>>, ) -> Result<Arc<ModernResourceDelivery>, String>

Source

pub async fn drain_modern_push_resource( &self, uri: &str, caller_key_id: &str, caller_allowed_acc_ids: Option<&HashSet<u64>>, caller_allowed_markets: Option<&HashSet<String>>, ) -> Result<(String, Vec<Value>, u64), String>

Source

pub async fn attach_modern_push_listener( &self, uri: &str, caller_key_id: &str, caller_allowed_acc_ids: Option<&HashSet<u64>>, caller_allowed_markets: Option<&HashSet<String>>, sink: SubscriptionSink, ) -> Result<(u64, CancellationToken), String>

Source

pub async fn detach_modern_push_listener(&self, uri: &str, listener_token: u64)

Source

pub(super) async fn purge_expired_push_subscribers(&self) -> usize

Source

async fn purge_expired_push_subscribers_at(&self, now: Instant) -> usize

Source

pub async fn push_subscribers_summary( &self, caller_allowed_acc_ids: Option<&HashSet<u64>>, ) -> Vec<(String, HashSet<u64>, u64)>

v1.4.58 Phase A: 列出所有 push 订阅 summary(tool diagnostic 用)。

返 Vec<(session_id, acc_ids, age_secs)>。

MED-NEW-3 修(2nd review):加 caller_allowed_acc_ids 参数做 scope-mode 多租过滤。当 caller 的 key 有 allowed_acc_ids 白名单时, 只返 subscription 的 acc_ids 与 caller 白名单有交集的条目。 避免 agent A(acc_ids=[100, 200])通过本 tool 看到 agent B 订阅的 acc_id=[300, 400]。

caller_allowed_acc_ids=None / empty → 不过滤(legacy mode / no-scope key)。

rmcp 版本兼容:rmcp 1.4.0 Peer<RoleServer> 不实装 PartialEq, 无法按 peer 身份直接过滤。若未来 rmcp 加 PartialEq,可切到更精确的 per-session-owner 过滤(当前只能靠 acc_id 权限交集近似)。

Source§

impl ServerState

Source

pub fn new(gateway: String) -> Self

创建默认 state:enable_trading=false / allow_real_trading=false / 空 [KeyStore] / 无 authed_key。使用 with_* 链式方法注入额外能力。

Source

pub fn with_trading( self, enable_trading: bool, allow_real_trading: bool, ) -> Self

启用交易写工具(构造器式链式设置)

Source

pub fn with_key_store(self, store: Arc<KeyStore>) -> Self

设置 KeyStore(新授权模式)

Source

pub fn with_authed_key(self, key: Option<Arc<KeyRecord>>) -> Self

设置已通过验证的 API Key 记录

Source

pub fn with_opend_rest( self, base_url: Option<String>, api_key: Option<String>, ) -> Self

Source

pub fn opend_rest_url(&self) -> Option<&str>

Source

pub fn opend_api_key(&self) -> Option<&str>

Source

pub fn with_trade_pwd_account(self, account: Option<String>) -> Self

设置交易密码所属登录账号(MCP 只连 gateway,本身无法可靠推断 daemon 的 login account;由 CLI/env/config 显式注入)。

Source

pub fn is_scope_mode(&self) -> bool

是否启用了 scope 授权模式

Source

pub fn enable_trading(&self) -> bool

交易写工具开关(legacy mode)。

Source

pub fn allow_real_trading(&self) -> bool

real 环境交易写工具开关(legacy mode)。

Source

pub fn key_store(&self) -> &Arc<KeyStore>

当前 MCP API key store。返回共享引用,避免调用方替换 runtime storage。

Source

pub fn authed_key(&self) -> Option<Arc<KeyRecord>>

startup 阶段验证过的 key 快照;调用方需要 fresh record 时仍应按 id 回查 key store。

Source

pub fn trade_pwd_account(&self) -> Option<&str>

交易密码所属登录账号。

Source

pub fn counters(&self) -> &Arc<RuntimeCounters>

限额运行时计数器。返回共享引用,避免调用方替换 runtime storage。

Source

pub async fn gateway(&self) -> String

当前配置的 gateway 地址。

Source

pub async fn client(&self) -> Result<Arc<FutuClient>>

获取(或懒加载)网关客户端。

issue #54:gateway 重启后旧 client 的 event loop 已退出 ([FutuClient::is_closed]),缓存视为失效并重建;并发调用经 connect_gate 单飞,只开一条新连接;重连成功后重发本地 push 订阅 (Self::restore_push_registration)。建连期间不持 inner 锁。

Source

async fn restore_push_registration(&self, client: &Arc<FutuClient>)

issue #54:daemon 侧 push 订阅按 conn_id 存,旧连接断开时已被 daemon on_disconnect(conn_id) 清空;重连后把本地仍在册订阅者的 acc_ids 并集 重发 TRD_SUB_ACC_PUSH(2008),否则 subscriber 留在本地却收不到任何 push。 失败只 warn,不阻塞 client() 返回(调用方可重新 futu_sub_acc_push)。 QOT 行情订阅 MCP 没有本地记录,不在此恢复。

Source

pub async fn verification_client(&self) -> Result<Arc<FutuClient>>

Open a transient C++-compatible internal-UI transport for the pre-login Verification tool. The ordinary cached MCP client must keep normal InitConnect semantics and wait for a real login identity.

Trait Implementations§

Source§

impl Clone for ServerState

Source§

fn clone(&self) -> ServerState

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DynClone for T
where T: Clone,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> FromRef<T> for T
where T: Clone,

§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
§

impl<T> PolicyExt for T
where T: ?Sized,

§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns [Action::Follow] only if self and other return Action::Follow. Read more
§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns [Action::Follow] if either self or other returns Action::Follow. Read more
§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more