/
lib.rs
3229 lines (2788 loc) · 112 KB
/
lib.rs
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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! Foca is a building block for your gossip-based cluster discovery. It's
//! a small library-first crate that implements the SWIM protocol along
//! with its useful extensions (`SWIM+Inf.+Susp.`).
//!
//! * It's a `no_std` + `alloc` crate by default. There's an optional
//! `std` feature that simply brings compatibility with some types
//! and the `std::error::Error` trait
//!
//! * Bring Your Own Everything: Foca doesn't care about anything that
//! isn't part of the cluster membership functionality:
//!
//! * Pluggable, renewable identities: Using a fixed port number?
//! No need to send it all the time. Want to attach extra crucial
//! information (shard id, deployment version, etc)? Easy.
//! Always have a lookup table mapping `u16` to hostnames? Use
//! that instead of a socket address! Bring your own type,
//! implement [`Identity`] and enjoy.
//!
//! * Write your own wire format by implementing [`Codec`]; Like
//! serde? There is `bincode-codec` and `postcard-codec` features,
//! or just use the `serde` feature and pick your favorite format.
//!
//! * Use any transport you want, it's up to you how messages
//! reach each member: Foca will tell you "Send these bytes to
//! member M", how that happens is not its business.
//!
//! * Custom Broadcasts: Foca can attach arbitrary data to its messages
//! and disseminate them the same way it distributes cluster updates.
//! Send CRDT operations, take a stab at implementing metadata-heavy
//! service discovery system, anything really. Give it something
//! that implements [`BroadcastHandler`] and Foca will ship it.
//!
//! * No runtime crashes: Apart from `alloc`-related aborts, Foca should
//! only crash inside something you provided: a [`Codec`], [`Runtime`]
//! or a [`BroadcastHandler`]- so long as those are solid, Foca is too.
//!
//! * Doesn't force you to choose between `sync` and `async`. It's as
//! easy to plug it in an evented runtime as it is to go old-school.
//!
#![forbid(unsafe_code)]
#![no_std]
#![deny(missing_docs)]
#![deny(rustdoc::broken_intra_doc_links)]
extern crate alloc;
use alloc::vec::Vec;
#[cfg(feature = "std")]
extern crate std;
use core::{cmp::Ordering, convert::TryFrom, fmt, mem};
use bytes::{Buf, BufMut, Bytes, BytesMut};
use rand::Rng;
mod broadcast;
mod codec;
mod config;
mod error;
mod identity;
mod member;
mod payload;
mod probe;
mod runtime;
#[cfg(test)]
mod testing;
use crate::{
broadcast::Broadcasts,
member::{ApplySummary, Members},
probe::Probe,
};
pub use crate::{
broadcast::{BroadcastHandler, Invalidates},
codec::Codec,
config::Config,
error::Error,
identity::Identity,
member::{Incarnation, Member, State},
payload::{Header, Message, ProbeNumber},
runtime::{Notification, Runtime, Timer, TimerToken},
};
#[cfg(feature = "postcard-codec")]
pub use crate::codec::postcard_impl::PostcardCodec;
#[cfg(feature = "bincode-codec")]
pub use crate::codec::bincode_impl::BincodeCodec;
type Result<T> = core::result::Result<T, Error>;
/// Foca is the main interaction point of this crate.
///
/// It manages the cluster members and executes the SWIM protocol. It's
/// intended as a low-level guts-exposed safe view into the protocol
/// allowing any kind of Identity and transport to be used.
///
/// Most interactions with Foca require the caller to provide a
/// [`Runtime`] type, which is simply a way to turn the result of an
/// operation inside out (think callbacks, or an out parameter like
/// `void* out`). This allows Foca to avoid deciding anything related
/// to how it interacts with the operating system.
pub struct Foca<T, C, RNG, B: BroadcastHandler<T>> {
identity: T,
codec: C,
rng: RNG,
incarnation: Incarnation,
config: Config,
connection_state: ConnectionState,
timer_token: TimerToken,
members: Members<T>,
probe: Probe<T>,
// Used to buffer up members/updates when receiving and
// sending data
member_buf: Vec<Member<T>>,
// Since we emit data via `Runtime::send_to`, this could
// easily be a Vec, but `BytesMut::limit` is quite handy
send_buf: BytesMut,
// Holds (serialized) cluster updates, which may live for a
// while until they get disseminated `Config::max_transmissions`
// times or replaced by fresher updates.
updates_buf: BytesMut,
updates: Broadcasts<ClusterUpdate<T>>,
broadcast_handler: B,
custom_broadcasts: Broadcasts<B::Broadcast>,
}
impl<T, C, RNG> Foca<T, C, RNG, NoCustomBroadcast>
where
T: Identity,
C: Codec<T>,
RNG: Rng,
{
/// Create a new Foca instance with custom broadcasts disabled.
///
/// This is a simple shortcut for [`Foca::with_custom_broadcast`]
/// using the [`NoCustomBroadcast`] type to deny any form of custom
/// broadcast.
pub fn new(identity: T, config: Config, rng: RNG, codec: C) -> Self {
Self::with_custom_broadcast(identity, config, rng, codec, NoCustomBroadcast)
}
}
#[cfg(feature = "tracing")]
impl<T: Identity, C, RNG, B: BroadcastHandler<T>> fmt::Debug for Foca<T, C, RNG, B> {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
// Assuming that when tracing comes into play the cluster is actually
// uniform. Meaning: everything is configured the same, including
// codec and broadcast handler.
// So the actually interesting thing is the identity.
formatter.debug_tuple("Foca").field(&self.identity).finish()
}
}
// XXX Does it make sense to have different associated type restrictions
// based on a feature flag? Say: when using `std` we would enforce
// that `Codec::Error` and `BroadcastHandler::Error` both implement
// `std::error::Error`, thus instead of wrapping these errors via
// `anyhow::Error::msg` we can use `anyhow::Error::new`.
impl<T, C, RNG, B> Foca<T, C, RNG, B>
where
T: Identity,
C: Codec<T>,
RNG: Rng,
B: BroadcastHandler<T>,
{
/// Initialize a new Foca instance.
pub fn with_custom_broadcast(
identity: T,
config: Config,
rng: RNG,
codec: C,
broadcast_handler: B,
) -> Self {
let max_indirect_probes = config.num_indirect_probes.get();
let max_bytes = config.max_packet_size.get();
Self {
identity,
config,
rng,
codec,
incarnation: Incarnation::default(),
timer_token: TimerToken::default(),
members: Members::new(Vec::new()),
probe: Probe::new(Vec::with_capacity(max_indirect_probes)),
member_buf: Vec::new(),
connection_state: ConnectionState::Disconnected,
updates: Broadcasts::new(),
send_buf: BytesMut::with_capacity(max_bytes),
custom_broadcasts: Broadcasts::new(),
updates_buf: BytesMut::new(),
broadcast_handler,
}
}
/// Getter for the current identity.
pub fn identity(&self) -> &T {
&self.identity
}
/// Re-enable joining a cluster with the same identity after being
/// declared Down.
///
/// This is intended to be use by implementations that decide not to
/// opt-in on auto-rejoining: once Foca detects its Down you'll
/// only be able to receive messages (which will likely stop after
/// a short while since the cluster things you are down).
///
/// Whatever is controlling the running Foca will then have to wait
/// for at least [`Config::remove_down_after`] before attempting a
/// rejoin. Then you can call this method followed by a
/// [`Foca::announce(T)`] to go back to the cluster.
#[cfg_attr(feature = "tracing", tracing::instrument)]
pub fn reuse_down_identity(&mut self) -> Result<()> {
if self.connection_state != ConnectionState::Undead {
Err(Error::NotUndead)
} else {
self.reset();
Ok(())
}
}
/// Change the current identity.
///
/// Foca will declare its previous identity as Down and immediatelly
/// notify the cluster about the changes.
///
/// Notice that changing your identity does not guarantee a
/// successful (re)join. After changing it and disseminating the updates
/// Foca will only know it's actually accepted after receiving a
/// message addressed to it.
///
/// Watch for [`Notification::Active`] if you want more confidence about
/// a successful (re)join.
///
/// Intended to be used when identities carry metadata that occasionally
/// changes.
#[cfg_attr(feature = "tracing", tracing::instrument(skip(runtime)))]
pub fn change_identity(&mut self, new_id: T, runtime: impl Runtime<T>) -> Result<()> {
if self.identity == new_id {
Err(Error::SameIdentity)
} else {
let previous_is_down = self.connection_state == ConnectionState::Undead;
let previous_id = mem::replace(&mut self.identity, new_id);
self.reset();
// If our previous identity wasn't known as Down already,
// we'll declare it ourselves
if !previous_is_down {
let data = self.serialize_member(Member::down(previous_id.clone()))?;
self.updates.add_or_replace(
ClusterUpdate {
member_id: previous_id,
data,
},
self.config.max_transmissions.get().into(),
);
}
self.gossip(runtime)?;
Ok(())
}
}
/// Iterate over the currently active cluster members.
pub fn iter_members(&self) -> impl Iterator<Item = &T> {
self.members.iter_active().map(|member| member.id())
}
/// Returns the number of active members in the cluster.
///
/// May only be used as a bound for [`Foca::iter_members`] if no
/// Foca method that takes `&mut self` is called in-between.
pub fn num_members(&self) -> usize {
self.members.num_active()
}
/// Applies cluster updates to this foca instance.
///
/// This is for advanced usage. It's intended as a way to unlock
/// more elaborate synchronization protocols: implementations may
/// choose to unify their cluster knowledge (say: a streaming
/// join protocol or a periodic sync) and use [`Foca::apply_many`]
/// as a way to feed Foca this new (external) knowledge.
pub fn apply_many(
&mut self,
updates: impl Iterator<Item = Member<T>>,
mut runtime: impl Runtime<T>,
) -> Result<()> {
for update in updates {
if update.id() == &self.identity {
self.handle_self_update(update.incarnation(), update.state(), &mut runtime)?;
} else {
self.apply_update(update, &mut runtime)?;
}
}
self.adjust_connection_state(runtime);
Ok(())
}
fn adjust_connection_state(&mut self, runtime: impl Runtime<T>) {
match self.connection_state {
ConnectionState::Disconnected => {
if self.members.num_active() > 0 {
self.become_connected(runtime);
}
}
ConnectionState::Connected => {
if self.members.num_active() == 0 {
self.become_disconnected(runtime);
}
}
ConnectionState::Undead => {
// We're undead. The only ways to recover are via
// an id change or reuse_down_identity(). Nothing else
// to do
}
}
}
/// Attempt to join the cluster `dst` belongs to.
///
/// Sends a [`Message::Announce`] to `dst`. If accepted, we'll receive
/// a [`Message::Feed`] as reply.
#[cfg_attr(feature = "tracing", tracing::instrument(skip(runtime)))]
pub fn announce(&mut self, dst: T, runtime: impl Runtime<T>) -> Result<()> {
self.send_message(dst, Message::Announce, runtime)
}
/// Disseminate updates/broadcasts to cluster members.
///
/// This instructs Foca to pick [`Config::num_indirect_probes`]
/// random active members and send a [`Message::Gossip`] containing
/// cluster updates.
///
/// Intended for more complex scenarios where an implementation wants
/// to attempt reducing the time it takes for information to
/// propagate thoroughly.
#[cfg_attr(feature = "tracing", tracing::instrument(skip(runtime)))]
pub fn gossip(&mut self, mut runtime: impl Runtime<T>) -> Result<()> {
self.member_buf.clear();
self.members.choose_active_members(
self.config.num_indirect_probes.get(),
&mut self.member_buf,
&mut self.rng,
|_| true,
);
while let Some(chosen) = self.member_buf.pop() {
self.send_message(chosen.into_identity(), Message::Gossip, &mut runtime)?;
}
Ok(())
}
/// Only disseminate custom broadcasts to cluster members
///
/// This instructs Foca to pick [`Config::num_indirect_probes`]
/// random active members that *pass* the
/// [`BroadcastHandler::should_add_broadcast_data`] check. It
/// guarantees custom broadcast dissemination if there are
/// candidate members available.
///
/// No cluster update will be sent with these messages. Intended
/// to be used in tandem with a non-default
/// `should_add_broadcast_data`.
#[cfg_attr(feature = "tracing", tracing::instrument(skip(runtime)))]
pub fn broadcast(&mut self, mut runtime: impl Runtime<T>) -> Result<()> {
if self.custom_broadcast_backlog() == 0 {
// Nothing to broadcast
return Ok(());
}
self.member_buf.clear();
self.members.choose_active_members(
self.config.num_indirect_probes.get(),
&mut self.member_buf,
&mut self.rng,
|member| self.broadcast_handler.should_add_broadcast_data(member),
);
while let Some(chosen) = self.member_buf.pop() {
self.send_message(chosen.into_identity(), Message::Broadcast, &mut runtime)?;
// Crafting the message above left the backlog empty,
// no need to send more messages since they won't
// contain anything
if self.custom_broadcast_backlog() == 0 {
break;
}
}
Ok(())
}
/// Leave the cluster by declaring our own identity as down.
///
/// If there are active members, we select a few are selected
/// and notify them of our exit so that the cluster learns
/// about it quickly.
///
/// This is the cleanest way to terminate a running Foca.
#[cfg_attr(feature = "tracing", tracing::instrument(skip(runtime)))]
pub fn leave_cluster(mut self, mut runtime: impl Runtime<T>) -> Result<()> {
let data = self.serialize_member(Member::down(self.identity().clone()))?;
self.updates.add_or_replace(
ClusterUpdate {
member_id: self.identity().clone(),
data,
},
self.config.max_transmissions.get().into(),
);
self.gossip(&mut runtime)?;
// We could try to be smart here and only go defunct if there
// are active members, but I'd rather have consistent behaviour.
self.become_undead(&mut runtime);
Ok(())
}
/// Register some data to be broadcast along with Foca messages.
///
/// Calls into this instance's BroadcastHandler and reacts accordingly.
pub fn add_broadcast(&mut self, data: &[u8]) -> Result<()> {
// NOTE: Receiving B::Broadcast instead of a byte slice would make it
// look more convenient, however it gets in the way when
// implementing more ergonomic interfaces (say: an async driver)
// it forces everything to know the exact concrete type of
// the broadcast. So... maybe revisit this decision later?
#[cfg(feature = "tracing")]
let span = tracing::span!(tracing::Level::DEBUG, "add_broadcast", len = data.len(),);
#[cfg(feature = "tracing")]
let _guard = span.enter();
// Not considering the whole header
if data.len() > self.config.max_packet_size.get() {
return Err(Error::DataTooBig);
}
if let Some(broadcast) = self
.broadcast_handler
.receive_item(data)
.map_err(anyhow::Error::msg)
.map_err(Error::CustomBroadcast)?
{
#[cfg(feature = "tracing")]
tracing::debug!("new item received");
self.custom_broadcasts
.add_or_replace(broadcast, self.config.max_transmissions.get().into());
}
Ok(())
}
/// React to a previously scheduled timer event.
///
/// See [`Runtime::submit_after`].
pub fn handle_timer(&mut self, event: Timer<T>, mut runtime: impl Runtime<T>) -> Result<()> {
#[cfg(feature = "tracing")]
let span = tracing::span!(
tracing::Level::DEBUG,
"handle_timer",
self.timer_token,
?event,
);
#[cfg(feature = "tracing")]
let _guard = span.enter();
match event {
Timer::SendIndirectProbe { probed_id, token } => {
// Changing identities in the middle of the probe cycle may
// naturally lead to this.
if token != self.timer_token {
#[cfg(feature = "tracing")]
tracing::debug!("Invalid timer token");
return Ok(());
}
// Bookkeeping: This is how we verify that the probe code
// is running correctly. If we reach the end of the
// probe and this hasn't happened, we know something is
// wrong.
self.probe.mark_indirect_probe_stage_reached();
if !self.probe.is_probing(&probed_id) {
#[cfg(feature = "tracing")]
tracing::warn!("Member not being probed");
return Ok(());
}
if self.probe.succeeded() {
// We received an Ack already, nothing else to do
return Ok(());
}
self.member_buf.clear();
self.members.choose_active_members(
self.config.num_indirect_probes.get(),
&mut self.member_buf,
&mut self.rng,
|candidate| Some(candidate) != self.probe.target(),
);
#[cfg(feature = "tracing")]
tracing::debug!("Indirect Probe Cycle started");
while let Some(chosen) = self.member_buf.pop() {
let indirect = chosen.into_identity();
self.probe.expect_indirect_ack(indirect.clone());
self.send_message(
indirect,
Message::PingReq {
target: probed_id.clone(),
probe_number: self.probe.probe_number(),
},
&mut runtime,
)?;
}
Ok(())
}
Timer::ChangeSuspectToDown {
member_id,
incarnation,
token,
} => {
if self.timer_token == token {
let as_down = Member::new(member_id, incarnation, State::Down);
if let Some(summary) = self
.members
// Down is terminal, so before doing that we ensure the member
// is still under suspicion.
// Checking only incarnation is sufficient because to refute
// suspicion the member must increment its own incarnation
.apply_existing_if(as_down.clone(), |member| {
member.incarnation() == incarnation
})
{
self.handle_apply_summary(&summary, as_down, &mut runtime)?;
// Member went down we might need to adjust our internal state
self.adjust_connection_state(runtime);
} else {
#[cfg(feature = "tracing")]
tracing::debug!("Member not found");
}
}
Ok(())
}
Timer::RemoveDown(down) => {
#[cfg_attr(
not(feature = "tracing"),
allow(unused_variables, clippy::if_same_then_else)
)]
if let Some(_removed) = self.members.remove_if_down(&down) {
#[cfg(feature = "tracing")]
tracing::trace!("Member removed");
} else {
#[cfg(feature = "tracing")]
tracing::trace!("Member not found / not down");
}
Ok(())
}
Timer::ProbeRandomMember(token) => {
if token == self.timer_token {
if self.connection_state != ConnectionState::Connected {
// Not expected to happen during normal operation, but
// may reach here via manually crafted Timer::
Err(Error::NotConnected)
} else {
self.probe_random_member(runtime)
}
} else {
// Invalid token, may happen whenever we go offline after
// being online
Ok(())
}
}
}
}
/// Reports the current length of the cluster updates queue.
///
/// Updates are transmitted [`Config::max_transmissions`] times
/// at most or until we learn new information about the same
/// member.
pub fn updates_backlog(&self) -> usize {
self.updates.len()
}
/// Repports the current length of the custom broadcast queue.
///
/// Custom broadcasts are transmitted [`Config::max_transmissions`]
/// times at most or until they get invalidated by another custom
/// broadcast.
pub fn custom_broadcast_backlog(&self) -> usize {
self.custom_broadcasts.len()
}
/// Replaces the current configuration with a new one.
///
/// Most of the time a static configuration is more than enough, but
/// for use-cases where the cluster size can drastically change during
/// normal operations, changing the configuration parameters is a
/// nicer alternative to recreating the Foca instance.
///
/// Presently, attempting to change [`Config::probe_period`] or
/// [`Config::probe_rtt`] results in [`Error::InvalidConfig`]; For
/// such cases it's recommended to recreate your Foca instance. When
/// an error occurrs, every configuration parameter remains
/// unchanged.
pub fn set_config(&mut self, config: Config) -> Result<()> {
if self.config.probe_period != config.probe_period
|| self.config.probe_rtt != config.probe_rtt
{
Err(Error::InvalidConfig)
} else {
self.config = config;
Ok(())
}
}
/// Handle data received from the network.
///
/// Data larger than the configured limit will be rejected. Errors are
/// expected if you're receiving arbitrary data (which very likely if
/// you are listening to a socket address).
pub fn handle_data(&mut self, mut data: &[u8], mut runtime: impl Runtime<T>) -> Result<()> {
#[cfg(feature = "tracing")]
let span = tracing::span!(
tracing::Level::DEBUG,
"handle_data",
data_len = data.len(),
src = tracing::field::Empty,
message = tracing::field::Empty,
);
#[cfg(feature = "tracing")]
let _guard = span.enter();
if data.remaining() > self.config.max_packet_size.get() {
return Err(Error::DataTooBig);
}
let header = self
.codec
.decode_header(&mut data)
.map_err(anyhow::Error::msg)
.map_err(Error::Decode)?;
#[cfg(feature = "tracing")]
span.record("src", &tracing::field::debug(&header.src));
#[cfg(feature = "tracing")]
span.record("message", &tracing::field::debug(&header.message));
let remaining = data.remaining();
// A single trailing byte or a Announce payload with _any_
// data is bad
if remaining == 1 || (header.message == Message::Announce && remaining > 0) {
return Err(Error::MalformedPacket);
}
if !self.accept_payload(&header) {
#[cfg(feature = "tracing")]
tracing::debug!("payload rejected");
return Ok(());
}
// We can skip this buffering is we assume that reaching here
// means the packet is valid. But that doesn't seem like a very
// good idea...
self.member_buf.clear();
if remaining >= 2 && header.message != Message::Broadcast {
let num_updates = data.get_u16();
for _i in 0..num_updates {
self.member_buf.push(
self.codec
.decode_member(&mut data)
.map_err(anyhow::Error::msg)
.map_err(Error::Decode)?,
);
}
}
let Header {
src,
src_incarnation,
dst: _,
message,
} = header;
if src == self.identity {
return Err(Error::DataFromOurselves);
}
let sender_is_active = self
// It's a known member, so we ensure our knowledge about
// it is up-to-date (it is at _least_ alive, since it can
// talk)
.apply_update(
Member::new(src.clone(), src_incarnation, State::Alive),
&mut runtime,
)?;
// But dead members are ignored. At least until the member
// list gets reaped.
if !sender_is_active {
#[cfg(feature = "tracing")]
tracing::debug!("Discarded: Inactive sender");
return Ok(());
}
// Now that we know the member is active, we'll handle the
// updates, which may change our referential cluster
// representation and our own connection state.
//
// Here we take the Vec so we can drain it without upsetting
// the borrow checker. And then put it back in its place, so
// that we can keep reusing its already-allocated space.
let mut updates = mem::take(&mut self.member_buf);
self.apply_many(updates.drain(..), &mut runtime)?;
debug_assert!(
self.member_buf.is_empty(),
"member_buf modified while taken"
);
self.member_buf = updates;
// Right now there might still be some data left to read in the
// buffer (custom broadcasts).
// We choose to defer handling them until after we're done
// with the core of the protocol.
// If we're not connected (anymore), we can't react to a message
// So we just finish consuming the data
if self.connection_state != ConnectionState::Connected {
return self.handle_custom_broadcasts(data);
}
match message {
Message::Ping(probe_number) => {
self.send_message(src, Message::Ack(probe_number), runtime)?;
}
Message::Ack(probe_number) => {
#[cfg_attr(not(feature = "tracing"), allow(clippy::if_same_then_else))]
if self.probe.receive_ack(&src, probe_number) {
#[cfg(feature = "tracing")]
tracing::debug!("Probe success");
} else {
// May be triggered by a member that slows down (say, you ^Z
// the proccess and `fg` back after a while).
// Might be interesting to keep an eye on.
#[cfg(feature = "tracing")]
tracing::warn!("Ack from unexpected member");
}
}
Message::PingReq {
target,
probe_number,
} => {
if target == self.identity {
return Err(Error::IndirectForOurselves);
} else {
self.send_message(
target,
Message::IndirectPing {
origin: src,
probe_number,
},
runtime,
)?;
}
}
Message::IndirectPing {
origin,
probe_number,
} => {
if origin == self.identity {
return Err(Error::IndirectForOurselves);
} else {
self.send_message(
src,
Message::IndirectAck {
target: origin,
probe_number,
},
runtime,
)?;
}
}
Message::IndirectAck {
target,
probe_number,
} => {
if target == self.identity {
return Err(Error::IndirectForOurselves);
} else {
self.send_message(
target,
Message::ForwardedAck {
origin: src,
probe_number,
},
runtime,
)?;
}
}
Message::ForwardedAck {
origin,
probe_number,
} =>
{
#[cfg_attr(not(feature = "tracing"), allow(clippy::if_same_then_else))]
if origin == self.identity {
return Err(Error::IndirectForOurselves);
} else if self.probe.receive_indirect_ack(&src, probe_number) {
#[cfg(feature = "tracing")]
tracing::debug!("Indirect probe success");
} else {
#[cfg(feature = "tracing")]
tracing::warn!("Unexpected ForwardedAck sender");
}
}
Message::Announce => self.send_message(src, Message::Feed, runtime)?,
// Nothing to do. These messages do not expect any reply
Message::Gossip | Message::Feed | Message::Broadcast => {}
};
self.handle_custom_broadcasts(data)
}
fn serialize_member(&mut self, member: Member<T>) -> Result<Bytes> {
let mut buf = self.updates_buf.split();
self.codec
.encode_member(&member, &mut buf)
.map_err(anyhow::Error::msg)
.map_err(Error::Encode)?;
Ok(buf.freeze())
}
fn reset(&mut self) {
self.connection_state = ConnectionState::Disconnected;
self.incarnation = Incarnation::default();
self.timer_token = self.timer_token.wrapping_add(1);
self.probe.clear();
// XXX It might make sense to `self.updates.clear()` if we're
// down for a very long while, but we don't track instants
// internally... Exposing a public method to do so and
// letting drivers decide when to do it could be a way
// out. But recreating Foca is quite cheap, so revisit
// me maybe?
}
fn probe_random_member(&mut self, mut runtime: impl Runtime<T>) -> Result<()> {
debug_assert_eq!(self.connection_state, ConnectionState::Connected);
if !self.probe.validate() {
// Probe has invalid state. We'll reset and submit another timer
// so that foca can recover from the issue gracefully
self.probe.clear();
runtime.submit_after(
Timer::ProbeRandomMember(self.timer_token),
self.config.probe_period,
);
return Err(Error::IncompleteProbeCycle);
}
if let Some(failed) = self.probe.take_failed() {
// Applying here can fail if:
//
// 1. The member increased its incarnation since the probe started
// (as a side effect of someone else probing and suspecting it)
//
// 2. The member was ALREADY suspect when we picked it for probing
//
// 3. The member is now Down, either by leaving voluntarily or by
// being declared down by another cluster member
//
// 4. The member doesn't exist anymore, which shouldn't actually
// happen...?
let as_suspect = Member::new(failed.id().clone(), failed.incarnation(), State::Suspect);
if let Some(summary) = self
.members
.apply_existing_if(as_suspect.clone(), |_member| true)
{
self.handle_apply_summary(&summary, as_suspect, &mut runtime)?;
// Now we ensure we change the member to Down if it
// isn't already inactive
if summary.is_active_now {
runtime.submit_after(
Timer::ChangeSuspectToDown {
member_id: failed.id().clone(),
incarnation: failed.incarnation(),
token: self.timer_token,
},
self.config.suspect_to_down_after,
);
}
} else {
#[cfg(feature = "tracing")]
tracing::error!(
failed = ?failed.id(),
"Member failed probe but doesn't exist"
);
}
}
if let Some(member) = self.members.next(&mut self.rng) {
let member_id = member.id().clone();
let probe_number = self.probe.start(member.clone());
#[cfg(feature = "tracing")]
tracing::debug!("Probe start");
self.send_message(member_id.clone(), Message::Ping(probe_number), &mut runtime)?;
runtime.submit_after(
Timer::SendIndirectProbe {
probed_id: member_id,
token: self.timer_token,
},
self.config.probe_rtt,
);
} else {
// Should never happen... Reaching here is gated by being
// online, which requires having at least one active member
#[cfg(feature = "tracing")]
tracing::error!("Expected to find an active member to probe");
}
runtime.submit_after(
Timer::ProbeRandomMember(self.timer_token),
self.config.probe_period,
);
Ok(())
}
// shortcut for apply + handle
fn apply_update(&mut self, update: Member<T>, runtime: impl Runtime<T>) -> Result<bool> {
debug_assert_ne!(&self.identity, update.id());
let summary = self.members.apply(update.clone(), &mut self.rng);
self.handle_apply_summary(&summary, update, runtime)?;
Ok(summary.is_active_now)
}
fn handle_apply_summary(
&mut self,
summary: &ApplySummary,
update: Member<T>,
mut runtime: impl Runtime<T>,
) -> Result<()> {
let id = update.id().clone();
if summary.apply_successful {
// Cluster state changed, start broadcasting it
let data = self.serialize_member(update)?;
self.updates.add_or_replace(
ClusterUpdate {
member_id: id.clone(),
data,
},
self.config.max_transmissions.get().into(),
);
// Down is a terminal state, so set up a handler for removing
// the member so that it may rejoin later
if !summary.is_active_now {
runtime.submit_after(Timer::RemoveDown(id.clone()), self.config.remove_down_after);
}
}
if summary.changed_active_set {
if summary.is_active_now {
runtime.notify(Notification::MemberUp(id));
} else {
runtime.notify(Notification::MemberDown(id));
}
}