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
/* 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/. */
use alloc::vec::Vec;
use core::{cmp::Ordering, fmt};

use bytes::BufMut;

/// A type capable of decoding a (associated) broadcast from a buffer
/// and deciding whether to keep disseminating it for other members
/// of the cluster (when it's new information) or to discard it (when
/// its outdated/stale).
pub trait BroadcastHandler<T> {
    /// A unique identifier for the broadcasts this handler manages
    ///
    /// It should be able to compare itself against an arbitrary number
    /// of other [`Self::Key`] instances and decide wether it
    /// replaces it or not so conflicting/stale information isn't
    /// disseminated.
    type Key: Invalidates;

    /// The error type that `receive_item` may emit. Will be wrapped
    /// by [`crate::Error::CustomBroadcast`].
    type Error: fmt::Debug + fmt::Display + Send + Sync + 'static;

    /// Decodes a [`Self::Key`] from a buffer and either discards
    /// it or tells Foca to persist and disseminate it.
    ///
    /// `Sender` is `None` when you're adding broadcast data directly,
    /// via [`crate::Foca::add_broadcast`], otherwise it will be the
    /// address of the member that sent the data. Notice that Foca
    /// doesn't track the origin of packets- if you need it you
    /// have to add it to the data you're broadcasting.
    ///
    /// When you receive a broadcast you have to decide whether it's
    /// new information that needs to be disseminated (`Ok(Some(...))`)
    /// or not (`Ok(None)`).
    ///
    /// Always yielding `Some(...)` is wrong because Foca will never
    /// know when to stop sending this information to other members.
    ///
    /// Example: Assume your custom broadcast is a simple Set-Key-Value
    /// operation. When you receive it you should check if your map
    /// contains the Key-Value pair; If it didn't, you yield
    /// `Some`, otherwise the operation is stale, so you yield `None`.
    ///
    /// The `data` parameter is the exact data provided to
    /// `crate::Foca::add_broadcast`. When Foca receives N custom
    /// broadcasts at once, this gets called N times.
    fn receive_item(
        &mut self,
        data: &[u8],
        sender: Option<&T>,
    ) -> Result<Option<Self::Key>, Self::Error>;

    /// Decides whether Foca should add broadcast data to the message
    /// it's about to send to active member `T`.
    ///
    /// Normally when Foca sends a message it always tries to include
    /// custom broadcasts alongside the information it actually
    /// cares about; This allows implementations to override this
    /// logic with something else.
    ///
    /// Example: You are running a heterogeneous cluster and some nodes
    /// are always very busy and you'd rather they never have to deal
    /// with the extra cpu/bandwidth cost of receiving/sending
    /// your custom broadcasts.
    ///
    /// Returning `true` tells Foca to proceed as it would normally,
    /// including broadcasts in the messages it sends when it can.
    ///
    /// Returning `false` tells Foca to not include such broadcasts
    /// in the message. It does *not* prevent the message from being
    /// sent, just keeps Foca from attaching extra data to them.
    fn should_add_broadcast_data(&self, _member: &T) -> bool {
        true
    }
}

/// A type that's able to look at another and decide wether it's
/// newer/fresher (i.e. invalidates) than it.
///
/// As you send/receive broadcasts, Foca will hold them for a while
/// as it disseminates the data to other cluster members. This trait
/// helps with replacing data that hasn't been fully disseminated
/// yet but you already know it's stale.
///
/// Example: Assume a versioned broadcast like `{key,version,...}`;
/// After you receive `{K, 0, ...}` and keep it, Foca will be
/// disseminating it. Soon after you receive `{K, 1, ...}` which
/// is a newer version for this broadcast. This trait enables
/// Foca to immediately stop disseminating the previous version,
/// even if it hasn't sent it to everyone it can yet.
pub trait Invalidates {
    /// When `item.invalidates(&other)` it means that Foca will
    /// keep `item` and discard `other` from its dissemination
    /// backlog.
    fn invalidates(&self, other: &Self) -> bool;
}

impl<'a> Invalidates for &'a [u8] {
    fn invalidates(&self, other: &Self) -> bool {
        self.eq(other)
    }
}

