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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
use std::sync::Arc;

use crate::{
  JoinMessageTransformError, LeaveMessageTransformError, MemberTransformError,
  PushPullMessageTransformError, QueryMessageTransformError, QueryResponseMessageTransformError,
  UserEventMessageTransformError,
};

use super::{
  Encodable, JoinMessage, LeaveMessage, Member, PushPullMessage, PushPullMessageRef, QueryMessage,
  QueryResponseMessage, Transformable, UserEventMessage,
};

#[cfg(feature = "encryption")]
use super::{KeyRequestMessage, KeyResponseMessage};

const LEAVE_MESSAGE_TAG: u8 = 0;
const JOIN_MESSAGE_TAG: u8 = 1;
const PUSH_PULL_MESSAGE_TAG: u8 = 2;
const USER_EVENT_MESSAGE_TAG: u8 = 3;
const QUERY_MESSAGE_TAG: u8 = 4;
const QUERY_RESPONSE_MESSAGE_TAG: u8 = 5;
const CONFLICT_RESPONSE_MESSAGE_TAG: u8 = 6;
const RELAY_MESSAGE_TAG: u8 = 7;
#[cfg(feature = "encryption")]
const KEY_REQUEST_MESSAGE_TAG: u8 = 253;
#[cfg(feature = "encryption")]
const KEY_RESPONSE_MESSAGE_TAG: u8 = 254;

/// Unknown message type error
#[derive(Debug, thiserror::Error)]
#[error("unknown message type byte: {0}")]
pub struct UnknownMessageType(u8);

impl TryFrom<u8> for MessageType {
  type Error = UnknownMessageType;

  fn try_from(value: u8) -> Result<Self, Self::Error> {
    Ok(match value {
      LEAVE_MESSAGE_TAG => Self::Leave,
      JOIN_MESSAGE_TAG => Self::Join,
      PUSH_PULL_MESSAGE_TAG => Self::PushPull,
      USER_EVENT_MESSAGE_TAG => Self::UserEvent,
      QUERY_MESSAGE_TAG => Self::Query,
      QUERY_RESPONSE_MESSAGE_TAG => Self::QueryResponse,
      CONFLICT_RESPONSE_MESSAGE_TAG => Self::ConflictResponse,
      RELAY_MESSAGE_TAG => Self::Relay,
      #[cfg(feature = "encryption")]
      KEY_REQUEST_MESSAGE_TAG => Self::KeyRequest,
      #[cfg(feature = "encryption")]
      KEY_RESPONSE_MESSAGE_TAG => Self::KeyResponse,
      _ => return Err(UnknownMessageType(value)),
    })
  }
}

impl From<MessageType> for u8 {
  fn from(value: MessageType) -> Self {
    value as u8
  }
}

/// The types of gossip messages Serf will send along
/// memberlist.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
#[repr(u8)]
#[non_exhaustive]
pub enum MessageType {
  /// Leave message
  Leave = LEAVE_MESSAGE_TAG,
  /// Join message
  Join = JOIN_MESSAGE_TAG,
  /// PushPull message
  PushPull = PUSH_PULL_MESSAGE_TAG,
  /// UserEvent message
  UserEvent = USER_EVENT_MESSAGE_TAG,
  /// Query message
  Query = QUERY_MESSAGE_TAG,
  /// QueryResponse message
  QueryResponse = QUERY_RESPONSE_MESSAGE_TAG,
  /// ConflictResponse message
  ConflictResponse = CONFLICT_RESPONSE_MESSAGE_TAG,
  /// Relay message
  Relay = RELAY_MESSAGE_TAG,
  /// KeyRequest message
  #[cfg(feature = "encryption")]
  KeyRequest = KEY_REQUEST_MESSAGE_TAG,
  /// KeyResponse message
  #[cfg(feature = "encryption")]
  KeyResponse = KEY_RESPONSE_MESSAGE_TAG,
}

impl MessageType {
  /// Get the string representation of the message type
  #[inline]
  pub const fn as_str(&self) -> &'static str {
    match self {
      Self::Leave => "leave",
      Self::Join => "join",
      Self::PushPull => "push pull",
      Self::UserEvent => "user event",
      Self::Query => "query",
      Self::QueryResponse => "query response",
      Self::ConflictResponse => "conflict response",
      Self::Relay => "relay",
      #[cfg(feature = "encryption")]
      Self::KeyRequest => "key request",
      #[cfg(feature = "encryption")]
      Self::KeyResponse => "key response",
    }
  }
}

/// Used to do a cheap reference to message reference conversion.
pub trait AsMessageRef<I, A> {
  /// Converts this type into a shared reference of the (usually inferred) input type.
  fn as_message_ref(&self) -> SerfMessageRef<'_, I, A>;
}

