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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
use std::{
    collections::HashMap,
    net::{IpAddr, Ipv4Addr, Ipv6Addr},
};

use serde::{Deserialize, Serialize};

use crate::{RPCResponse, RPCResult};

#[derive(Serialize)]
#[serde(rename_all = "PascalCase")]
pub(crate) struct RequestHeader {
    pub seq: u64,
    pub command: &'static str,
}

#[derive(Deserialize)]
#[serde(rename_all = "PascalCase")]
pub(crate) struct ResponseHeader {
    pub seq: u64,
    pub error: String,
}

macro_rules! count {
    () => { 0 };
    ($item:tt) => {1};
    ($item:tt$(, $rest:tt)+) => { count!( $($rest),+ ) + 1 }
}

macro_rules! cmd_arg {
    (
        $buf:expr,
        $($key:literal: $val:expr),*
    ) => {{
        let len: u32 = count!( $($key),* );

        rmp::encode::write_map_len($buf, len).unwrap();
        $(
            rmp::encode::write_str($buf, $key).unwrap();
            rmp_serde::encode::write_named($buf, $val).unwrap();
        )*
    }};
}

macro_rules! req {
    (
        $name:literal
        $(#[$meta:meta])*
        $vis:vis $ident:ident( $($arg:ident: $arg_ty:ty),* ) -> $res:ty $({
            $($key:literal: $val:expr),*
        })?
    ) => {
        impl crate::Client {
            $(#[$meta])*
            $vis fn $ident<'a>(&'a self$(, $arg: $arg_ty)*) -> crate::RPCRequest<'a, $res> {
                #[allow(unused_mut)]
                let mut buf = Vec::new();

                $(cmd_arg! { &mut buf, $($key: $val),* };)?

                self.request($name, buf)
            }
        }
    };
}

macro_rules! stream {
    (
        $name:literal

        $vis:vis $ident:ident( $($arg:ident: $arg_ty:ty),* ) -> $res:ty $({
            $($key:literal: $val:expr),*
        })?
    ) => {
        impl crate::Client {
            $vis fn $ident(self: &std::sync::Arc<Self>$(, $arg: $arg_ty)*) -> crate::RPCStream<$res> {
                #[allow(unused_mut)]
                let mut buf = Vec::new();

                $(cmd_arg! { &mut buf, $($key: $val),* };)?

                self.start_stream($name, buf)
            }
        }
    };
}

macro_rules! res {
    ($ty:ty) => {
        impl RPCResponse for $ty {
            fn read_from(read: crate::SeqRead<'_>) -> RPCResult<Self> {
                Ok(read.read_msg())
            }
        }
    };
}

req! {
    "handshake"
    /// Send a handshake
    pub(crate) handshake(version: u32) -> () {
        "Version": &version
    }
}

req! {
    "auth"
    /// Send an auth key
    pub(crate) auth(auth_key: &str) -> () {
        "AuthKey": auth_key
    }
}

req! {
    "event"
    /// Fire an event
    pub fire_event(name: &str, payload: &[u8], coalesce: bool) -> () {
        "Name": name,
        "Payload": payload,
        "Coalesce": &coalesce
    }
}

req! {
    "force-leave"
    /// Force a node to leave
    pub force_leave(node: &str) -> () {
        "Node": node
    }
}

#[derive(Deserialize, Debug)]
pub struct JoinResponse {
    #[serde(rename = "Num")]
    pub nodes_joined: u64,
}

res!(JoinResponse);

