-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathRaftMemberData.scala
600 lines (518 loc) · 23.4 KB
/
RaftMemberData.scala
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
package lerna.akka.entityreplication.raft
import lerna.akka.entityreplication.ClusterReplicationSerializable
import lerna.akka.entityreplication.model.NormalizedEntityId
import lerna.akka.entityreplication.raft.model._
import lerna.akka.entityreplication.raft.routing.MemberIndex
import lerna.akka.entityreplication.raft.snapshot.SnapshotProtocol.EntitySnapshotMetadata
private[entityreplication] object PersistentStateData {
final case class PersistentState(
currentTerm: Term,
votedFor: Option[MemberIndex],
replicatedLog: ReplicatedLog,
lastSnapshotStatus: SnapshotStatus,
) extends ClusterReplicationSerializable
}
private[entityreplication] trait PersistentStateData[T <: PersistentStateData[T]] {
import PersistentStateData._
def currentTerm: Term
def votedFor: Option[MemberIndex]
def replicatedLog: ReplicatedLog
def lastSnapshotStatus: SnapshotStatus
protected def updatePersistentState(
currentTerm: Term = currentTerm,
votedFor: Option[MemberIndex] = votedFor,
replicatedLog: ReplicatedLog = replicatedLog,
lastSnapshotStatus: SnapshotStatus = lastSnapshotStatus,
): T
def persistentState: PersistentState =
PersistentState(currentTerm, votedFor, replicatedLog, lastSnapshotStatus)
}
private[entityreplication] trait VolatileStateData[T <: VolatileStateData[T]] {
def commitIndex: LogEntryIndex
def lastApplied: LogEntryIndex
def snapshottingProgress: SnapshottingProgress
/** Indicates that [[eventsourced.CommitLogStoreActor]] has already persisted events with indices
* lower than or equal to that index
*
* Note that `None` is '''NOT''' the same as `Some(LogEntryIndex(0))`.
* `None` indicates that a Raft actor doesn't know such an index.
* `Some(LogEntryIndex(0))` indicates that a Raft actor know that such an index is zero.
*
* [[eventSourcingIndex]] may be larger than [[commitIndex]] since the leader election and the event sourcing works
* independently. This case happens if there is no leader (due to a split vote) until a follower update its [[eventSourcingIndex]]
* at SnapshotTick.
*/
def eventSourcingIndex: Option[LogEntryIndex]
protected def updateVolatileState(
commitIndex: LogEntryIndex = commitIndex,
lastApplied: LogEntryIndex = lastApplied,
snapshottingProgress: SnapshottingProgress = snapshottingProgress,
eventSourcingIndex: Option[LogEntryIndex] = eventSourcingIndex,
): T
/** Returns new [[RaftMemberData]] those [[eventSourcingIndex]] updated to the given index
*
* [[eventSourcingIndex]] should only increase.
* If the given index is lower than the current [[eventSourcingIndex]], throws an [[IllegalArgumentException]].
* This method always success if the current [[eventSourcingIndex]] is [[None]].
*/
def updateEventSourcingIndex(newEventSourcingIndex: LogEntryIndex): T = {
eventSourcingIndex.foreach { currentEventSourcingIndex =>
require(
currentEventSourcingIndex < newEventSourcingIndex,
"eventSourcingIndex should only increase. " +
s"The given index [${newEventSourcingIndex.underlying}] is less than or equal to the current index [${currentEventSourcingIndex.underlying}].",
)
}
updateVolatileState(eventSourcingIndex = Option(newEventSourcingIndex))
}
}
private[entityreplication] trait FollowerData { self: RaftMemberData =>
def leaderMember: Option[MemberIndex]
def initializeFollowerData(): RaftMemberData = {
this
}
def syncTerm(term: Term): RaftMemberData = {
require(term >= currentTerm, s"should be term:$term >= currentTerm:$currentTerm")
if (term == currentTerm) {
updatePersistentState(currentTerm = term)
} else {
updatePersistentState(currentTerm = term, votedFor = None)
}
}
def vote(candidate: MemberIndex, term: Term): RaftMemberData = {
require(
!(term < currentTerm),
s"term:$term should be greater than or equal to currentTerm:$currentTerm",
)
updatePersistentState(currentTerm = term, votedFor = Some(candidate))
}
def appendEntries(logEntries: Seq[LogEntry], prevLogIndex: LogEntryIndex): RaftMemberData = {
updatePersistentState(
replicatedLog = replicatedLog.merge(logEntries, prevLogIndex),
)
}
def detectLeaderMember(leaderMember: MemberIndex): RaftMemberData = {
updateFollowerVolatileState(leaderMember = Some(leaderMember))
}
def followLeaderCommit(leaderCommit: LogEntryIndex): RaftMemberData = {
if (leaderCommit >= commitIndex) {
import LogEntryIndex.min
val newCommitIndex = replicatedLog.lastIndexOption
.map { lastIndex =>
if (leaderCommit > commitIndex) min(leaderCommit, lastIndex) else commitIndex
}.getOrElse(commitIndex)
updateVolatileState(commitIndex = newCommitIndex)
} else {
// If a new leader is elected even if the leader is alive,
// leaderCommit is less than commitIndex when the old leader didn't tell the follower the new commitIndex.
// Do not back commitIndex because there is a risk of applying the event to Entity in duplicate.
this
}
}
protected def updateFollowerVolatileState(leaderMember: Option[MemberIndex] = leaderMember): RaftMemberData
}
private[entityreplication] trait CandidateData { self: RaftMemberData =>
def acceptedMembers: Set[MemberIndex]
def initializeCandidateData(): RaftMemberData = {
updateFollowerVolatileState(
leaderMember = None,
).updateCandidateVolatileState(
acceptedMembers = Set(),
)
}
def acceptedBy(follower: MemberIndex): RaftMemberData = {
updateCandidateVolatileState(acceptedMembers = acceptedMembers + follower)
}
def gotAcceptionMajorityOf(numberOfMembers: Int): Boolean =
acceptedMembers.size >= (numberOfMembers / 2) + 1
protected def updateCandidateVolatileState(acceptedMembers: Set[MemberIndex]): RaftMemberData
}
private[entityreplication] trait LeaderData { self: RaftMemberData =>
def nextIndex: Option[NextIndex]
def matchIndex: MatchIndex
def clients: Map[LogEntryIndex, ClientContext]
private[this] def getNextIndex: NextIndex =
nextIndex.getOrElse(throw new IllegalStateException("nextIndex does not initialized"))
def initializeLeaderData(): RaftMemberData = {
updateLeaderVolatileState(
nextIndex = Some(NextIndex(replicatedLog)),
matchIndex = MatchIndex(),
)
}
def appendEvent(event: EntityEvent): RaftMemberData = {
updatePersistentState(replicatedLog = replicatedLog.append(event, currentTerm))
}
def registerClient(client: ClientContext, logEntryIndex: LogEntryIndex): RaftMemberData = {
updateLeaderVolatileState(clients = clients + (logEntryIndex -> client))
}
def nextIndexFor(follower: MemberIndex): LogEntryIndex = {
getNextIndex(follower)
}
def syncLastLogIndex(follower: MemberIndex, lastLogIndex: LogEntryIndex): RaftMemberData = {
updateLeaderVolatileState(
nextIndex = Some(getNextIndex.update(follower, lastLogIndex.next())),
matchIndex = matchIndex.update(follower, lastLogIndex),
)
}
def markSyncLogFailed(follower: MemberIndex): RaftMemberData = {
val followerNextIndex = getNextIndex(follower).prev()
updateLeaderVolatileState(nextIndex = Some(getNextIndex.update(follower, followerNextIndex)))
}
/**
* @param numberOfAllMembers
* @param maxIndex
* @return If there exists an N such that N > commitIndex, a majority of matchIndex[i] ≥ N, and log[N].term == currentTerm
* (N <= maxIndex)
* - true: N
* - false: commitIndex
*/
def findReplicatedLastLogIndex(numberOfAllMembers: Int, maxIndex: LogEntryIndex): LogEntryIndex = {
val numberOfMajorityMembers = (numberOfAllMembers / 2) + 1
replicatedLog
.sliceEntries(from = commitIndex.next(), to = maxIndex).reverse.find { entry =>
val leaderMatchIndexCount = 1
val followerMatchIndexCount = matchIndex.countMatch(_ >= entry.index)
val matchIndexCount = leaderMatchIndexCount + followerMatchIndexCount
// true: 閾値までレプリケーションできた false: まだレプリケーションできていない
entry.term == currentTerm && matchIndexCount >= numberOfMajorityMembers
}.map(_.index).getOrElse(commitIndex)
}
def commit(logEntryIndex: LogEntryIndex): RaftMemberData = {
require(logEntryIndex >= commitIndex)
updateVolatileState(commitIndex = logEntryIndex)
}
def currentTermIsCommitted: Boolean = {
val commitIndexTerm = replicatedLog.get(commitIndex).map(_.term)
commitIndexTerm.contains(currentTerm)
}
def handleCommittedLogEntriesAndClients(handler: Seq[(LogEntry, Option[ClientContext])] => Unit): RaftMemberData = {
val applicableLogEntries = selectApplicableLogEntries
handler(applicableLogEntries.map(e => (e, clients.get(e.index))))
updateVolatileState(lastApplied = applicableLogEntries.lastOption.map(_.index).getOrElse(lastApplied))
.updateLeaderVolatileState(clients = clients -- applicableLogEntries.map(_.index)) // 通知したクライアントは削除してメモリを節約
}
protected def updateLeaderVolatileState(
nextIndex: Option[NextIndex] = nextIndex,
matchIndex: MatchIndex = matchIndex,
clients: Map[LogEntryIndex, ClientContext] = clients,
): RaftMemberData
}
private[entityreplication] object ShardData {
type EntityStates = Map[NormalizedEntityId, EntityState]
sealed trait EntityState {
def isPassivating: Boolean
}
final case object NoState extends EntityState {
override def isPassivating: Boolean = false
}
final case object Passivating extends EntityState {
override def isPassivating: Boolean = true
}
}
private[entityreplication] trait ShardData { self: RaftMemberData =>
import ShardData._
def entityStates: EntityStates
def entityStateOf(entityId: NormalizedEntityId): EntityState = {
entityStates.getOrElse(entityId, NoState)
}
def passivateEntity(entityId: NormalizedEntityId): RaftMemberData =
updateShardVolatileState(
entityStates = entityStates.updated(entityId, Passivating),
)
def terminateEntity(entityId: NormalizedEntityId): RaftMemberData =
updateShardVolatileState(
entityStates = entityStates.removed(entityId),
)
protected def updateShardVolatileState(
entityStates: EntityStates = entityStates,
): RaftMemberData
}
private[entityreplication] object RaftMemberData {
import PersistentStateData._
def apply(persistentState: PersistentState): RaftMemberData = {
val PersistentState(currentTerm, votedFor, replicatedLog, snapshotStatus) = persistentState
apply(
currentTerm = currentTerm,
votedFor = votedFor,
replicatedLog = replicatedLog,
lastSnapshotStatus = snapshotStatus,
)
}
def apply(
currentTerm: Term = Term.initial(),
votedFor: Option[MemberIndex] = None,
replicatedLog: ReplicatedLog = ReplicatedLog(),
commitIndex: LogEntryIndex = LogEntryIndex.initial(),
lastApplied: LogEntryIndex = LogEntryIndex.initial(),
leaderMember: Option[MemberIndex] = None,
acceptedMembers: Set[MemberIndex] = Set(),
nextIndex: Option[NextIndex] = None,
matchIndex: MatchIndex = MatchIndex(),
clients: Map[LogEntryIndex, ClientContext] = Map(),
snapshottingProgress: SnapshottingProgress = SnapshottingProgress.empty,
lastSnapshotStatus: SnapshotStatus = SnapshotStatus.empty,
entityStates: ShardData.EntityStates = Map(),
eventSourcingIndex: Option[LogEntryIndex] = None,
) =
RaftMemberDataImpl(
currentTerm = currentTerm,
votedFor = votedFor,
replicatedLog = replicatedLog,
commitIndex = commitIndex,
lastApplied = lastApplied,
leaderMember = leaderMember,
acceptedMembers = acceptedMembers,
nextIndex = nextIndex,
matchIndex = matchIndex,
clients = clients,
snapshottingProgress = snapshottingProgress,
lastSnapshotStatus = lastSnapshotStatus,
entityStates = entityStates,
eventSourcingIndex = eventSourcingIndex,
)
/** Indicates an error reason [[RaftMemberData.resolveCommittedEntriesForEventSourcing]] returns */
sealed trait CommittedEntriesForEventSourcingResolveError
object CommittedEntriesForEventSourcingResolveError {
/** Indicates [[RaftMemberData]] doesn't have the index of entries [[eventsourced.CommitLogStoreActor]] has saved
* ([[RaftMemberData.eventSourcingIndex]] is [[None]]
*/
case object UnknownCurrentEventSourcingIndex extends CommittedEntriesForEventSourcingResolveError
/** Indicates [[RaftMemberData.replicatedLog]] doesn't contain the next entry even if there should be.
*
* The next entry should have the next eventSourcingIndex ([[RaftMemberData.eventSourcingIndex]] + one).
*/
final case class NextCommittedEntryNotFound(
nextEventSourcingIndex: LogEntryIndex,
foundFirstIndex: Option[LogEntryIndex],
) extends CommittedEntriesForEventSourcingResolveError
}
}
private[entityreplication] trait RaftMemberData
extends PersistentStateData[RaftMemberData]
with VolatileStateData[RaftMemberData]
with FollowerData
with CandidateData
with LeaderData
with ShardData {
protected def selectApplicableLogEntries: Seq[LogEntry] =
if (commitIndex > lastApplied) {
replicatedLog.sliceEntries(from = lastApplied.next(), to = commitIndex)
} else {
Seq.empty
}
def applyCommittedLogEntries(handler: Seq[LogEntry] => Unit): RaftMemberData = {
val applicableLogEntries = selectApplicableLogEntries
handler(applicableLogEntries)
updateVolatileState(lastApplied = applicableLogEntries.lastOption.map(_.index).getOrElse(lastApplied))
}
def selectEntityEntries(
entityId: NormalizedEntityId,
from: LogEntryIndex,
to: LogEntryIndex,
): Seq[LogEntry] = {
require(
to <= lastApplied,
s"Cannot select the entries (${from}-${to}) unless RaftActor have applied the entries to the entities (lastApplied: ${lastApplied})",
)
replicatedLog.sliceEntries(from, to).filter(_.event.entityId.contains(entityId))
}
def hasUncommittedLogEntryOf(entityId: NormalizedEntityId): Boolean = {
replicatedLog
.entriesAfter(index = commitIndex) // uncommitted entries
.exists(_.event.entityId.contains(entityId))
}
def alreadyVotedOthers(candidate: MemberIndex): Boolean = votedFor.exists(candidate != _)
def hasMatchLogEntry(prevLogIndex: LogEntryIndex, prevLogTerm: Term): Boolean = {
// リーダーにログが無い場合は LogEntryIndex.initial が送られてくる。
// そのケースでは AppendEntries が成功したとみなしたいので、
// prevLogIndex が LogEntryIndex.initial の場合はマッチするログが存在するとみなす
prevLogIndex == LogEntryIndex.initial() || replicatedLog.termAt(prevLogIndex).contains(prevLogTerm)
}
def willGetMatchSnapshots(prevLogIndex: LogEntryIndex, prevLogTerm: Term): Boolean = {
prevLogTerm == lastSnapshotStatus.targetSnapshotLastTerm &&
prevLogIndex == lastSnapshotStatus.targetSnapshotLastLogIndex
}
/** Returns true if [[replicatedLog]] has entries that have been already applied */
def hasAppliedLogEntries: Boolean = {
replicatedLog.sliceEntriesFromHead(lastApplied).nonEmpty
}
def resolveSnapshotTargets(): (Term, LogEntryIndex, Set[NormalizedEntityId]) = {
replicatedLog.termAt(lastApplied) match {
case Some(lastAppliedTerm) =>
val entityIds =
replicatedLog
.sliceEntries(lastSnapshotStatus.snapshotLastLogIndex.next(), lastApplied)
.flatMap(_.event.entityId.toSeq)
.toSet
(lastAppliedTerm, lastApplied, entityIds)
case None =>
// This exception is not thrown unless there is a bug
throw new IllegalStateException(s"Term not found at lastApplied: $lastApplied")
}
}
def startSnapshotting(
term: Term,
logEntryIndex: LogEntryIndex,
entityIds: Set[NormalizedEntityId],
): RaftMemberData = {
updateVolatileState(snapshottingProgress =
SnapshottingProgress(term, logEntryIndex, inProgressEntities = entityIds, completedEntities = Set()),
)
}
def recordSavedSnapshot(snapshotMetadata: EntitySnapshotMetadata): RaftMemberData = {
if (
snapshottingProgress.isInProgress && snapshottingProgress.snapshotLastLogIndex == snapshotMetadata.logEntryIndex
) {
val newProgress =
snapshottingProgress.recordSnapshottingComplete(snapshotMetadata.logEntryIndex, snapshotMetadata.entityId)
updateVolatileState(snapshottingProgress = newProgress)
} else {
this
}
}
def updateLastSnapshotStatus(snapshotLastTerm: Term, snapshotLastIndex: LogEntryIndex): RaftMemberData = {
updatePersistentState(lastSnapshotStatus =
lastSnapshotStatus.updateSnapshotsCompletely(snapshotLastTerm, snapshotLastIndex),
)
}
/** Returns the estimated size of [[replicatedLog]] after compaction completes.
*
* This estimated size is helpful to decide whether the compaction executes or not.
* Note that this value is '''estimation''' since values for the calculation can change during compaction.
*
* Throws an [[IllegalArgumentException]] if the given `preserveLogSize` is less than or equals to 0.
*/
def estimatedReplicatedLogSizeAfterCompaction(preserveLogSize: Int): Int = {
require(preserveLogSize > 0, s"preserveLogSize($preserveLogSize) should be greater than 0.")
val toIndex = LogEntryIndex.min(
lastApplied,
eventSourcingIndex.getOrElse(LogEntryIndex(0)),
)
replicatedLog.deleteOldEntries(toIndex, preserveLogSize).entries.size
}
/** Return new [[RaftMemberData]] those [[replicatedLog]] compacted (some prefix entries are deleted)
*
* While preserving that the compacted log has at least the given `preserveLogSize` entries, the compaction deletes
* entries with indices less than or equal to the minimum of index of [[lastSnapshotStatus]] and [[eventSourcingIndex]].
* If [[eventSourcingIndex]] is unknown (it is [[None]]), the compaction deletes no entries.
* The compacted log entries might be less than `preserveLogSize` if the current number of entries is already smaller than that size.
*
* Throws an [[IllegalArgumentException]] if the given `preserveLogSize` is less than or equals to 0.
*/
def compactReplicatedLog(preserveLogSize: Int): RaftMemberData = {
require(preserveLogSize > 0, s"preserveLogSize($preserveLogSize) should be greater than 0.")
val toIndex = LogEntryIndex.min(
lastSnapshotStatus.snapshotLastLogIndex,
// Use 0 as the default since this must not delete entries if eventSourcingIndex is unknown.
eventSourcingIndex.getOrElse(LogEntryIndex(0)),
)
updatePersistentState(
replicatedLog = replicatedLog.deleteOldEntries(toIndex, preserveLogSize),
)
}
def startSnapshotSync(snapshotLastLogTerm: Term, snapshotLastLogIndex: LogEntryIndex): RaftMemberData = {
updatePersistentState(
lastSnapshotStatus = lastSnapshotStatus.startSnapshotSync(snapshotLastLogTerm, snapshotLastLogIndex),
)
}
def completeSnapshotSync(snapshotLastLogTerm: Term, snapshotLastLogIndex: LogEntryIndex): RaftMemberData = {
updatePersistentState(
/**
* [[startSnapshotSync()]] updates [[SnapshotStatus.snapshotLastTerm]] and [[SnapshotStatus.snapshotLastLogIndex]]
* but we updates these value again here for backward-compatibility.
* Because the event sequence produced by v2.0.0 doesn't call [[startSnapshotSync()]].
*/
lastSnapshotStatus = lastSnapshotStatus.updateSnapshotsCompletely(snapshotLastLogTerm, snapshotLastLogIndex),
replicatedLog = replicatedLog.reset(snapshotLastLogTerm, snapshotLastLogIndex),
)
}
/** Returns a sequence of [[LogEntry]] to persist in [[eventsourced.CommitLogStoreActor]]
*
* Returns [[RaftMemberData.CommittedEntriesForEventSourcingResolveError.UnknownCurrentEventSourcingIndex]] if this
* data doesn't have the index of entries `CommitLogStoreActor` has saved ([[eventSourcingIndex]] is [[None]]).
*
* If [[eventSourcingIndex]] is less than [[commitIndex]], returning entries should not be empty, and should contain
* the entry with eventSourcingIndex plus one. Returns [[RaftMemberData.CommittedEntriesForEventSourcingResolveError.NextCommittedEntryNotFound]]
* if these conditions don't meet.
*
* Note that [[eventSourcingIndex]] may be larger than [[commitIndex]]. See [[eventSourcingIndex]].
*/
def resolveCommittedEntriesForEventSourcing
: Either[RaftMemberData.CommittedEntriesForEventSourcingResolveError, IndexedSeq[LogEntry]] = {
import RaftMemberData.CommittedEntriesForEventSourcingResolveError._
eventSourcingIndex match {
case None =>
Left(UnknownCurrentEventSourcingIndex)
case Some(currentEventSourcingIndex) =>
if (currentEventSourcingIndex < commitIndex) {
val nextEventSourcingIndex = currentEventSourcingIndex.next()
val availableEntries =
replicatedLog.sliceEntries(from = nextEventSourcingIndex, to = commitIndex)
val firstIndexOption = availableEntries.headOption.map(_.index)
if (firstIndexOption != Option(nextEventSourcingIndex)) {
Left(NextCommittedEntryNotFound(nextEventSourcingIndex, firstIndexOption))
} else {
Right(availableEntries.toIndexedSeq)
}
} else {
Right(IndexedSeq.empty)
}
}
}
}
private[entityreplication] final case class RaftMemberDataImpl(
currentTerm: Term,
votedFor: Option[MemberIndex],
replicatedLog: ReplicatedLog,
commitIndex: LogEntryIndex,
lastApplied: LogEntryIndex,
leaderMember: Option[MemberIndex],
acceptedMembers: Set[MemberIndex],
nextIndex: Option[NextIndex],
matchIndex: MatchIndex,
clients: Map[LogEntryIndex, ClientContext],
snapshottingProgress: SnapshottingProgress,
lastSnapshotStatus: SnapshotStatus,
entityStates: ShardData.EntityStates,
eventSourcingIndex: Option[LogEntryIndex],
) extends RaftMemberData {
override protected def updatePersistentState(
currentTerm: Term,
votedFor: Option[MemberIndex],
replicatedLog: ReplicatedLog,
lastSnapshotStatus: SnapshotStatus,
): RaftMemberData =
copy(
currentTerm = currentTerm,
votedFor = votedFor,
replicatedLog = replicatedLog,
lastSnapshotStatus = lastSnapshotStatus,
)
override protected def updateVolatileState(
commitIndex: LogEntryIndex,
lastApplied: LogEntryIndex,
snapshottingProgress: SnapshottingProgress,
eventSourcingIndex: Option[LogEntryIndex],
): RaftMemberData =
copy(
commitIndex = commitIndex,
votedFor = votedFor,
lastApplied = lastApplied,
snapshottingProgress = snapshottingProgress,
eventSourcingIndex = eventSourcingIndex,
)
override protected def updateFollowerVolatileState(leaderMember: Option[MemberIndex]): RaftMemberData =
copy(leaderMember = leaderMember)
override protected def updateCandidateVolatileState(acceptedMembers: Set[MemberIndex]): RaftMemberData =
copy(acceptedMembers = acceptedMembers)
override protected def updateLeaderVolatileState(
nextIndex: Option[NextIndex],
matchIndex: MatchIndex,
clients: Map[LogEntryIndex, ClientContext],
): RaftMemberData =
copy(nextIndex = nextIndex, matchIndex = matchIndex, clients = clients)
override protected def updateShardVolatileState(
entityStates: ShardData.EntityStates,
): RaftMemberData =
copy(entityStates = entityStates)
}