Skip to main content

dig_node_control_interface/
traits.rs

1//! The two contract traits: the client-facing call builder/parser and the node-facing handler.
2//!
3//! * [`ControlCall`] binds a typed params struct to its [`ControlMethod`] and its typed result — so
4//!   a caller writes `client.request(&SetCapParams { cap_bytes })` and gets back a `SetCapResult`,
5//!   never a stringly-typed `Value`.
6//! * [`ControlClient`] is what a CLIENT depends on: build a JSON-RPC request from a typed call, and
7//!   parse a response back into the typed result (or a [`ControlError`]). Pure — no transport; the
8//!   consumer carries the bytes over dig-ipc / loopback-mTLS itself.
9//! * [`ControlHandler`] is what a NODE implements to SERVE the surface: one typed method per control
10//!   method, plus a provided [`dispatch`](ControlHandler::dispatch) that routes a raw request to the
11//!   right method — the single anti-drift seam the conformance KATs exercise.
12
13use async_trait::async_trait;
14use serde::de::DeserializeOwned;
15use serde::Serialize;
16use serde_json::Value;
17
18use crate::envelope::{JsonRpcRequest, JsonRpcResponse, RequestId};
19use crate::error::{ControlError, ControlErrorCode};
20use crate::method::ControlMethod;
21use crate::params;
22use crate::results;
23
24/// A typed control call: a params struct that knows its [`ControlMethod`] and its result type.
25///
26/// Implemented by every struct in [`crate::params`]; this is what makes [`ControlClient::request`]
27/// return the right typed result for each method at compile time.
28pub trait ControlCall: Serialize {
29    /// The wire method this call invokes.
30    const METHOD: ControlMethod;
31    /// The typed result this call returns on success.
32    type Output: DeserializeOwned;
33}
34
35/// Serialize a typed call's params into a JSON object (`{}` for a no-param call, never `null`).
36fn params_value<C: ControlCall>(call: &C) -> Value {
37    match serde_json::to_value(call) {
38        Ok(Value::Null) => Value::Object(Default::default()),
39        Ok(v) => v,
40        Err(_) => Value::Object(Default::default()),
41    }
42}
43
44/// Build the JSON-RPC request envelope for a typed control call. Pure.
45pub fn build_request<C: ControlCall>(id: RequestId, call: &C) -> JsonRpcRequest {
46    JsonRpcRequest::new(id, C::METHOD.name(), params_value(call))
47}
48
49/// Parse a JSON-RPC response into a typed result, or the [`ControlError`] it carried. Pure.
50pub fn parse_response<C: ControlCall>(
51    response: JsonRpcResponse,
52) -> Result<C::Output, ControlError> {
53    let value = response.into_result()?;
54    serde_json::from_value(value).map_err(|e| {
55        ControlError::of(
56            ControlErrorCode::ControlError,
57            format!("failed to parse {} result: {e}", C::METHOD.name()),
58        )
59    })
60}
61
62/// The client-facing half of the contract: turn typed calls into requests and responses back into
63/// typed results.
64///
65/// The default implementations cover every client; a consumer implements this trait only to
66/// customise request construction (e.g. attaching the control token in a bespoke way). The blanket
67/// [`DefaultControlClient`] gives callers the standard behaviour for free.
68pub trait ControlClient {
69    /// Build the request envelope for a typed call with the given request `id`.
70    fn build_request<C: ControlCall>(&self, id: RequestId, call: &C) -> JsonRpcRequest {
71        build_request(id, call)
72    }
73
74    /// Parse a response envelope into the typed result for call type `C`.
75    fn parse_response<C: ControlCall>(
76        &self,
77        response: JsonRpcResponse,
78    ) -> Result<C::Output, ControlError> {
79        parse_response::<C>(response)
80    }
81}
82
83/// The standard, zero-configuration [`ControlClient`] using the default request/response behaviour.
84#[derive(Debug, Clone, Copy, Default)]
85pub struct DefaultControlClient;
86
87impl ControlClient for DefaultControlClient {}
88
89/// The node-facing half of the contract: a running node implements this to SERVE the control
90/// surface. Each method is typed to the catalog's params/results; the provided
91/// [`dispatch`](ControlHandler::dispatch) routes a raw [`JsonRpcRequest`] to the right method so a
92/// server needs only one entry point and can never mis-route.
93///
94/// Open/proxied shapes (the updater beacon status, the pairing list, the peer-pool snapshot) return
95/// [`Value`] rather than a frozen struct, matching the catalog's [`ControlCall::Output`] for those
96/// methods.
97#[async_trait]
98pub trait ControlHandler: Sync {
99    /// `control.status`
100    async fn status(&self) -> Result<results::StatusResult, ControlError>;
101    /// `control.config.get`
102    async fn config_get(&self) -> Result<results::ConfigResult, ControlError>;
103    /// `control.config.setUpstream`
104    async fn config_set_upstream(
105        &self,
106        params: params::SetUpstreamParams,
107    ) -> Result<results::SetUpstreamResult, ControlError>;
108    /// `control.log.setLevel`
109    async fn log_set_level(
110        &self,
111        params: params::SetLevelParams,
112    ) -> Result<results::SetLevelResult, ControlError>;
113    /// `control.cache.get`
114    async fn cache_get(&self) -> Result<results::CacheView, ControlError>;
115    /// `control.cache.setCap`
116    async fn cache_set_cap(
117        &self,
118        params: params::SetCapParams,
119    ) -> Result<results::SetCapResult, ControlError>;
120    /// `control.cache.clear`
121    async fn cache_clear(&self) -> Result<results::CacheClearResult, ControlError>;
122    /// `control.hostedStores.list`
123    async fn hosted_stores_list(&self) -> Result<results::HostedStoresListResult, ControlError>;
124    /// `control.hostedStores.pin`
125    async fn hosted_stores_pin(
126        &self,
127        params: params::PinParams,
128    ) -> Result<results::PinResult, ControlError>;
129    /// `control.hostedStores.unpin`
130    async fn hosted_stores_unpin(
131        &self,
132        params: params::UnpinParams,
133    ) -> Result<results::UnpinResult, ControlError>;
134    /// `control.hostedStores.status`
135    async fn hosted_stores_status(
136        &self,
137        params: params::HostedStoreStatusParams,
138    ) -> Result<results::HostedStoreStatusResult, ControlError>;
139    /// `control.sync.status`
140    async fn sync_status(&self) -> Result<results::SyncStatusResult, ControlError>;
141    /// `control.sync.trigger`
142    async fn sync_trigger(
143        &self,
144        params: params::SyncTriggerParams,
145    ) -> Result<results::SyncTriggerResult, ControlError>;
146    /// `control.updater.status`
147    async fn updater_status(&self) -> Result<Value, ControlError>;
148    /// `control.updater.setChannel`
149    async fn updater_set_channel(
150        &self,
151        params: params::SetChannelParams,
152    ) -> Result<Value, ControlError>;
153    /// `control.updater.pause`
154    async fn updater_pause(&self, params: params::PauseParams) -> Result<Value, ControlError>;
155    /// `control.updater.resume`
156    async fn updater_resume(&self) -> Result<Value, ControlError>;
157    /// `control.updater.checkNow`
158    async fn updater_check_now(&self) -> Result<Value, ControlError>;
159    /// `control.pairing.list`
160    async fn pairing_list(&self) -> Result<Value, ControlError>;
161    /// `control.pairing.approve`
162    async fn pairing_approve(
163        &self,
164        params: params::ApproveParams,
165    ) -> Result<results::PairingApproveResult, ControlError>;
166    /// `control.pairing.revoke`
167    async fn pairing_revoke(
168        &self,
169        params: params::RevokeParams,
170    ) -> Result<results::PairingRevokeResult, ControlError>;
171    /// `control.peerStatus`
172    async fn peer_status(&self) -> Result<Value, ControlError>;
173    /// `control.peers.connect`
174    async fn peers_connect(
175        &self,
176        params: params::PeersConnectParams,
177    ) -> Result<results::PeersConnectResult, ControlError>;
178    /// `control.peers.disconnect`
179    async fn peers_disconnect(
180        &self,
181        params: params::PeersDisconnectParams,
182    ) -> Result<results::PeersDisconnectResult, ControlError>;
183    /// `control.subscribe`
184    async fn subscribe(
185        &self,
186        params: params::SubscribeParams,
187    ) -> Result<results::SubscribeResult, ControlError>;
188    /// `control.unsubscribe`
189    async fn unsubscribe(
190        &self,
191        params: params::UnsubscribeParams,
192    ) -> Result<results::UnsubscribeResult, ControlError>;
193    /// `control.listSubscriptions`
194    async fn list_subscriptions(&self) -> Result<results::ListSubscriptionsResult, ControlError>;
195    /// `control.wallet.balance` (READ-only)
196    async fn wallet_balance(
197        &self,
198        params: params::WalletBalanceParams,
199    ) -> Result<results::WalletBalanceResult, ControlError>;
200    /// `control.wallet.coins` (READ-only, OPEN)
201    ///
202    /// An empty `coins` list MUST mean "a chain was consulted and this address holds nothing".
203    /// A read that could not consult a chain MUST return the matching catalogued error instead.
204    async fn wallet_coins(
205        &self,
206        params: params::WalletCoinsParams,
207    ) -> Result<results::WalletCoinsResult, ControlError>;
208    /// `control.wallet.peak` (READ-only, OPEN)
209    async fn wallet_peak(&self) -> Result<results::WalletPeakResult, ControlError>;
210    /// `control.wallet.broadcast` (TOKEN-GATED)
211    ///
212    /// Pushes an ALREADY-SIGNED bundle: the implementation never signs, and never receives anything
213    /// it could sign with (§908). A mempool refusal is `Ok` with `accepted: false`; failing to
214    /// reach a mempool is `Err`.
215    async fn wallet_broadcast(
216        &self,
217        params: params::WalletBroadcastParams,
218    ) -> Result<results::WalletBroadcastResult, ControlError>;
219    /// `pairing.request` (OPEN)
220    async fn pairing_request(
221        &self,
222        params: params::RequestParams,
223    ) -> Result<results::PairingRequestResult, ControlError>;
224    /// `pairing.poll` (OPEN)
225    async fn pairing_poll(
226        &self,
227        params: params::PollParams,
228    ) -> Result<results::PairingPollResult, ControlError>;
229
230    /// Route a raw JSON-RPC request to the right typed method and build the response envelope.
231    ///
232    /// Deserializes the params for methods that take them, calls the handler, and serializes the
233    /// typed result. An unknown method → `METHOD_NOT_FOUND`; malformed params → `INVALID_PARAMS`.
234    /// This is the single seam a server dispatches through — the KATs exercise it end-to-end.
235    async fn dispatch(&self, request: JsonRpcRequest) -> JsonRpcResponse {
236        let id = request.id.clone();
237        let Some(method) = ControlMethod::from_name(&request.method) else {
238            return JsonRpcResponse::error(
239                id,
240                ControlError::of(
241                    ControlErrorCode::MethodNotFound,
242                    format!("unknown control method: {}", request.method),
243                ),
244            );
245        };
246        match self.dispatch_method(method, request.params).await {
247            Ok(result) => JsonRpcResponse::success(id, result),
248            Err(err) => JsonRpcResponse::error(id, err),
249        }
250    }
251
252    /// Route to the typed method by [`ControlMethod`], returning the result as a [`Value`]. Split
253    /// from [`dispatch`](ControlHandler::dispatch) so the envelope wrapping stays in one place.
254    #[doc(hidden)]
255    async fn dispatch_method(
256        &self,
257        method: ControlMethod,
258        params: Value,
259    ) -> Result<Value, ControlError> {
260        /// Deserialize a method's params, mapping a shape error to `INVALID_PARAMS`.
261        fn decode<T: DeserializeOwned>(params: Value) -> Result<T, ControlError> {
262            serde_json::from_value(params)
263                .map_err(|e| ControlError::of(ControlErrorCode::InvalidParams, e.to_string()))
264        }
265        /// Serialize a typed result to a `Value` (infallible for our derive-Serialize results).
266        fn encode<T: Serialize>(value: T) -> Result<Value, ControlError> {
267            serde_json::to_value(value)
268                .map_err(|e| ControlError::of(ControlErrorCode::ControlError, e.to_string()))
269        }
270        match method {
271            ControlMethod::Status => encode(self.status().await?),
272            ControlMethod::ConfigGet => encode(self.config_get().await?),
273            ControlMethod::ConfigSetUpstream => {
274                encode(self.config_set_upstream(decode(params)?).await?)
275            }
276            ControlMethod::LogSetLevel => encode(self.log_set_level(decode(params)?).await?),
277            ControlMethod::CacheGet => encode(self.cache_get().await?),
278            ControlMethod::CacheSetCap => encode(self.cache_set_cap(decode(params)?).await?),
279            ControlMethod::CacheClear => encode(self.cache_clear().await?),
280            ControlMethod::HostedStoresList => encode(self.hosted_stores_list().await?),
281            ControlMethod::HostedStoresPin => {
282                encode(self.hosted_stores_pin(decode(params)?).await?)
283            }
284            ControlMethod::HostedStoresUnpin => {
285                encode(self.hosted_stores_unpin(decode(params)?).await?)
286            }
287            ControlMethod::HostedStoresStatus => {
288                encode(self.hosted_stores_status(decode(params)?).await?)
289            }
290            ControlMethod::SyncStatus => encode(self.sync_status().await?),
291            ControlMethod::SyncTrigger => encode(self.sync_trigger(decode(params)?).await?),
292            ControlMethod::UpdaterStatus => self.updater_status().await,
293            ControlMethod::UpdaterSetChannel => self.updater_set_channel(decode(params)?).await,
294            ControlMethod::UpdaterPause => self.updater_pause(decode(params)?).await,
295            ControlMethod::UpdaterResume => self.updater_resume().await,
296            ControlMethod::UpdaterCheckNow => self.updater_check_now().await,
297            ControlMethod::PairingList => self.pairing_list().await,
298            ControlMethod::PairingApprove => encode(self.pairing_approve(decode(params)?).await?),
299            ControlMethod::PairingRevoke => encode(self.pairing_revoke(decode(params)?).await?),
300            ControlMethod::PeerStatus => self.peer_status().await,
301            ControlMethod::PeersConnect => encode(self.peers_connect(decode(params)?).await?),
302            ControlMethod::PeersDisconnect => encode(self.peers_disconnect(decode(params)?).await?),
303            ControlMethod::Subscribe => encode(self.subscribe(decode(params)?).await?),
304            ControlMethod::Unsubscribe => encode(self.unsubscribe(decode(params)?).await?),
305            ControlMethod::ListSubscriptions => encode(self.list_subscriptions().await?),
306            ControlMethod::WalletBalance => encode(self.wallet_balance(decode(params)?).await?),
307            ControlMethod::WalletCoins => encode(self.wallet_coins(decode(params)?).await?),
308            ControlMethod::WalletPeak => encode(self.wallet_peak().await?),
309            ControlMethod::WalletBroadcast => encode(self.wallet_broadcast(decode(params)?).await?),
310            ControlMethod::PairingRequest => encode(self.pairing_request(decode(params)?).await?),
311            ControlMethod::PairingPoll => encode(self.pairing_poll(decode(params)?).await?),
312        }
313    }
314}