#[allow(dead_code)]
pub(crate) struct Broadcasts<V> {
    flip: alloc::collections::BinaryHeap<Entry<V>>,
    flop: alloc::collections::BinaryHeap<Entry<V>>,
}

impl<T> Broadcasts<T>
where
    T: Invalidates,
{
    pub(crate) fn new() -> Self {
        Self {
            flip: Default::default(),
            flop: Default::default(),
        }
    }

    pub(crate) fn len(&self) -> usize {
        self.flip.len()
    }

    pub(crate) fn is_empty(&self) -> bool {
        self.flip.is_empty()
    }

    pub(crate) fn add_or_replace(&mut self, item: T, data: Vec<u8>, max_tx: usize) {
        debug_assert!(max_tx > 0);
        self.flip.retain(|node| !item.invalidates(&node.item));
        self.flip.push(Entry {
            remaining_tx: max_tx,
            item,
            data,
        });
    }

    pub(crate) fn fill(&mut self, mut buffer: impl BufMut, max_items: usize) -> usize {
        if self.flip.is_empty() {
            return 0;
        }
        debug_assert!(self.flop.is_empty());

        let mut num_taken = 0;
        let mut remaining = max_items;

        while buffer.has_remaining_mut() && remaining > 0 {
            let Some(mut node) = self.flip.pop() else {
                break;
            };
            debug_assert!(node.remaining_tx > 0);

            if buffer.remaining_mut() >= node.data.len() {
                num_taken += 1;
                remaining -= 1;

                buffer.put_slice(&node.data);
                node.remaining_tx -= 1;
            }

            if node.remaining_tx > 0 {
                self.flop.push(node);
            }
        }

        self.flip.append(&mut self.flop);

        num_taken
    }

    pub(crate) fn fill_with_len_prefix(
        &mut self,
        mut buffer: impl BufMut,
        max_items: usize,
    ) -> usize {
        if self.flip.is_empty() {
            return 0;
        }
        debug_assert!(self.flop.is_empty());

        let mut num_taken = 0;
        let mut remaining = max_items;

        while buffer.has_remaining_mut() && remaining > 0 {
            let Some(mut node) = self.flip.pop() else {
                break;
            };
            debug_assert!(node.remaining_tx > 0);

            if buffer.remaining_mut() >= node.data.len() + 2 {
                num_taken += 1;
                remaining -= 1;

                debug_assert!(node.data.len() <= core::u16::MAX as usize);
                buffer.put_u16(node.data.len() as u16);
                buffer.put_slice(&node.data);
                node.remaining_tx -= 1;
            }

            if node.remaining_tx > 0 {
                self.flop.push(node);
            }
        }

        self.flip.append(&mut self.flop);

        num_taken
    }
}

#[derive(Debug, Clone)]
struct Entry<T> {
    remaining_tx: usize,
    // XXX could be Bytes, or keep a pool in parent
    data: Vec<u8>,
    // ignored for eq/ord. sorting is unstable
    item: T,
}

impl<T> PartialEq for Entry<T> {
    fn eq(&self, other: &Self) -> bool {
        self.cmp(other).is_eq()
    }
}

impl<T> Eq for Entry<T> {}

impl<T> PartialOrd for Entry<T> {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl<T> Ord for Entry<T> {
    fn cmp(&self, other: &Self) -> Ordering {
        self.remaining_tx
            .cmp(&other.remaining_tx)
            .then_with(|| self.data.len().cmp(&other.data.len()))
    }
}

#[cfg(test)]
mod tests {

    use super::*;

