Skip to main content

ctrader_connector/open_api/
payload.rs

1//! Typed pairing of messages with their payload types and of requests with their responses.
2
3use prost::Message;
4
5use crate::common::errors::{ConnectorError, SessionEndCause, SessionEnded, TransportError};
6use crate::common::ids::AccountId;
7use crate::open_api::messages::{
8    ProtoErrorRes, ProtoHeartbeatEvent, ProtoMessage, ProtoOaAccountAuthReq, ProtoOaAccountAuthRes,
9    ProtoOaAccountDisconnectEvent, ProtoOaAccountsTokenInvalidatedEvent, ProtoOaAmendOrderReq,
10    ProtoOaAmendPositionSltpReq, ProtoOaApplicationAuthReq, ProtoOaApplicationAuthRes,
11    ProtoOaAssetListReq, ProtoOaAssetListRes, ProtoOaCancelOrderReq, ProtoOaCashFlowHistoryListReq,
12    ProtoOaCashFlowHistoryListRes, ProtoOaClientDisconnectEvent, ProtoOaClosePositionReq,
13    ProtoOaDealListReq, ProtoOaDealListRes, ProtoOaDepthEvent, ProtoOaErrorRes,
14    ProtoOaExecutionEvent, ProtoOaGetAccountListByAccessTokenReq,
15    ProtoOaGetAccountListByAccessTokenRes, ProtoOaGetTickDataReq, ProtoOaGetTickDataRes,
16    ProtoOaGetTrendbarsReq, ProtoOaGetTrendbarsRes, ProtoOaMarginCallListReq,
17    ProtoOaMarginCallListRes, ProtoOaMarginCallTriggerEvent, ProtoOaMarginCallUpdateEvent,
18    ProtoOaMarginCallUpdateReq, ProtoOaMarginCallUpdateRes, ProtoOaMarginChangedEvent,
19    ProtoOaNewOrderReq, ProtoOaOrderErrorEvent, ProtoOaOrderListReq, ProtoOaOrderListRes,
20    ProtoOaPayloadType, ProtoOaReconcileReq, ProtoOaReconcileRes, ProtoOaRefreshTokenReq,
21    ProtoOaRefreshTokenRes, ProtoOaSpotEvent, ProtoOaSubscribeDepthQuotesReq,
22    ProtoOaSubscribeDepthQuotesRes, ProtoOaSubscribeLiveTrendbarReq,
23    ProtoOaSubscribeLiveTrendbarRes, ProtoOaSubscribeSpotsReq, ProtoOaSubscribeSpotsRes,
24    ProtoOaSymbolByIdReq, ProtoOaSymbolByIdRes, ProtoOaSymbolsListReq, ProtoOaSymbolsListRes,
25    ProtoOaTraderReq, ProtoOaTraderRes, ProtoOaUnsubscribeDepthQuotesReq,
26    ProtoOaUnsubscribeDepthQuotesRes, ProtoOaUnsubscribeLiveTrendbarReq,
27    ProtoOaUnsubscribeLiveTrendbarRes, ProtoOaUnsubscribeSpotsReq, ProtoOaUnsubscribeSpotsRes,
28    ProtoOaVersionReq, ProtoOaVersionRes, ProtoPayloadType,
29};
30
31/// Message that travels inside a [`ProtoMessage`] under a fixed payload type.
32pub trait Payload: Message + Default {
33    /// Number that identifies the message on the wire.
34    const PAYLOAD_TYPE: u32;
35
36    /// Wraps the message in the envelope the transport frames.
37    fn to_message(&self, client_msg_id: Option<String>) -> ProtoMessage {
38        ProtoMessage {
39            payload_type: Self::PAYLOAD_TYPE,
40            payload: Some(self.encode_to_vec()),
41            client_msg_id,
42        }
43    }
44
45    /// Unwraps the message from its envelope.
46    ///
47    /// # Errors
48    ///
49    /// Returns [`ConnectorError::UnexpectedResponse`] when the envelope carries another payload
50    /// type and [`TransportError::Decode`] when the payload is malformed.
51    fn from_message(message: &ProtoMessage) -> Result<Self, ConnectorError> {
52        if message.payload_type != Self::PAYLOAD_TYPE {
53            return Err(ConnectorError::UnexpectedResponse {
54                expected: Self::PAYLOAD_TYPE,
55                received: message.payload_type,
56            });
57        }
58        Self::decode(message.payload.as_deref().unwrap_or_default())
59            .map_err(|error| TransportError::Decode(error.to_string()).into())
60    }
61}
62
63/// Message the server answers with exactly one response.
64pub trait Request: Payload {
65    /// Message the server answers with.
66    type Response: Payload;
67
68    /// Tells whether the request counts against the stricter limit for historical data.
69    const HISTORICAL: bool = false;
70}
71
72macro_rules! payloads {
73    ($($message:ident => $kind:expr,)*) => {
74        $(impl Payload for $message {
75            const PAYLOAD_TYPE: u32 = $kind as u32;
76        })*
77
78        #[cfg(test)]
79        fn declared() -> Vec<(&'static str, u32, i32)> {
80            vec![$((
81                stringify!($message),
82                <$message>::PAYLOAD_TYPE,
83                <$message>::default().payload_type() as i32,
84            ),)*]
85        }
86    };
87}
88
89macro_rules! requests {
90    ($($request:ident => $response:ident, $historical:literal;)*) => {
91        $(impl Request for $request {
92            type Response = $response;
93
94            const HISTORICAL: bool = $historical;
95        })*
96
97        /// Tells whether requests of the payload type count against the limit for historical data.
98        #[must_use]
99        pub fn is_historical(payload_type: u32) -> bool {
100            [$((<$request as Payload>::PAYLOAD_TYPE, $historical)),*]
101                .iter()
102                .any(|(known, historical)| *historical && *known == payload_type)
103        }
104    };
105}
106
107#[derive(Clone, PartialEq, Eq, Message)]
108struct AccountScope {
109    #[prost(int64, optional, tag = "2")]
110    account: Option<i64>,
111}
112
113/// Returns the account the message of the payload type acts on, read from its encoded form.
114///
115/// Every message of the Open API that belongs to an account carries the account in its second
116/// field. The requests that belong to the application as a whole name no account.
117pub(crate) fn account_of(payload_type: u32, payload: &[u8]) -> Option<AccountId> {
118    let unscoped = [
119        ProtoHeartbeatEvent::PAYLOAD_TYPE,
120        ProtoOaApplicationAuthReq::PAYLOAD_TYPE,
121        ProtoOaVersionReq::PAYLOAD_TYPE,
122        ProtoOaGetAccountListByAccessTokenReq::PAYLOAD_TYPE,
123        ProtoOaRefreshTokenReq::PAYLOAD_TYPE,
124    ];
125    if unscoped.contains(&payload_type) {
126        return None;
127    }
128    let scope = AccountScope::decode(payload).ok()?;
129    AccountId::new(scope.account?).ok()
130}
131
132/// Returns the sessions whose authorisation the pushed message ends, one for every account
133/// it names, or the session of the application.
134pub(crate) fn sessions_ended_by(message: &ProtoMessage) -> Vec<SessionEnded> {
135    if let Ok(event) = ProtoOaAccountsTokenInvalidatedEvent::from_message(message) {
136        let cause = SessionEndCause::TokenInvalidated {
137            reason: event.reason,
138        };
139        event
140            .ctid_trader_account_ids
141            .into_iter()
142            .filter_map(|id| AccountId::new(id).ok())
143            .map(|account| SessionEnded::new(Some(account), cause.clone()))
144            .collect()
145    } else if let Ok(event) = ProtoOaAccountDisconnectEvent::from_message(message) {
146        AccountId::new(event.ctid_trader_account_id)
147            .ok()
148            .map(|account| SessionEnded::new(Some(account), SessionEndCause::AccountDisconnected))
149            .into_iter()
150            .collect()
151    } else if let Ok(event) = ProtoOaClientDisconnectEvent::from_message(message) {
152        vec![SessionEnded::new(
153            None,
154            SessionEndCause::ClientDisconnected {
155                reason: event.reason,
156            },
157        )]
158    } else {
159        Vec::new()
160    }
161}
162
163payloads! {
164    ProtoErrorRes => ProtoPayloadType::ErrorRes,
165    ProtoHeartbeatEvent => ProtoPayloadType::HeartbeatEvent,
166    ProtoOaApplicationAuthReq => ProtoOaPayloadType::ProtoOaApplicationAuthReq,
167    ProtoOaApplicationAuthRes => ProtoOaPayloadType::ProtoOaApplicationAuthRes,
168    ProtoOaAccountAuthReq => ProtoOaPayloadType::ProtoOaAccountAuthReq,
169    ProtoOaAccountAuthRes => ProtoOaPayloadType::ProtoOaAccountAuthRes,
170    ProtoOaVersionReq => ProtoOaPayloadType::ProtoOaVersionReq,
171    ProtoOaVersionRes => ProtoOaPayloadType::ProtoOaVersionRes,
172    ProtoOaSubscribeSpotsReq => ProtoOaPayloadType::ProtoOaSubscribeSpotsReq,
173    ProtoOaSubscribeSpotsRes => ProtoOaPayloadType::ProtoOaSubscribeSpotsRes,
174    ProtoOaUnsubscribeSpotsReq => ProtoOaPayloadType::ProtoOaUnsubscribeSpotsReq,
175    ProtoOaUnsubscribeSpotsRes => ProtoOaPayloadType::ProtoOaUnsubscribeSpotsRes,
176    ProtoOaSpotEvent => ProtoOaPayloadType::ProtoOaSpotEvent,
177    ProtoOaDealListReq => ProtoOaPayloadType::ProtoOaDealListReq,
178    ProtoOaDealListRes => ProtoOaPayloadType::ProtoOaDealListRes,
179    ProtoOaGetTrendbarsReq => ProtoOaPayloadType::ProtoOaGetTrendbarsReq,
180    ProtoOaGetTrendbarsRes => ProtoOaPayloadType::ProtoOaGetTrendbarsRes,
181    ProtoOaErrorRes => ProtoOaPayloadType::ProtoOaErrorRes,
182    ProtoOaCashFlowHistoryListReq => ProtoOaPayloadType::ProtoOaCashFlowHistoryListReq,
183    ProtoOaCashFlowHistoryListRes => ProtoOaPayloadType::ProtoOaCashFlowHistoryListRes,
184    ProtoOaGetTickDataReq => ProtoOaPayloadType::ProtoOaGetTickdataReq,
185    ProtoOaGetTickDataRes => ProtoOaPayloadType::ProtoOaGetTickdataRes,
186    ProtoOaAccountsTokenInvalidatedEvent => ProtoOaPayloadType::ProtoOaAccountsTokenInvalidatedEvent,
187    ProtoOaClientDisconnectEvent => ProtoOaPayloadType::ProtoOaClientDisconnectEvent,
188    ProtoOaGetAccountListByAccessTokenReq => ProtoOaPayloadType::ProtoOaGetAccountsByAccessTokenReq,
189    ProtoOaGetAccountListByAccessTokenRes => ProtoOaPayloadType::ProtoOaGetAccountsByAccessTokenRes,
190    ProtoOaAccountDisconnectEvent => ProtoOaPayloadType::ProtoOaAccountDisconnectEvent,
191    ProtoOaRefreshTokenReq => ProtoOaPayloadType::ProtoOaRefreshTokenReq,
192    ProtoOaRefreshTokenRes => ProtoOaPayloadType::ProtoOaRefreshTokenRes,
193    ProtoOaSubscribeLiveTrendbarReq => ProtoOaPayloadType::ProtoOaSubscribeLiveTrendbarReq,
194    ProtoOaSubscribeLiveTrendbarRes => ProtoOaPayloadType::ProtoOaSubscribeLiveTrendbarRes,
195    ProtoOaUnsubscribeLiveTrendbarReq => ProtoOaPayloadType::ProtoOaUnsubscribeLiveTrendbarReq,
196    ProtoOaUnsubscribeLiveTrendbarRes => ProtoOaPayloadType::ProtoOaUnsubscribeLiveTrendbarRes,
197    ProtoOaDepthEvent => ProtoOaPayloadType::ProtoOaDepthEvent,
198    ProtoOaSubscribeDepthQuotesReq => ProtoOaPayloadType::ProtoOaSubscribeDepthQuotesReq,
199    ProtoOaSubscribeDepthQuotesRes => ProtoOaPayloadType::ProtoOaSubscribeDepthQuotesRes,
200    ProtoOaUnsubscribeDepthQuotesReq => ProtoOaPayloadType::ProtoOaUnsubscribeDepthQuotesReq,
201    ProtoOaUnsubscribeDepthQuotesRes => ProtoOaPayloadType::ProtoOaUnsubscribeDepthQuotesRes,
202    ProtoOaAssetListReq => ProtoOaPayloadType::ProtoOaAssetListReq,
203    ProtoOaAssetListRes => ProtoOaPayloadType::ProtoOaAssetListRes,
204    ProtoOaSymbolsListReq => ProtoOaPayloadType::ProtoOaSymbolsListReq,
205    ProtoOaSymbolsListRes => ProtoOaPayloadType::ProtoOaSymbolsListRes,
206    ProtoOaSymbolByIdReq => ProtoOaPayloadType::ProtoOaSymbolByIdReq,
207    ProtoOaSymbolByIdRes => ProtoOaPayloadType::ProtoOaSymbolByIdRes,
208    ProtoOaNewOrderReq => ProtoOaPayloadType::ProtoOaNewOrderReq,
209    ProtoOaCancelOrderReq => ProtoOaPayloadType::ProtoOaCancelOrderReq,
210    ProtoOaAmendOrderReq => ProtoOaPayloadType::ProtoOaAmendOrderReq,
211    ProtoOaAmendPositionSltpReq => ProtoOaPayloadType::ProtoOaAmendPositionSltpReq,
212    ProtoOaClosePositionReq => ProtoOaPayloadType::ProtoOaClosePositionReq,
213    ProtoOaReconcileReq => ProtoOaPayloadType::ProtoOaReconcileReq,
214    ProtoOaReconcileRes => ProtoOaPayloadType::ProtoOaReconcileRes,
215    ProtoOaExecutionEvent => ProtoOaPayloadType::ProtoOaExecutionEvent,
216    ProtoOaOrderErrorEvent => ProtoOaPayloadType::ProtoOaOrderErrorEvent,
217    ProtoOaTraderReq => ProtoOaPayloadType::ProtoOaTraderReq,
218    ProtoOaTraderRes => ProtoOaPayloadType::ProtoOaTraderRes,
219    ProtoOaOrderListReq => ProtoOaPayloadType::ProtoOaOrderListReq,
220    ProtoOaOrderListRes => ProtoOaPayloadType::ProtoOaOrderListRes,
221    ProtoOaMarginChangedEvent => ProtoOaPayloadType::ProtoOaMarginChangedEvent,
222    ProtoOaMarginCallListReq => ProtoOaPayloadType::ProtoOaMarginCallListReq,
223    ProtoOaMarginCallListRes => ProtoOaPayloadType::ProtoOaMarginCallListRes,
224    ProtoOaMarginCallUpdateReq => ProtoOaPayloadType::ProtoOaMarginCallUpdateReq,
225    ProtoOaMarginCallUpdateRes => ProtoOaPayloadType::ProtoOaMarginCallUpdateRes,
226    ProtoOaMarginCallUpdateEvent => ProtoOaPayloadType::ProtoOaMarginCallUpdateEvent,
227    ProtoOaMarginCallTriggerEvent => ProtoOaPayloadType::ProtoOaMarginCallTriggerEvent,
228}
229
230requests! {
231    ProtoOaApplicationAuthReq => ProtoOaApplicationAuthRes, false;
232    ProtoOaAccountAuthReq => ProtoOaAccountAuthRes, false;
233    ProtoOaVersionReq => ProtoOaVersionRes, false;
234    ProtoOaSubscribeSpotsReq => ProtoOaSubscribeSpotsRes, false;
235    ProtoOaUnsubscribeSpotsReq => ProtoOaUnsubscribeSpotsRes, false;
236    ProtoOaGetAccountListByAccessTokenReq => ProtoOaGetAccountListByAccessTokenRes, false;
237    ProtoOaRefreshTokenReq => ProtoOaRefreshTokenRes, false;
238    ProtoOaSubscribeLiveTrendbarReq => ProtoOaSubscribeLiveTrendbarRes, false;
239    ProtoOaUnsubscribeLiveTrendbarReq => ProtoOaUnsubscribeLiveTrendbarRes, false;
240    ProtoOaSubscribeDepthQuotesReq => ProtoOaSubscribeDepthQuotesRes, false;
241    ProtoOaUnsubscribeDepthQuotesReq => ProtoOaUnsubscribeDepthQuotesRes, false;
242    ProtoOaAssetListReq => ProtoOaAssetListRes, false;
243    ProtoOaSymbolsListReq => ProtoOaSymbolsListRes, false;
244    ProtoOaSymbolByIdReq => ProtoOaSymbolByIdRes, false;
245    ProtoOaReconcileReq => ProtoOaReconcileRes, false;
246    ProtoOaTraderReq => ProtoOaTraderRes, false;
247    ProtoOaMarginCallListReq => ProtoOaMarginCallListRes, false;
248    ProtoOaMarginCallUpdateReq => ProtoOaMarginCallUpdateRes, false;
249    ProtoOaDealListReq => ProtoOaDealListRes, true;
250    ProtoOaOrderListReq => ProtoOaOrderListRes, true;
251    ProtoOaGetTrendbarsReq => ProtoOaGetTrendbarsRes, true;
252    ProtoOaCashFlowHistoryListReq => ProtoOaCashFlowHistoryListRes, true;
253    ProtoOaGetTickDataReq => ProtoOaGetTickDataRes, true;
254}
255
256#[cfg(test)]
257mod tests {
258    use prost::Message as _;
259
260    use super::{Payload, Request, account_of, declared, is_historical, sessions_ended_by};
261    use crate::common::errors::{ConnectorError, SessionEndCause, SessionEnded, TransportError};
262    use crate::common::ids::AccountId;
263    use crate::open_api::messages::{
264        ProtoHeartbeatEvent, ProtoMessage, ProtoOaAccountAuthReq, ProtoOaAccountDisconnectEvent,
265        ProtoOaAccountsTokenInvalidatedEvent, ProtoOaClientDisconnectEvent,
266        ProtoOaGetAccountListByAccessTokenReq, ProtoOaGetTrendbarsReq, ProtoOaTraderReq,
267        ProtoOaVersionReq, ProtoOaVersionRes,
268    };
269
270    #[test]
271    fn declared_payload_types_match_the_defaults_in_the_proto_files() {
272        let declared = declared();
273        assert_eq!(declared.len(), 64);
274        for (name, constant, default) in declared {
275            assert_eq!(i64::from(constant), i64::from(default), "{name}");
276        }
277        assert_eq!(ProtoHeartbeatEvent::PAYLOAD_TYPE, 51);
278        assert_eq!(ProtoOaVersionReq::PAYLOAD_TYPE, 2104);
279    }
280
281    #[test]
282    fn only_requests_for_historical_data_are_marked_historical() {
283        fn historical<R: Request>(_: &R) -> bool {
284            R::HISTORICAL
285        }
286        assert!(historical(&ProtoOaGetTrendbarsReq::default()));
287        assert!(!historical(&ProtoOaVersionReq::default()));
288        assert!(is_historical(ProtoOaGetTrendbarsReq::PAYLOAD_TYPE));
289        assert!(!is_historical(ProtoOaVersionReq::PAYLOAD_TYPE));
290        assert!(!is_historical(0));
291    }
292
293    #[test]
294    fn account_is_read_from_scoped_messages_only() {
295        let account = AccountId::new(7).expect("account id");
296        let scoped = ProtoOaTraderReq {
297            payload_type: None,
298            ctid_trader_account_id: 7,
299        };
300        assert_eq!(
301            account_of(ProtoOaTraderReq::PAYLOAD_TYPE, &scoped.encode_to_vec()),
302            Some(account)
303        );
304        let authorisation = ProtoOaAccountAuthReq {
305            payload_type: None,
306            ctid_trader_account_id: 7,
307            access_token: "token".to_owned(),
308        };
309        assert_eq!(
310            account_of(
311                ProtoOaAccountAuthReq::PAYLOAD_TYPE,
312                &authorisation.encode_to_vec()
313            ),
314            Some(account)
315        );
316        let list = ProtoOaGetAccountListByAccessTokenReq {
317            payload_type: None,
318            access_token: "token".to_owned(),
319        };
320        assert_eq!(
321            account_of(
322                ProtoOaGetAccountListByAccessTokenReq::PAYLOAD_TYPE,
323                &list.encode_to_vec()
324            ),
325            None
326        );
327        assert_eq!(account_of(ProtoOaVersionReq::PAYLOAD_TYPE, &[]), None);
328        assert_eq!(account_of(ProtoOaTraderReq::PAYLOAD_TYPE, &[0xff]), None);
329        let nobody = ProtoOaTraderReq {
330            payload_type: None,
331            ctid_trader_account_id: 0,
332        };
333        assert_eq!(
334            account_of(ProtoOaTraderReq::PAYLOAD_TYPE, &nobody.encode_to_vec()),
335            None
336        );
337    }
338
339    #[test]
340    fn only_the_three_events_end_sessions() {
341        let account = |id| AccountId::new(id).expect("account id");
342        let invalidated = ProtoOaAccountsTokenInvalidatedEvent {
343            payload_type: None,
344            ctid_trader_account_ids: vec![7, 0, 8],
345            reason: Some("refreshed".to_owned()),
346        };
347        let cause = SessionEndCause::TokenInvalidated {
348            reason: Some("refreshed".to_owned()),
349        };
350        assert_eq!(
351            sessions_ended_by(&invalidated.to_message(None)),
352            vec![
353                SessionEnded::new(Some(account(7)), cause.clone()),
354                SessionEnded::new(Some(account(8)), cause),
355            ]
356        );
357        let dropped = ProtoOaAccountDisconnectEvent {
358            payload_type: None,
359            ctid_trader_account_id: 7,
360        };
361        assert_eq!(
362            sessions_ended_by(&dropped.to_message(None)),
363            vec![SessionEnded::new(
364                Some(account(7)),
365                SessionEndCause::AccountDisconnected
366            )]
367        );
368        let nobody = ProtoOaAccountDisconnectEvent {
369            payload_type: None,
370            ctid_trader_account_id: -1,
371        };
372        assert_eq!(sessions_ended_by(&nobody.to_message(None)), Vec::new());
373        let client = ProtoOaClientDisconnectEvent {
374            payload_type: None,
375            reason: None,
376        };
377        assert_eq!(
378            sessions_ended_by(&client.to_message(None)),
379            vec![SessionEnded::new(
380                None,
381                SessionEndCause::ClientDisconnected { reason: None }
382            )]
383        );
384        assert_eq!(
385            sessions_ended_by(&ProtoOaVersionReq::default().to_message(None)),
386            Vec::new()
387        );
388    }
389
390    #[test]
391    fn message_round_trips_through_its_envelope() {
392        let response = ProtoOaVersionRes {
393            payload_type: None,
394            version: "97".to_owned(),
395        };
396        let envelope = response.to_message(Some("id".to_owned()));
397        assert_eq!(envelope.payload_type, 2105);
398        assert_eq!(envelope.client_msg_id.as_deref(), Some("id"));
399        assert_eq!(ProtoOaVersionRes::from_message(&envelope), Ok(response));
400    }
401
402    #[test]
403    fn envelope_of_another_type_is_rejected() {
404        let envelope = ProtoOaVersionReq::default().to_message(None);
405        assert_eq!(
406            ProtoOaVersionRes::from_message(&envelope),
407            Err(ConnectorError::UnexpectedResponse {
408                expected: 2105,
409                received: 2104,
410            })
411        );
412    }
413
414    #[test]
415    fn malformed_payload_is_a_decode_error_and_an_absent_one_is_empty() {
416        let envelope = ProtoMessage {
417            payload_type: 2105,
418            payload: Some(vec![0xff]),
419            client_msg_id: None,
420        };
421        assert!(matches!(
422            ProtoOaVersionRes::from_message(&envelope),
423            Err(ConnectorError::Transport(TransportError::Decode(_)))
424        ));
425        let empty = ProtoMessage {
426            payload_type: 2105,
427            payload: None,
428            client_msg_id: None,
429        };
430        assert_eq!(
431            ProtoOaVersionRes::from_message(&empty),
432            Ok(ProtoOaVersionRes::default())
433        );
434    }
435}