req! {
    "join"
    /// Join a serf cluster, given existing ip addresses. `replay` controls whether to replay old user events
    pub join(existing: &[&str], replay: bool) -> JoinResponse {
        "Existing": existing,
        "Replay": &replay
    }
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct Member {
    pub name: String,
    #[serde(deserialize_with = "deserialize_ip_addr")]
    pub addr: IpAddr,
    pub port: u32,
    pub tags: HashMap<String, String>,
    pub status: String,
    pub protocol_min: u32,
    pub protocol_max: u32,
    pub protocol_cur: u32,
    pub delegate_max: u32,
    pub delegate_min: u32,
    pub delegate_cur: u32,
}

fn deserialize_ip_addr<'de, D>(de: D) -> Result<IpAddr, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let addr = Ipv6Addr::from(<u128 as serde::Deserialize>::deserialize(de)?);

    // serf gives us ipv6 ips, with ipv4 addresses mapped to ipv6.
    // https://en.wikipedia.org/wiki/IPv6#IPv4-mapped_IPv6_addresses
    //
    // based on std's unstable to_ipv4_mapped()
    let addr = match addr.octets() {
        [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, a, b, c, d] => {
            IpAddr::V4(Ipv4Addr::new(a, b, c, d))
        }
        _ => IpAddr::V6(addr),
    };

    Ok(addr)
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct MembersResponse {
    pub members: Vec<Member>,
}

res!(MembersResponse);

req! {
    "members"
    /// Returns a list of all known members
    pub members() -> MembersResponse
}

req! {
    "members-filtered"
    /// Returns a filtered list of all known members
    pub members_filtered(status: Option<&str>, name: Option<&str>, tags: Option<&HashMap<String, String>>) -> MembersResponse {
        "Status": &status,
        "Name": &name,
        "Tags": &tags
    }
}

req! {
    "tags"
    /// Modifies the tags of the current node
    pub tags(add_tags: &[&str], delete_tags: &[&str]) -> MembersResponse {
        "Tags": add_tags,
        "DeleteTags": delete_tags
    }
}

req! {
    "stop"
    /// Stops a stream by seq id (this is automatically called on Drop by the RPCStream struct)
    pub(crate) stop_stream(seq: u64) -> () {
        "Stop": &seq
    }
}

req! {
    "leave"
    /// Gracefully leave
    pub leave() -> ()
}

req! {
    "respond"
    /// Response to a query
    pub query_respond(id: u64, payload: &[u8]) -> () {
        "ID": &id,
        "Payload": payload
    }
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct Coordinate {
    pub adjustment: f32,
    pub error: f32,
    pub height: f32,
    pub vec: [f32; 8],
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct CoordinateResponse {
    pub ok: bool,

    #[serde(default)]
    pub coord: Option<Coordinate>,
}

res!(CoordinateResponse);

req! {
    "get-coordinate"
    /// Get a node's coordinate
    pub get_coordinate(node: &str) -> CoordinateResponse {
        "Node": node
    }
}

#[derive(Deserialize, Debug)]
pub struct Agent {
    pub name: String,
}

#[derive(Deserialize, Debug)]
pub struct RuntimeInfo {
    pub os: String,
    pub arch: String,
    pub version: String,
    pub max_procs: String,
    pub goroutines: String,
    pub cpu_count: String,
}

#[derive(Deserialize, Debug)]
pub struct SerfInfo {
    pub failed: String,
    pub left: String,
    pub event_time: String,
    pub query_time: String,
    pub event_queue: String,
    pub members: String,
    pub member_time: String,
    pub intent_queue: String,
    pub query_queue: String,
}

#[derive(Deserialize, Debug)]
pub struct AgentStats {
    pub agent: Agent,
    pub runtime: RuntimeInfo,
    pub serf: SerfInfo,
    pub tags: HashMap<String, String>,
}

res!(AgentStats);

req! {
    "stats"
    /// Get information about the Serf agent.
    pub stats() -> AgentStats
}

// TODO: STREAM, MONITOR, QUERY

#[derive(Deserialize, Debug)]
#[serde(tag = "Event")]
pub enum StreamMessage {
    #[serde(rename = "user")]
    User {
        #[serde(rename = "LTime")]
        ltime: u64,
        #[serde(rename = "Name")]
        name: String,
        #[serde(rename = "Payload")]
        payload: Vec<u8>,
        #[serde(rename = "Coalesce")]
        coalesce: bool,
    },
    #[serde(rename = "member-join")]
    MemberJoin {
        #[serde(rename = "Members")]
        members: Vec<Member>,
    },
    Query {
        #[serde(rename = "ID")]
        id: u64,
        #[serde(rename = "LTime")]
        ltime: u64,
        #[serde(rename = "Name")]
        name: String,
        #[serde(rename = "Payload")]
        payload: Vec<u8>,
    },
}
res!(StreamMessage);

stream! {
    "stream"
    pub stream(ty: &str) -> StreamMessage {
        "Type": ty
    }
}

// TODO: query