    struct Key(&'static str);

    impl Invalidates for Key {
        fn invalidates(&self, other: &Self) -> bool {
            self.0 == other.0
        }
    }

    #[test]
    fn piggyback_behaviour() {
        let max_tx = 5;
        let mut piggyback = Broadcasts::new();

        assert!(piggyback.is_empty(), "Piggyback starts empty");

        piggyback.add_or_replace(Key("AA"), b"AAabc".to_vec(), max_tx);

        assert_eq!(1, piggyback.len());

        piggyback.add_or_replace(Key("AA"), b"AAcba".to_vec(), max_tx);

        assert_eq!(
            1,
            piggyback.len(),
            "add_or_replace with same key should replace"
        );

        let mut buf = Vec::new();

        for _i in 0..max_tx {
            buf.clear();
            let num_items = piggyback.fill(&mut buf, usize::MAX);
            assert_eq!(1, num_items);
            assert_eq!(
                b"AAcba",
                &buf[..],
                "Should transmit an item at most max_tx times"
            );
        }

        assert!(
            piggyback.is_empty(),
            "Should remove item after being used max_tx times"
        );
    }

    #[test]
    fn fill_does_nothing_if_buffer_full() {
        let mut piggyback = Broadcasts::new();
        piggyback.add_or_replace(Key("a "), b"a super long value".to_vec(), 1);

        let buf = bytes::BytesMut::new();
        let mut limited = buf.limit(5);

        let num_items = piggyback.fill(&mut limited, usize::MAX);

        assert_eq!(0, num_items);
        assert_eq!(5, limited.remaining_mut());
        assert_eq!(1, piggyback.len());
    }

    #[test]
    fn piggyback_consumes_largest_first() {
        let max_tx = 10;
        let mut piggyback = Broadcasts::new();

        piggyback.add_or_replace(Key("00"), b"00hi".to_vec(), max_tx);
        piggyback.add_or_replace(Key("01"), b"01hello".to_vec(), max_tx);
        piggyback.add_or_replace(Key("02"), b"02hey".to_vec(), max_tx);

        let mut buf = Vec::new();
        let num_items = piggyback.fill(&mut buf, usize::MAX);

        assert_eq!(3, num_items);
        assert_eq!(b"01hello02hey00hi", &buf[..]);
    }

    #[test]
    fn highest_max_tx_is_consumed_first() {
        let mut piggyback = Broadcasts::new();

        // 3 items, same byte size, distinct max_tx
        piggyback.add_or_replace(Key("10"), b"100".to_vec(), 1);
        piggyback.add_or_replace(Key("20"), b"200".to_vec(), 2);
        piggyback.add_or_replace(Key("30"), b"300".to_vec(), 3);

        let mut buf = Vec::new();
        piggyback.fill(&mut buf, usize::MAX);
        assert_eq!(b"300200100", &buf[..]);

        buf.clear();
        piggyback.fill(&mut buf, usize::MAX);
        assert_eq!(b"300200", &buf[..]);

        buf.clear();
        piggyback.fill(&mut buf, usize::MAX);
        assert_eq!(b"300", &buf[..]);

        assert_eq!(0, piggyback.len());
    }

    #[test]
    fn piggyback_respects_limit() {
        let max_tx = 10;
        let mut piggyback = Broadcasts::new();

        piggyback.add_or_replace(Key("fo"), b"foo".to_vec(), max_tx);
        piggyback.add_or_replace(Key("ba"), b"bar".to_vec(), max_tx);
        piggyback.add_or_replace(Key("ba"), b"baz".to_vec(), max_tx);

        let mut buf = Vec::new();
        let num_items = piggyback.fill(&mut buf, 0);

        assert_eq!(0, num_items);
        assert!(buf.is_empty());

        let num_items = piggyback.fill(&mut buf, 2);
        assert_eq!(2, num_items);
    }

    #[test]
    fn fill_with_len_prefix() {
        let mut bcs = Broadcasts::new();

        bcs.add_or_replace(Key("fo"), b"foo".to_vec(), 10);
        bcs.add_or_replace(Key("ba"), b"barr".to_vec(), 10);
        bcs.add_or_replace(Key("ba"), b"bazz".to_vec(), 10);

        let mut buf = Vec::new();
        let num_items = bcs.fill_with_len_prefix(&mut buf, 0);

        assert_eq!(0, num_items);
        assert!(buf.is_empty());

        let num_items = bcs.fill_with_len_prefix(&mut buf, 2);
        assert_eq!(2, num_items);

        use bytes::Buf;
        let mut buf = &buf[..];
        assert_eq!(4, buf.get_u16());
        assert_eq!(&b"bazz"[..], &buf[..4]);
        buf.advance(4);
        assert_eq!(3, buf.get_u16());
        assert_eq!(&b"foo"[..], &buf[..3]);
        buf.advance(3);
        assert!(buf.is_empty());
    }
}