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
//! State synchronization (catch-up) for followers that are behind the
//! leader's log.
//!
//! When a follower receives a log entry that is not an immediate successor
//! of its last local entry, it knows there is a gap. The [`StateSync`]
//! trait provides the machinery to close that gap — either by replaying
//! the missing log entries from peers ([`LogReplaySync`](super::LogReplaySync))
//! or by transferring a compact snapshot of the state.
//!
//! # Architecture
//!
//! A `StateSync` implementation is a factory for two companion types:
//!
//! - **[`StateSyncProvider`]** — a long-lived object created once per peer. It
//! runs on *every* node in the group (including the leader) and serves state
//! to sessions on lagging followers.
//! - **[`StateSyncSession`]** — a short-lived object created on a lagging
//! follower for the duration of a single catch-up episode. It drives the sync
//! protocol (requesting data from providers, applying it to the state
//! machine) and terminates once the follower's log is fully caught up.
//!
//! Both types communicate via [`StateSync::Message`]s sent through the
//! group's bond network.
//!
//! # Built-in implementation
//!
//! [`LogReplaySync`](super::LogReplaySync) works with any state machine.
//! It recovers missing entries by broadcasting an availability request to
//! all bonded peers, partitioning the needed range across responders, and
//! pulling entries in parallel batches. This is the recommended starting
//! point — switch to a custom implementation only when log replay becomes
//! too slow for your workload.
//!
//! # Custom implementations
//!
//! For high-throughput state machines where replaying every command is
//! expensive, you can implement snapshot-based sync. The general
//! approach is:
//!
//! 1. The **provider** periodically snapshots the state machine and remembers
//! the log position of the snapshot.
//! 2. When a **session** starts, it requests the latest snapshot from a
//! provider, loads it into the local state machine, and then replays only
//! the commands that arrived after the snapshot.
//!
//! The mosaik [`collections`](crate::collections) subsystem uses this
//! strategy internally.
use ;
/// Defines how a lagging follower catches up with the rest of the group.
///
/// A `StateSync` implementation is a **factory** that produces two
/// collaborating types:
///
/// | Type | Lifetime | Runs on | Purpose |
/// |------|----------|---------|---------|
/// | [`StateSyncProvider`] | Group lifetime | Every peer | Serves state to catching-up followers |
/// | [`StateSyncSession`] | Catch-up duration | Lagging follower | Drives one catch-up episode |
///
/// The runtime calls [`create_provider`](Self::create_provider) once at
/// group initialization on every peer, and
/// [`create_session`](Self::create_session) each time a follower detects
/// a gap in its log.
///
/// # Signature and group identity
///
/// Like [`StateMachine::signature`], the
/// [`signature`](Self::signature) of the sync implementation is part
/// of the [`GroupId`](super::GroupId) derivation. All group members
/// must use the same sync implementation with the same configuration,
/// otherwise they will derive different group ids and fail to bond.
///
/// # Using the built-in log replay
///
/// For most use cases [`LogReplaySync`](super::LogReplaySync) is
/// sufficient:
///
/// ```rust,ignore
/// impl StateSync for LogReplaySync<MyMachine> {
/// // All types and methods are already implemented.
/// }
///
/// // In your StateMachine impl:
/// fn state_sync(&self) -> LogReplaySync<Self> {
/// LogReplaySync::default()
/// .with_batch_size(NonZero::new(5000).unwrap())
/// }
/// ```
/// A long-lived server that runs on every peer and serves state to
/// catching-up followers.
///
/// One `StateSyncProvider` instance is created per peer via
/// [`StateSync::create_provider`] at group initialization and lives
/// for the entire group lifetime. Its responsibilities are:
///
/// - **Responding to sync requests** — when a lagging follower's
/// [`StateSyncSession`] sends a message, the provider handles it via
/// [`receive`](Self::receive).
/// - **Background work** — the optional [`poll`](Self::poll) method is called
/// on each tick of the group scheduler, letting the provider drive timeouts,
/// create snapshots, or perform other periodic work.
/// - **Log compaction hints** — via
/// [`safe_to_prune_prefix`](Self::safe_to_prune_prefix), the provider can
/// tell the runtime which log entries are safe to discard.
/// A short-lived catch-up session running on a single lagging follower.
///
/// Created by [`StateSync::create_session`] when a follower detects a
/// gap in its log, and dropped once the gap is closed. The session
/// drives the sync protocol by:
///
/// 1. Requesting missing state from [`StateSyncProvider`]s on other peers via
/// messages.
/// 2. Receiving responses and applying them to the local state machine (through
/// the [`SyncSessionContext`]).
/// 3. Buffering any new entries that arrive from the leader while the gap is
/// being filled (via [`buffer`](Self::buffer)).
/// 4. Returning `Poll::Ready(position)` from [`poll`](Self::poll) once the
/// follower is fully caught up to the returned position.
/// Shared context available to both [`StateSyncProvider`] and
/// [`StateSyncSession`] instances.
///
/// Provides access to the group's state machine, log storage, network
/// identity, and messaging primitives. All context methods are
/// determinism-safe — they expose only state that is consistent across
/// nodes.
/// Extended context for [`StateSyncSession`] instances, available only
/// on the lagging follower during catch-up.
///
/// Adds leader-awareness and the ability to fast-forward the committed
/// index after a snapshot load.
/// Extended context for [`StateSyncProvider`] instances, available on
/// all peers in all Raft roles.
///
/// Adds leader-awareness and the ability to inject commands into the
/// Raft log.
/// Marker trait for sync protocol wire messages.
///
/// Automatically implemented for any type that is `Clone +
/// Serialize + DeserializeOwned + Send + Sync + 'static`.
pub type Machine<S> = Machine;
pub type Message<S> = Message;
pub type Command<S> = Command;
pub type Session<S> = Session;
pub type Provider<S> = Provider;