/// The reference type of [`SerfMessage`].
#[derive(Debug)]
pub enum SerfMessageRef<'a, I, A> {
  /// Leave message reference
  Leave(&'a LeaveMessage<I>),
  /// Join message reference
  Join(&'a JoinMessage<I>),
  /// PushPull message reference
  PushPull(PushPullMessageRef<'a, I>),
  /// UserEvent message reference
  UserEvent(&'a UserEventMessage),
  /// Query message reference
  Query(&'a QueryMessage<I, A>),
  /// QueryResponse message reference
  QueryResponse(&'a QueryResponseMessage<I, A>),
  /// ConflictResponse message reference
  ConflictResponse(&'a Member<I, A>),
  /// KeyRequest message reference
  #[cfg(feature = "encryption")]
  KeyRequest(&'a KeyRequestMessage),
  /// KeyResponse message reference
  #[cfg(feature = "encryption")]
  KeyResponse(&'a KeyResponseMessage),
}

impl<'a, I, A> Clone for SerfMessageRef<'a, I, A> {
  fn clone(&self) -> Self {
    *self
  }
}

impl<'a, I, A> Copy for SerfMessageRef<'a, I, A> {}

impl<'a, I, A> AsMessageRef<I, A> for SerfMessageRef<'a, I, A> {
  fn as_message_ref(&self) -> SerfMessageRef<I, A> {
    *self
  }
}

/// The types of gossip messages Serf will send along
/// memberlist.
#[derive(Debug, Clone)]
pub enum SerfMessage<I, A> {
  /// Leave message
  Leave(LeaveMessage<I>),
  /// Join message
  Join(JoinMessage<I>),
  /// PushPull message
  PushPull(PushPullMessage<I>),
  /// UserEvent message
  UserEvent(UserEventMessage),
  /// Query message
  Query(QueryMessage<I, A>),
  /// QueryResponse message
  QueryResponse(QueryResponseMessage<I, A>),
  /// ConflictResponse message
  ConflictResponse(Member<I, A>),
  /// Relay message
  #[cfg(feature = "encryption")]
  KeyRequest(KeyRequestMessage),
  /// KeyResponse message
  #[cfg(feature = "encryption")]
  KeyResponse(KeyResponseMessage),
}

impl<'a, I, A> From<&'a SerfMessage<I, A>> for MessageType {
  fn from(msg: &'a SerfMessage<I, A>) -> Self {
    match msg {
      SerfMessage::Leave(_) => MessageType::Leave,
      SerfMessage::Join(_) => MessageType::Join,
      SerfMessage::PushPull(_) => MessageType::PushPull,
      SerfMessage::UserEvent(_) => MessageType::UserEvent,
      SerfMessage::Query(_) => MessageType::Query,
      SerfMessage::QueryResponse(_) => MessageType::QueryResponse,
      SerfMessage::ConflictResponse(_) => MessageType::ConflictResponse,
      #[cfg(feature = "encryption")]
      SerfMessage::KeyRequest(_) => MessageType::KeyRequest,
      #[cfg(feature = "encryption")]
      SerfMessage::KeyResponse(_) => MessageType::KeyResponse,
    }
  }
}

impl<I, A> AsMessageRef<I, A> for QueryMessage<I, A> {
  fn as_message_ref(&self) -> SerfMessageRef<I, A> {
    SerfMessageRef::Query(self)
  }
}

impl<I, A> AsMessageRef<I, A> for QueryResponseMessage<I, A> {
  fn as_message_ref(&self) -> SerfMessageRef<I, A> {
    SerfMessageRef::QueryResponse(self)
  }
}

impl<I, A> AsMessageRef<I, A> for JoinMessage<I> {
  fn as_message_ref(&self) -> SerfMessageRef<I, A> {
    SerfMessageRef::Join(self)
  }
}

impl<I, A> AsMessageRef<I, A> for UserEventMessage {
  fn as_message_ref(&self) -> SerfMessageRef<I, A> {
    SerfMessageRef::UserEvent(self)
  }
}

impl<'a, I, A> AsMessageRef<I, A> for &'a QueryMessage<I, A> {
  fn as_message_ref(&self) -> SerfMessageRef<I, A> {
    SerfMessageRef::Query(self)
  }
}

impl<'a, I, A> AsMessageRef<I, A> for &'a QueryResponseMessage<I, A> {
  fn as_message_ref(&self) -> SerfMessageRef<I, A> {
    SerfMessageRef::QueryResponse(self)
  }
}

impl<'a, I, A> AsMessageRef<I, A> for &'a JoinMessage<I> {
  fn as_message_ref(&self) -> SerfMessageRef<I, A> {
    SerfMessageRef::Join(self)
  }
}

impl<'a, I, A> AsMessageRef<I, A> for PushPullMessageRef<'a, I> {
  fn as_message_ref(&self) -> SerfMessageRef<I, A> {
    SerfMessageRef::PushPull(*self)
  }
}

impl<'a, I, A> AsMessageRef<I, A> for &'a PushPullMessage<I> {
  fn as_message_ref(&self) -> SerfMessageRef<I, A> {
    SerfMessageRef::PushPull(PushPullMessageRef {
      ltime: self.ltime,
      status_ltimes: &self.status_ltimes,
      left_members: &self.left_members,
      event_ltime: self.event_ltime,
      events: &self.events,
      query_ltime: self.query_ltime,
    })
  }
}

impl<'a, I, A> AsMessageRef<I, A> for &'a UserEventMessage {
  fn as_message_ref(&self) -> SerfMessageRef<I, A> {
    SerfMessageRef::UserEvent(self)
  }
}

impl<'a, I, A> AsMessageRef<I, A> for &'a LeaveMessage<I> {
  fn as_message_ref(&self) -> SerfMessageRef<I, A> {
    SerfMessageRef::Leave(self)
  }
}

impl<'a, I, A> AsMessageRef<I, A> for &'a Member<I, A> {
  fn as_message_ref(&self) -> SerfMessageRef<I, A> {
    SerfMessageRef::ConflictResponse(self)
  }
}

impl<'a, I, A> AsMessageRef<I, A> for &'a Arc<Member<I, A>> {
  fn as_message_ref(&self) -> SerfMessageRef<I, A> {
    SerfMessageRef::ConflictResponse(self)
  }
}

#[cfg(feature = "encryption")]
impl<'a, I, A> AsMessageRef<I, A> for &'a KeyRequestMessage {
  fn as_message_ref(&self) -> SerfMessageRef<I, A> {
    SerfMessageRef::KeyRequest(self)
  }
}

#[cfg(feature = "encryption")]
impl<'a, I, A> AsMessageRef<I, A> for &'a KeyResponseMessage {
  fn as_message_ref(&self) -> SerfMessageRef<I, A> {
    SerfMessageRef::KeyResponse(self)
  }
}

impl<I, A> AsMessageRef<I, A> for SerfMessage<I, A> {
  fn as_message_ref(&self) -> SerfMessageRef<I, A> {
    match self {
      Self::Leave(l) => SerfMessageRef::Leave(l),
      Self::Join(j) => SerfMessageRef::Join(j),
      Self::PushPull(pp) => SerfMessageRef::PushPull(PushPullMessageRef {
        ltime: pp.ltime,
        status_ltimes: &pp.status_ltimes,
        left_members: &pp.left_members,
        event_ltime: pp.event_ltime,
        events: &pp.events,
        query_ltime: pp.query_ltime,
      }),
      Self::UserEvent(u) => SerfMessageRef::UserEvent(u),
      Self::Query(q) => SerfMessageRef::Query(q),
      Self::QueryResponse(q) => SerfMessageRef::QueryResponse(q),
      Self::ConflictResponse(m) => SerfMessageRef::ConflictResponse(m),
      #[cfg(feature = "encryption")]
      Self::KeyRequest(kr) => SerfMessageRef::KeyRequest(kr),
      #[cfg(feature = "encryption")]
      Self::KeyResponse(kr) => SerfMessageRef::KeyResponse(kr),
    }
  }
}

impl<'b, I, A> AsMessageRef<I, A> for &'b SerfMessage<I, A> {
  fn as_message_ref(&self) -> SerfMessageRef<I, A> {
    match self {
      SerfMessage::Leave(l) => SerfMessageRef::Leave(l),
      SerfMessage::Join(j) => SerfMessageRef::Join(j),
      SerfMessage::PushPull(pp) => SerfMessageRef::PushPull(PushPullMessageRef {
        ltime: pp.ltime,
        status_ltimes: &pp.status_ltimes,
        left_members: &pp.left_members,
        event_ltime: pp.event_ltime,
        events: &pp.events,
        query_ltime: pp.query_ltime,
      }),
      SerfMessage::UserEvent(u) => SerfMessageRef::UserEvent(u),
      SerfMessage::Query(q) => SerfMessageRef::Query(q),
      SerfMessage::QueryResponse(q) => SerfMessageRef::QueryResponse(q),
      SerfMessage::ConflictResponse(m) => SerfMessageRef::ConflictResponse(m),
      #[cfg(feature = "encryption")]
      SerfMessage::KeyRequest(kr) => SerfMessageRef::KeyRequest(kr),
      #[cfg(feature = "encryption")]
      SerfMessage::KeyResponse(kr) => SerfMessageRef::KeyResponse(kr),
    }
  }
}

impl<I, A> core::fmt::Display for SerfMessage<I, A> {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    write!(f, "{}", self.ty().as_str())
  }
}

impl<I, A> SerfMessage<I, A> {
  /// Returns the message type of this message
  #[inline]
  pub const fn ty(&self) -> MessageType {
    match self {
      Self::Leave(_) => MessageType::Leave,
      Self::Join(_) => MessageType::Join,
      Self::PushPull(_) => MessageType::PushPull,
      Self::UserEvent(_) => MessageType::UserEvent,
      Self::Query(_) => MessageType::Query,
      Self::QueryResponse(_) => MessageType::QueryResponse,
      Self::ConflictResponse(_) => MessageType::ConflictResponse,
      #[cfg(feature = "encryption")]
      Self::KeyRequest(_) => MessageType::KeyRequest,
      #[cfg(feature = "encryption")]
      Self::KeyResponse(_) => MessageType::KeyResponse,
    }
  }
}

/// Error that can occur when transforming a [`SerfMessage`] or [`SerfMessageRef`]
#[derive(thiserror::Error)]
pub enum SerfMessageTransformError<I, A>
where
  I: Transformable + core::hash::Hash + Eq,
  A: Transformable + core::hash::Hash + Eq,
{
  /// [`LeaveMessage`] transformation error
  #[error(transparent)]
  Leave(#[from] LeaveMessageTransformError<I>),
  /// [`JoinMessage`] transformation error
  #[error(transparent)]
  Join(#[from] JoinMessageTransformError<I>),
  /// [`PushPullMessage`] transformation error
  #[error(transparent)]
  PushPull(#[from] PushPullMessageTransformError<I>),
  /// [`UserEventMessage`] transformation error
  #[error(transparent)]
  UserEvent(#[from] UserEventMessageTransformError),
  /// [`QueryMessage`] transformation error
  #[error(transparent)]
  Query(#[from] QueryMessageTransformError<I, A>),
  /// [`QueryResponseMessage`] transformation error
  #[error(transparent)]
  QueryResponse(#[from] QueryResponseMessageTransformError<I, A>),
  /// [`Member`] transformation error
  #[error(transparent)]
  ConflictResponse(#[from] MemberTransformError<I, A>),
  /// [`KeyRequestMessage`] transformation error
  #[cfg(feature = "encryption")]
  #[error(transparent)]
  KeyRequest(#[from] crate::key::OptionSecretKeyTransformError),
  /// [`KeyResponseMessage`] transformation error
  #[cfg(feature = "encryption")]
  #[error(transparent)]
  KeyResponse(#[from] crate::key::KeyResponseMessageTransformError),
}

impl<I, A> core::fmt::Debug for SerfMessageTransformError<I, A>
where
  I: Transformable + core::hash::Hash + Eq,
  A: Transformable + core::hash::Hash + Eq,
{
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    write!(f, "{}", self)
  }
}

impl<'a, I, A> Encodable for SerfMessageRef<'a, I, A>
where
  I: Transformable + core::hash::Hash + Eq,
  A: Transformable + core::hash::Hash + Eq,
{
  type Error = SerfMessageTransformError<I, A>;

  #[inline]
  fn encoded_len(&self) -> usize {
    match *self {
      Self::Leave(msg) => Transformable::encoded_len(msg),
      Self::Join(msg) => Transformable::encoded_len(msg),
      Self::PushPull(msg) => Encodable::encoded_len(&msg),
      Self::UserEvent(msg) => Transformable::encoded_len(msg),
      Self::Query(msg) => Transformable::encoded_len(msg),
      Self::QueryResponse(msg) => Transformable::encoded_len(msg),
      Self::ConflictResponse(msg) => Transformable::encoded_len(msg),
      #[cfg(feature = "encryption")]
      Self::KeyRequest(msg) => Transformable::encoded_len(msg),
      #[cfg(feature = "encryption")]
      Self::KeyResponse(msg) => Transformable::encoded_len(msg),
    }
  }

  #[inline]
  fn encode(&self, dst: &mut [u8]) -> Result<usize, Self::Error> {
    match *self {
      Self::Leave(msg) => Transformable::encode(msg, dst).map_err(Into::into),
      Self::Join(msg) => Transformable::encode(msg, dst).map_err(Into::into),
      Self::PushPull(msg) => Encodable::encode(&msg, dst).map_err(Into::into),
      Self::UserEvent(msg) => Transformable::encode(msg, dst).map_err(Into::into),
      Self::Query(msg) => Transformable::encode(msg, dst).map_err(Into::into),
      Self::QueryResponse(msg) => Transformable::encode(msg, dst).map_err(Into::into),
      Self::ConflictResponse(msg) => Transformable::encode(msg, dst).map_err(Into::into),
      #[cfg(feature = "encryption")]
      Self::KeyRequest(msg) => Transformable::encode(msg, dst).map_err(Into::into),
      #[cfg(feature = "encryption")]
      Self::KeyResponse(msg) => Transformable::encode(msg, dst).map_err(Into::into),
    }
  }
}