1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
use barter_integration::{error::SocketError, Validator};
use serde::{Deserialize, Serialize};
/// [`Coinbase`](super::Coinbase) WebSocket subscription response.
///
/// ### Raw Payload Examples
/// See docs: <https://docs.cloud.coinbase.com/exchange/docs/websocket-overview#subscribe>
/// #### Subscripion Success
/// ```json
/// {
/// "type":"subscriptions",
/// "channels":[
/// {"name":"matches","product_ids":["BTC-USD", "ETH-USD"]}
/// ]
/// }
/// ```
///
/// #### Subscription Failure
/// ```json
/// {
/// "type":"error",
/// "message":"Failed to subscribe",
/// "reason":"GIBBERISH-USD is not a valid product"
/// }
/// ```
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Deserialize, Serialize)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum CoinbaseSubResponse {
#[serde(alias = "subscriptions")]
Subscribed {
channels: Vec<CoinbaseChannels>,
},
Error {
reason: String,
},
}
/// Communicates the [`Coinbase`](super::Coinbase) product_ids (eg/ "ETH-USD") associated with
/// a successful channel (eg/ "matches") subscription.
///
/// See [`CoinbaseSubResponse`] for full raw paylaod examples.
///
/// See docs: <https://docs.cloud.coinbase.com/exchange/docs/websocket-overview#subscribe>
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Deserialize, Serialize)]
pub struct CoinbaseChannels {
#[serde(alias = "name")]
pub channel: String,
pub product_ids: Vec<String>,
}
impl Validator for CoinbaseSubResponse {
fn validate(self) -> Result<Self, SocketError>
where
Self: Sized,
{
match &self {
CoinbaseSubResponse::Subscribed { .. } => Ok(self),
CoinbaseSubResponse::Error { reason } => Err(SocketError::Subscribe(format!(
"received failure subscription response: {}",
reason
))),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
mod de {
use super::*;
#[test]
fn test_coinbase_sub_response() {
struct TestCase {
input: &'static str,
expected: Result<CoinbaseSubResponse, SocketError>,
}
let cases = vec![
TestCase {
// TC0: input response is Subscribed
input: r#"
{
"type":"subscriptions",
"channels":[
{"name":"matches","product_ids":["BTC-USD", "ETH-USD"]}
]
}
"#,
expected: Ok(CoinbaseSubResponse::Subscribed {
channels: vec![CoinbaseChannels {
channel: "matches".to_string(),
product_ids: vec!["BTC-USD".to_string(), "ETH-USD".to_string()],
}],
}),
},
TestCase {
// TC1: input response is failed subscription
input: r#"
{
"type":"error",
"message":"Failed to subscribe",
"reason":"GIBBERISH-USD is not a valid product"
}
"#,
expected: Ok(CoinbaseSubResponse::Error {
reason: "GIBBERISH-USD is not a valid product".to_string(),
}),
},
];
for (index, test) in cases.into_iter().enumerate() {
let actual = serde_json::from_str::<CoinbaseSubResponse>(test.input);
match (actual, test.expected) {
(Ok(actual), Ok(expected)) => {
assert_eq!(actual, expected, "TC{} failed", index)
}
(Err(_), Err(_)) => {
// Test passed
}
(actual, expected) => {
// Test failed
panic!("TC{index} failed because actual != expected. \nActual: {actual:?}\nExpected: {expected:?}\n");
}
}
}
}
}
#[test]
fn test_validate_coinbase_sub_response() {
struct TestCase {
input_response: CoinbaseSubResponse,
is_valid: bool,
}
let cases = vec![
TestCase {
// TC0: input response is successful subscription
input_response: CoinbaseSubResponse::Subscribed {
channels: vec![CoinbaseChannels {
channel: "matches".to_string(),
product_ids: vec!["BTC-USD".to_string(), "ETH-USD".to_string()],
}],
},
is_valid: true,
},
TestCase {
// TC1: input response is failed subscription
input_response: CoinbaseSubResponse::Error {
reason: "GIBBERISH-USD is not a valid product".to_string(),
},
is_valid: false,
},
];
for (index, test) in cases.into_iter().enumerate() {
let actual = test.input_response.validate().is_ok();
assert_eq!(actual, test.is_valid, "TestCase {} failed", index);
}
}
}