Remove ask-based protocol client
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / datastore / Shard.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.controller.cluster.datastore;
9
10 import static com.google.common.base.Preconditions.checkState;
11 import static com.google.common.base.Verify.verify;
12 import static com.google.common.base.Verify.verifyNotNull;
13 import static java.util.Objects.requireNonNull;
14
15 import akka.actor.ActorRef;
16 import akka.actor.ActorSelection;
17 import akka.actor.Cancellable;
18 import akka.actor.ExtendedActorSystem;
19 import akka.actor.PoisonPill;
20 import akka.actor.Props;
21 import akka.actor.Status;
22 import akka.actor.Status.Failure;
23 import akka.persistence.RecoveryCompleted;
24 import akka.persistence.SnapshotOffer;
25 import akka.serialization.JavaSerializer;
26 import akka.serialization.Serialization;
27 import com.google.common.annotations.VisibleForTesting;
28 import com.google.common.base.Ticker;
29 import com.google.common.collect.ImmutableList;
30 import com.google.common.collect.ImmutableMap;
31 import com.google.common.collect.ImmutableSet;
32 import com.google.common.collect.Range;
33 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
34 import java.io.IOException;
35 import java.util.Arrays;
36 import java.util.Collection;
37 import java.util.Collections;
38 import java.util.HashMap;
39 import java.util.Map;
40 import java.util.Optional;
41 import java.util.OptionalLong;
42 import java.util.concurrent.TimeUnit;
43 import org.eclipse.jdt.annotation.NonNull;
44 import org.eclipse.jdt.annotation.Nullable;
45 import org.opendaylight.controller.cluster.access.ABIVersion;
46 import org.opendaylight.controller.cluster.access.commands.ConnectClientRequest;
47 import org.opendaylight.controller.cluster.access.commands.ConnectClientSuccess;
48 import org.opendaylight.controller.cluster.access.commands.LocalHistoryRequest;
49 import org.opendaylight.controller.cluster.access.commands.NotLeaderException;
50 import org.opendaylight.controller.cluster.access.commands.OutOfSequenceEnvelopeException;
51 import org.opendaylight.controller.cluster.access.commands.TransactionRequest;
52 import org.opendaylight.controller.cluster.access.concepts.ClientIdentifier;
53 import org.opendaylight.controller.cluster.access.concepts.FrontendIdentifier;
54 import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
55 import org.opendaylight.controller.cluster.access.concepts.RequestEnvelope;
56 import org.opendaylight.controller.cluster.access.concepts.RequestException;
57 import org.opendaylight.controller.cluster.access.concepts.RequestSuccess;
58 import org.opendaylight.controller.cluster.access.concepts.RetiredGenerationException;
59 import org.opendaylight.controller.cluster.access.concepts.RuntimeRequestException;
60 import org.opendaylight.controller.cluster.access.concepts.SliceableMessage;
61 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
62 import org.opendaylight.controller.cluster.access.concepts.UnsupportedRequestException;
63 import org.opendaylight.controller.cluster.common.actor.CommonConfig;
64 import org.opendaylight.controller.cluster.common.actor.Dispatchers;
65 import org.opendaylight.controller.cluster.common.actor.Dispatchers.DispatcherType;
66 import org.opendaylight.controller.cluster.common.actor.MessageTracker;
67 import org.opendaylight.controller.cluster.common.actor.MeteringBehavior;
68 import org.opendaylight.controller.cluster.datastore.actors.JsonExportActor;
69 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
70 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
71 import org.opendaylight.controller.cluster.datastore.messages.AbortTransaction;
72 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
73 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
74 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransaction;
75 import org.opendaylight.controller.cluster.datastore.messages.CloseTransactionChain;
76 import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction;
77 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
78 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
79 import org.opendaylight.controller.cluster.datastore.messages.DataTreeChangedReply;
80 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
81 import org.opendaylight.controller.cluster.datastore.messages.GetKnownClients;
82 import org.opendaylight.controller.cluster.datastore.messages.GetKnownClientsReply;
83 import org.opendaylight.controller.cluster.datastore.messages.GetShardDataTree;
84 import org.opendaylight.controller.cluster.datastore.messages.MakeLeaderLocal;
85 import org.opendaylight.controller.cluster.datastore.messages.OnDemandShardState;
86 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
87 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
88 import org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeChangeListener;
89 import org.opendaylight.controller.cluster.datastore.messages.ShardLeaderStateChanged;
90 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
91 import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot;
92 import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot.ShardSnapshot;
93 import org.opendaylight.controller.cluster.datastore.persisted.DisableTrackingPayload;
94 import org.opendaylight.controller.cluster.messaging.MessageAssembler;
95 import org.opendaylight.controller.cluster.messaging.MessageSlicer;
96 import org.opendaylight.controller.cluster.messaging.SliceOptions;
97 import org.opendaylight.controller.cluster.notifications.LeaderStateChanged;
98 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
99 import org.opendaylight.controller.cluster.notifications.RoleChangeNotifier;
100 import org.opendaylight.controller.cluster.raft.LeadershipTransferFailedException;
101 import org.opendaylight.controller.cluster.raft.RaftActor;
102 import org.opendaylight.controller.cluster.raft.RaftActorRecoveryCohort;
103 import org.opendaylight.controller.cluster.raft.RaftActorSnapshotCohort;
104 import org.opendaylight.controller.cluster.raft.RaftState;
105 import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
106 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
107 import org.opendaylight.controller.cluster.raft.client.messages.OnDemandRaftState;
108 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
109 import org.opendaylight.controller.cluster.raft.messages.Payload;
110 import org.opendaylight.controller.cluster.raft.messages.RequestLeadership;
111 import org.opendaylight.controller.cluster.raft.messages.ServerRemoved;
112 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.distributed.datastore.provider.rev231229.DataStoreProperties.ExportOnRecovery;
113 import org.opendaylight.yangtools.concepts.Identifier;
114 import org.opendaylight.yangtools.yang.data.tree.api.DataTree;
115 import org.opendaylight.yangtools.yang.data.tree.api.DataValidationFailedException;
116 import org.opendaylight.yangtools.yang.data.tree.api.TreeType;
117 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
118 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContextProvider;
119 import scala.concurrent.duration.FiniteDuration;
120
121 /**
122  * A Shard represents a portion of the logical data tree.
123  *
124  * <p>
125  * Our Shard uses InMemoryDataTree as it's internal representation and delegates all requests it
126  */
127 // FIXME: non-final for testing?
128 public class Shard extends RaftActor {
129
130     @VisibleForTesting
131     static final Object TX_COMMIT_TIMEOUT_CHECK_MESSAGE = new Object() {
132         @Override
133         public String toString() {
134             return "txCommitTimeoutCheck";
135         }
136     };
137
138     @VisibleForTesting
139     static final Object GET_SHARD_MBEAN_MESSAGE = new Object() {
140         @Override
141         public String toString() {
142             return "getShardMBeanMessage";
143         }
144     };
145
146     static final Object RESUME_NEXT_PENDING_TRANSACTION = new Object() {
147         @Override
148         public String toString() {
149             return "resumeNextPendingTransaction";
150         }
151     };
152
153     // FIXME: shard names should be encapsulated in their own class and this should be exposed as a constant.
154     public static final String DEFAULT_NAME = "default";
155
156     private static final Collection<ABIVersion> SUPPORTED_ABIVERSIONS;
157
158     // Make sure to keep this in sync with the journal configuration in factory-akka.conf
159     public static final String NON_PERSISTENT_JOURNAL_ID = "akka.persistence.non-persistent.journal";
160
161     static {
162         final ABIVersion[] values = ABIVersion.values();
163         final ABIVersion[] real = Arrays.copyOfRange(values, 1, values.length - 1);
164         SUPPORTED_ABIVERSIONS = ImmutableList.copyOf(real).reverse();
165     }
166
167     // FIXME: make this a dynamic property based on mailbox size and maximum number of clients
168     private static final int CLIENT_MAX_MESSAGES = 1000;
169
170     // The state of this Shard
171     private final ShardDataTree store;
172
173     /// The name of this shard
174     private final String name;
175
176     private final String shardName;
177
178     private final ShardStats shardMBean;
179
180     private final ShardDataTreeListenerInfoMXBeanImpl listenerInfoMXBean;
181
182     private DatastoreContext datastoreContext;
183
184     private final ShardCommitCoordinator commitCoordinator;
185
186     private long transactionCommitTimeout;
187
188     private Cancellable txCommitTimeoutCheckSchedule;
189
190     private final Optional<ActorRef> roleChangeNotifier;
191
192     private final MessageTracker appendEntriesReplyTracker;
193
194     private final ShardTransactionActorFactory transactionActorFactory;
195
196     private final ShardSnapshotCohort snapshotCohort;
197
198     private final DataTreeChangeListenerSupport treeChangeSupport = new DataTreeChangeListenerSupport(this);
199
200     private ShardSnapshot restoreFromSnapshot;
201
202     private final ShardTransactionMessageRetrySupport messageRetrySupport;
203
204     @VisibleForTesting
205     final FrontendMetadata frontendMetadata;
206
207     private Map<FrontendIdentifier, LeaderFrontendState> knownFrontends = ImmutableMap.of();
208     private boolean paused;
209
210     private final MessageSlicer responseMessageSlicer;
211     private final Dispatchers dispatchers;
212
213     private final MessageAssembler requestMessageAssembler;
214
215     private final ExportOnRecovery exportOnRecovery;
216
217     private final ActorRef exportActor;
218
219     @SuppressFBWarnings(value = "MC_OVERRIDABLE_METHOD_CALL_IN_CONSTRUCTOR", justification = "Akka class design")
220     Shard(final AbstractBuilder<?, ?> builder) {
221         super(builder.getId().toString(), builder.getPeerAddresses(),
222                 Optional.of(builder.getDatastoreContext().getShardRaftConfig()), DataStoreVersions.CURRENT_VERSION);
223
224         name = builder.getId().toString();
225         shardName = builder.getId().getShardName();
226         datastoreContext = builder.getDatastoreContext();
227         restoreFromSnapshot = builder.getRestoreFromSnapshot();
228         frontendMetadata = new FrontendMetadata(name);
229         exportOnRecovery = datastoreContext.getExportOnRecovery();
230
231         exportActor = switch (exportOnRecovery) {
232             case Json -> getContext().actorOf(JsonExportActor.props(builder.getSchemaContext(),
233                 datastoreContext.getRecoveryExportBaseDir()));
234             case Off -> null;
235         };
236
237         setPersistence(datastoreContext.isPersistent());
238
239         LOG.info("Shard created : {}, persistent : {}", name, datastoreContext.isPersistent());
240
241         ShardDataTreeChangeListenerPublisherActorProxy treeChangeListenerPublisher =
242                 new ShardDataTreeChangeListenerPublisherActorProxy(getContext(), name + "-DTCL-publisher", name);
243         if (builder.getDataTree() != null) {
244             store = new ShardDataTree(this, builder.getSchemaContext(), builder.getDataTree(),
245                     treeChangeListenerPublisher, name,
246                     frontendMetadata);
247         } else {
248             store = new ShardDataTree(this, builder.getSchemaContext(), builder.getTreeType(),
249                     builder.getDatastoreContext().getStoreRoot(), treeChangeListenerPublisher, name,
250                     frontendMetadata);
251         }
252
253         shardMBean = ShardStats.create(name, datastoreContext.getDataStoreMXBeanType(), this);
254
255         if (isMetricsCaptureEnabled()) {
256             getContext().become(new MeteringBehavior(this));
257         }
258
259         commitCoordinator = new ShardCommitCoordinator(store, LOG, name);
260
261         setTransactionCommitTimeout();
262
263         // create a notifier actor for each cluster member
264         roleChangeNotifier = createRoleChangeNotifier(name);
265
266         appendEntriesReplyTracker = new MessageTracker(AppendEntriesReply.class,
267                 getRaftActorContext().getConfigParams().getIsolatedCheckIntervalInMillis());
268
269         dispatchers = new Dispatchers(context().system().dispatchers());
270         transactionActorFactory = new ShardTransactionActorFactory(store, datastoreContext,
271             dispatchers.getDispatcherPath(Dispatchers.DispatcherType.Transaction),
272                 self(), getContext(), shardMBean, builder.getId().getShardName());
273
274         snapshotCohort = ShardSnapshotCohort.create(getContext(), builder.getId().getMemberName(), store, LOG,
275             name, datastoreContext);
276
277         messageRetrySupport = new ShardTransactionMessageRetrySupport(this);
278
279         responseMessageSlicer = MessageSlicer.builder().logContext(name)
280                 .messageSliceSize(datastoreContext.getMaximumMessageSliceSize())
281                 .fileBackedStreamFactory(getRaftActorContext().getFileBackedOutputStreamFactory())
282                 .expireStateAfterInactivity(2, TimeUnit.MINUTES).build();
283
284         requestMessageAssembler = MessageAssembler.builder().logContext(name)
285                 .fileBackedStreamFactory(getRaftActorContext().getFileBackedOutputStreamFactory())
286                 .assembledMessageCallback((message, sender) -> self().tell(message, sender))
287                 .expireStateAfterInactivity(datastoreContext.getRequestTimeout(), TimeUnit.NANOSECONDS).build();
288
289         listenerInfoMXBean = new ShardDataTreeListenerInfoMXBeanImpl(name, datastoreContext.getDataStoreMXBeanType(),
290                 self());
291         listenerInfoMXBean.register();
292     }
293
294     private void setTransactionCommitTimeout() {
295         transactionCommitTimeout = TimeUnit.MILLISECONDS.convert(
296                 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS) / 2;
297     }
298
299     private Optional<ActorRef> createRoleChangeNotifier(final String shardId) {
300         ActorRef shardRoleChangeNotifier = getContext().actorOf(
301             RoleChangeNotifier.getProps(shardId), shardId + "-notifier");
302         return Optional.of(shardRoleChangeNotifier);
303     }
304
305     @Override
306     public final void postStop() throws Exception {
307         LOG.info("Stopping Shard {}", persistenceId());
308
309         super.postStop();
310
311         messageRetrySupport.close();
312
313         if (txCommitTimeoutCheckSchedule != null) {
314             txCommitTimeoutCheckSchedule.cancel();
315         }
316
317         commitCoordinator.abortPendingTransactions("Transaction aborted due to shutdown.", this);
318
319         shardMBean.unregisterMBean();
320         listenerInfoMXBean.unregister();
321     }
322
323     @Override
324     protected final void handleRecover(final Object message) {
325         LOG.debug("{}: onReceiveRecover: Received message {} from {}", persistenceId(), message.getClass(),
326             getSender());
327
328         super.handleRecover(message);
329
330         switch (exportOnRecovery) {
331             case Json:
332                 if (message instanceof SnapshotOffer) {
333                     exportActor.tell(new JsonExportActor.ExportSnapshot(store.readCurrentData().orElseThrow(), name),
334                             ActorRef.noSender());
335                 } else if (message instanceof ReplicatedLogEntry replicatedLogEntry) {
336                     exportActor.tell(new JsonExportActor.ExportJournal(replicatedLogEntry), ActorRef.noSender());
337                 } else if (message instanceof RecoveryCompleted) {
338                     exportActor.tell(new JsonExportActor.FinishExport(name), ActorRef.noSender());
339                     exportActor.tell(PoisonPill.getInstance(), ActorRef.noSender());
340                 }
341                 break;
342             case Off:
343             default:
344                 break;
345         }
346
347         if (LOG.isTraceEnabled()) {
348             appendEntriesReplyTracker.begin();
349         }
350     }
351
352     @Override
353     // non-final for TestShard
354     protected void handleNonRaftCommand(final Object message) {
355         try (var context = appendEntriesReplyTracker.received(message)) {
356             final var maybeError = context.error();
357             if (maybeError.isPresent()) {
358                 LOG.trace("{} : AppendEntriesReply failed to arrive at the expected interval {}", persistenceId(),
359                     maybeError.orElseThrow());
360             }
361
362             store.resetTransactionBatch();
363
364             if (message instanceof RequestEnvelope request) {
365                 handleRequestEnvelope(request);
366             } else if (MessageAssembler.isHandledMessage(message)) {
367                 handleRequestAssemblerMessage(message);
368             } else if (message instanceof ConnectClientRequest request) {
369                 handleConnectClient(request);
370             } else if (CreateTransaction.isSerializedType(message)) {
371                 handleCreateTransaction(message);
372             } else if (message instanceof BatchedModifications request) {
373                 handleBatchedModifications(request);
374             } else if (message instanceof ForwardedReadyTransaction request) {
375                 handleForwardedReadyTransaction(request);
376             } else if (message instanceof ReadyLocalTransaction request) {
377                 handleReadyLocalTransaction(request);
378             } else if (CanCommitTransaction.isSerializedType(message)) {
379                 handleCanCommitTransaction(CanCommitTransaction.fromSerializable(message));
380             } else if (CommitTransaction.isSerializedType(message)) {
381                 handleCommitTransaction(CommitTransaction.fromSerializable(message));
382             } else if (AbortTransaction.isSerializedType(message)) {
383                 handleAbortTransaction(AbortTransaction.fromSerializable(message));
384             } else if (CloseTransactionChain.isSerializedType(message)) {
385                 closeTransactionChain(CloseTransactionChain.fromSerializable(message));
386             } else if (message instanceof DataTreeChangedReply) {
387                 // Ignore reply
388             } else if (message instanceof RegisterDataTreeChangeListener request) {
389                 treeChangeSupport.onMessage(request, isLeader(), hasLeader());
390             } else if (message instanceof UpdateSchemaContext request) {
391                 updateSchemaContext(request);
392             } else if (message instanceof PeerAddressResolved resolved) {
393                 setPeerAddress(resolved.getPeerId(), resolved.getPeerAddress());
394             } else if (TX_COMMIT_TIMEOUT_CHECK_MESSAGE.equals(message)) {
395                 commitTimeoutCheck();
396             } else if (message instanceof DatastoreContext request) {
397                 onDatastoreContext(request);
398             } else if (message instanceof RegisterRoleChangeListener) {
399                 roleChangeNotifier.orElseThrow().forward(message, context());
400             } else if (message instanceof FollowerInitialSyncUpStatus request) {
401                 shardMBean.setFollowerInitialSyncStatus(request.isInitialSyncDone());
402                 context().parent().tell(message, self());
403             } else if (GET_SHARD_MBEAN_MESSAGE.equals(message)) {
404                 sender().tell(getShardMBean(), self());
405             } else if (message instanceof GetShardDataTree) {
406                 sender().tell(store.getDataTree(), self());
407             } else if (message instanceof ServerRemoved) {
408                 context().parent().forward(message, context());
409             } else if (ShardTransactionMessageRetrySupport.TIMER_MESSAGE_CLASS.isInstance(message)) {
410                 messageRetrySupport.onTimerMessage(message);
411             } else if (message instanceof DataTreeCohortActorRegistry.CohortRegistryCommand request) {
412                 store.processCohortRegistryCommand(getSender(), request);
413             } else if (message instanceof MakeLeaderLocal) {
414                 onMakeLeaderLocal();
415             } else if (RESUME_NEXT_PENDING_TRANSACTION.equals(message)) {
416                 store.resumeNextPendingTransaction();
417             } else if (GetKnownClients.INSTANCE.equals(message)) {
418                 handleGetKnownClients();
419             } else if (!responseMessageSlicer.handleMessage(message)) {
420                 super.handleNonRaftCommand(message);
421             }
422         }
423     }
424
425     private void handleRequestAssemblerMessage(final Object message) {
426         dispatchers.getDispatcher(DispatcherType.Serialization).execute(() -> {
427             JavaSerializer.currentSystem().value_$eq((ExtendedActorSystem) context().system());
428             requestMessageAssembler.handleMessage(message, self());
429         });
430     }
431
432     @SuppressWarnings("checkstyle:IllegalCatch")
433     private void handleRequestEnvelope(final RequestEnvelope envelope) {
434         final long now = ticker().read();
435         try {
436             final RequestSuccess<?, ?> success = handleRequest(envelope, now);
437             if (success != null) {
438                 final long executionTimeNanos = ticker().read() - now;
439                 if (success instanceof SliceableMessage) {
440                     dispatchers.getDispatcher(DispatcherType.Serialization).execute(() ->
441                         responseMessageSlicer.slice(SliceOptions.builder().identifier(success.getTarget())
442                             .message(envelope.newSuccessEnvelope(success, executionTimeNanos))
443                             .sendTo(envelope.getMessage().getReplyTo()).replyTo(self())
444                             .onFailureCallback(t -> LOG.warn("Error slicing response {}", success, t)).build()));
445                 } else {
446                     envelope.sendSuccess(success, executionTimeNanos);
447                 }
448             }
449         } catch (RequestException e) {
450             LOG.debug("{}: request {} failed", persistenceId(), envelope, e);
451             envelope.sendFailure(e, ticker().read() - now);
452         } catch (Exception e) {
453             LOG.debug("{}: request {} caused failure", persistenceId(), envelope, e);
454             envelope.sendFailure(new RuntimeRequestException("Request failed to process", e),
455                 ticker().read() - now);
456         }
457     }
458
459     private void commitTimeoutCheck() {
460         store.checkForExpiredTransactions(transactionCommitTimeout, this::updateAccess);
461         commitCoordinator.checkForExpiredTransactions(transactionCommitTimeout, this);
462         requestMessageAssembler.checkExpiredAssembledMessageState();
463     }
464
465     private OptionalLong updateAccess(final SimpleShardDataTreeCohort cohort) {
466         final FrontendIdentifier frontend = cohort.getIdentifier().getHistoryId().getClientId().getFrontendId();
467         final LeaderFrontendState state = knownFrontends.get(frontend);
468         if (state == null) {
469             // Not tell-based protocol, do nothing
470             return OptionalLong.empty();
471         }
472
473         if (isIsolatedLeader()) {
474             // We are isolated and no new request can come through until we emerge from it. We are still updating
475             // liveness of frontend when we see it attempting to communicate. Use the last access timer.
476             return OptionalLong.of(state.getLastSeenTicks());
477         }
478
479         // If this frontend has freshly connected, give it some time to catch up before killing its transactions.
480         return OptionalLong.of(state.getLastConnectTicks());
481     }
482
483     private void disableTracking(final DisableTrackingPayload payload) {
484         final ClientIdentifier clientId = payload.getIdentifier();
485         LOG.debug("{}: disabling tracking of {}", persistenceId(), clientId);
486         frontendMetadata.disableTracking(clientId);
487
488         if (isLeader()) {
489             final FrontendIdentifier frontendId = clientId.getFrontendId();
490             final LeaderFrontendState frontend = knownFrontends.get(frontendId);
491             if (frontend != null) {
492                 if (clientId.equals(frontend.getIdentifier())) {
493                     if (!(frontend instanceof LeaderFrontendState.Disabled)) {
494                         verify(knownFrontends.replace(frontendId, frontend,
495                             new LeaderFrontendState.Disabled(persistenceId(), clientId, store)));
496                         LOG.debug("{}: leader state for {} disabled", persistenceId(), clientId);
497                     } else {
498                         LOG.debug("{}: leader state {} is already disabled", persistenceId(), frontend);
499                     }
500                 } else {
501                     LOG.debug("{}: leader state {} does not match {}", persistenceId(), frontend, clientId);
502                 }
503             } else {
504                 LOG.debug("{}: leader state for {} not found", persistenceId(), clientId);
505                 knownFrontends.put(frontendId, new LeaderFrontendState.Disabled(persistenceId(), clientId,
506                     getDataStore()));
507             }
508         }
509     }
510
511     private void onMakeLeaderLocal() {
512         LOG.debug("{}: onMakeLeaderLocal received", persistenceId());
513         if (isLeader()) {
514             getSender().tell(new Status.Success(null), getSelf());
515             return;
516         }
517
518         final ActorSelection leader = getLeader();
519
520         if (leader == null) {
521             // Leader is not present. The cluster is most likely trying to
522             // elect a leader and we should let that run its normal course
523
524             // TODO we can wait for the election to complete and retry the
525             // request. We can also let the caller retry by sending a flag
526             // in the response indicating the request is "reTryable".
527             getSender().tell(new Failure(
528                     new LeadershipTransferFailedException("We cannot initiate leadership transfer to local node. "
529                             + "Currently there is no leader for " + persistenceId())),
530                     getSelf());
531             return;
532         }
533
534         leader.tell(new RequestLeadership(getId(), getSender()), getSelf());
535     }
536
537     // Acquire our frontend tracking handle and verify generation matches
538     private @Nullable LeaderFrontendState findFrontend(final ClientIdentifier clientId) throws RequestException {
539         final LeaderFrontendState existing = knownFrontends.get(clientId.getFrontendId());
540         if (existing != null) {
541             final int cmp = Long.compareUnsigned(existing.getIdentifier().getGeneration(), clientId.getGeneration());
542             if (cmp == 0) {
543                 existing.touch();
544                 return existing;
545             }
546             if (cmp > 0) {
547                 LOG.debug("{}: rejecting request from outdated client {}", persistenceId(), clientId);
548                 throw new RetiredGenerationException(clientId.getGeneration(),
549                     existing.getIdentifier().getGeneration());
550             }
551
552             LOG.info("{}: retiring state {}, outdated by request from client {}", persistenceId(), existing, clientId);
553             existing.retire();
554             knownFrontends.remove(clientId.getFrontendId());
555         } else {
556             LOG.debug("{}: client {} is not yet known", persistenceId(), clientId);
557         }
558
559         return null;
560     }
561
562     private LeaderFrontendState getFrontend(final ClientIdentifier clientId) throws RequestException {
563         final LeaderFrontendState ret = findFrontend(clientId);
564         if (ret != null) {
565             return ret;
566         }
567
568         // TODO: a dedicated exception would be better, but this is technically true, too
569         throw new OutOfSequenceEnvelopeException(0);
570     }
571
572     private static @NonNull ABIVersion selectVersion(final ConnectClientRequest message) {
573         final Range<ABIVersion> clientRange = Range.closed(message.getMinVersion(), message.getMaxVersion());
574         for (ABIVersion v : SUPPORTED_ABIVERSIONS) {
575             if (clientRange.contains(v)) {
576                 return v;
577             }
578         }
579
580         throw new IllegalArgumentException(String.format(
581             "No common version between backend versions %s and client versions %s", SUPPORTED_ABIVERSIONS,
582             clientRange));
583     }
584
585     @SuppressWarnings("checkstyle:IllegalCatch")
586     private void handleConnectClient(final ConnectClientRequest message) {
587         try {
588             final ClientIdentifier clientId = message.getTarget();
589             final LeaderFrontendState existing = findFrontend(clientId);
590             if (existing != null) {
591                 existing.touch();
592             }
593
594             if (!isLeader() || !isLeaderActive()) {
595                 LOG.info("{}: not currently leader, rejecting request {}. isLeader: {}, isLeaderActive: {},"
596                                 + "isLeadershipTransferInProgress: {}.",
597                         persistenceId(), message, isLeader(), isLeaderActive(), isLeadershipTransferInProgress());
598                 throw new NotLeaderException(getSelf());
599             }
600
601             final ABIVersion selectedVersion = selectVersion(message);
602             final LeaderFrontendState frontend;
603             if (existing == null) {
604                 frontend = new LeaderFrontendState.Enabled(persistenceId(), clientId, store);
605                 knownFrontends.put(clientId.getFrontendId(), frontend);
606                 LOG.debug("{}: created state {} for client {}", persistenceId(), frontend, clientId);
607             } else {
608                 frontend = existing;
609             }
610
611             frontend.reconnect();
612             message.getReplyTo().tell(new ConnectClientSuccess(message.getTarget(), message.getSequence(), getSelf(),
613                 ImmutableList.of(), store.getDataTree(), CLIENT_MAX_MESSAGES).toVersion(selectedVersion),
614                 ActorRef.noSender());
615         } catch (RequestException | RuntimeException e) {
616             message.getReplyTo().tell(new Failure(e), ActorRef.noSender());
617         }
618     }
619
620     private @Nullable RequestSuccess<?, ?> handleRequest(final RequestEnvelope envelope, final long now)
621             throws RequestException {
622         // We are not the leader, hence we want to fail-fast.
623         if (!isLeader() || paused || !isLeaderActive()) {
624             LOG.debug("{}: not currently active leader, rejecting request {}. isLeader: {}, isLeaderActive: {},"
625                             + "isLeadershipTransferInProgress: {}, paused: {}",
626                     persistenceId(), envelope, isLeader(), isLeaderActive(), isLeadershipTransferInProgress(), paused);
627             throw new NotLeaderException(getSelf());
628         }
629
630         final var request = envelope.getMessage();
631         if (request instanceof TransactionRequest<?> txReq) {
632             final var clientId = txReq.getTarget().getHistoryId().getClientId();
633             return getFrontend(clientId).handleTransactionRequest(txReq, envelope, now);
634         } else if (request instanceof LocalHistoryRequest<?> lhReq) {
635             final var clientId = lhReq.getTarget().getClientId();
636             return getFrontend(clientId).handleLocalHistoryRequest(lhReq, envelope, now);
637         } else {
638             LOG.warn("{}: rejecting unsupported request {}", persistenceId(), request);
639             throw new UnsupportedRequestException(request);
640         }
641     }
642
643     private void handleGetKnownClients() {
644         final ImmutableSet<ClientIdentifier> clients;
645         if (isLeader()) {
646             clients = knownFrontends.values().stream()
647                     .map(LeaderFrontendState::getIdentifier)
648                     .collect(ImmutableSet.toImmutableSet());
649         } else {
650             clients = frontendMetadata.getClients();
651         }
652         sender().tell(new GetKnownClientsReply(clients), self());
653     }
654
655     private boolean hasLeader() {
656         return getLeaderId() != null;
657     }
658
659     final int getPendingTxCommitQueueSize() {
660         return store.getQueueSize();
661     }
662
663     final int getCohortCacheSize() {
664         return commitCoordinator.getCohortCacheSize();
665     }
666
667     @Override
668     protected final Optional<ActorRef> getRoleChangeNotifier() {
669         return roleChangeNotifier;
670     }
671
672     final String getShardName() {
673         return shardName;
674     }
675
676     @Override
677     protected final LeaderStateChanged newLeaderStateChanged(final String memberId, final String leaderId,
678             final short leaderPayloadVersion) {
679         return isLeader() ? new ShardLeaderStateChanged(memberId, leaderId, store.getDataTree(), leaderPayloadVersion)
680                 : new ShardLeaderStateChanged(memberId, leaderId, leaderPayloadVersion);
681     }
682
683     private void onDatastoreContext(final DatastoreContext context) {
684         datastoreContext = verifyNotNull(context);
685
686         setTransactionCommitTimeout();
687
688         setPersistence(datastoreContext.isPersistent());
689
690         updateConfigParams(datastoreContext.getShardRaftConfig());
691     }
692
693     // applyState() will be invoked once consensus is reached on the payload
694     // non-final for mocking
695     void persistPayload(final Identifier id, final Payload payload, final boolean batchHint) {
696         final boolean canSkipPayload = !hasFollowers() && !persistence().isRecoveryApplicable();
697         if (canSkipPayload) {
698             applyState(self(), id, payload);
699         } else {
700             // We are faking the sender
701             persistData(self(), id, payload, batchHint);
702         }
703     }
704
705     private void handleCommitTransaction(final CommitTransaction commit) {
706         final TransactionIdentifier txId = commit.getTransactionId();
707         if (isLeader()) {
708             askProtocolEncountered(txId);
709             commitCoordinator.handleCommit(txId, getSender(), this);
710         } else {
711             ActorSelection leader = getLeader();
712             if (leader == null) {
713                 messageRetrySupport.addMessageToRetry(commit, getSender(), "Could not commit transaction " + txId);
714             } else {
715                 LOG.debug("{}: Forwarding CommitTransaction to leader {}", persistenceId(), leader);
716                 leader.forward(commit, getContext());
717             }
718         }
719     }
720
721     private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
722         final TransactionIdentifier txId = canCommit.getTransactionId();
723         LOG.debug("{}: Can committing transaction {}", persistenceId(), txId);
724
725         if (isLeader()) {
726             askProtocolEncountered(txId);
727             commitCoordinator.handleCanCommit(txId, getSender(), this);
728         } else {
729             ActorSelection leader = getLeader();
730             if (leader == null) {
731                 messageRetrySupport.addMessageToRetry(canCommit, getSender(),
732                         "Could not canCommit transaction " + txId);
733             } else {
734                 LOG.debug("{}: Forwarding CanCommitTransaction to leader {}", persistenceId(), leader);
735                 leader.forward(canCommit, getContext());
736             }
737         }
738     }
739
740     @SuppressWarnings("checkstyle:IllegalCatch")
741     private void handleBatchedModificationsLocal(final BatchedModifications batched, final ActorRef sender) {
742         askProtocolEncountered(batched.getTransactionId());
743
744         try {
745             commitCoordinator.handleBatchedModifications(batched, sender, this);
746         } catch (Exception e) {
747             LOG.error("{}: Error handling BatchedModifications for Tx {}", persistenceId(),
748                     batched.getTransactionId(), e);
749             sender.tell(new Failure(e), getSelf());
750         }
751     }
752
753     private void handleBatchedModifications(final BatchedModifications batched) {
754         // This message is sent to prepare the modifications transaction directly on the Shard as an
755         // optimization to avoid the extra overhead of a separate ShardTransaction actor. On the last
756         // BatchedModifications message, the caller sets the ready flag in the message indicating
757         // modifications are complete. The reply contains the cohort actor path (this actor) for the caller
758         // to initiate the 3-phase commit. This also avoids the overhead of sending an additional
759         // ReadyTransaction message.
760
761         // If we're not the leader then forward to the leader. This is a safety measure - we shouldn't
762         // normally get here if we're not the leader as the front-end (TransactionProxy) should determine
763         // the primary/leader shard. However with timing and caching on the front-end, there's a small
764         // window where it could have a stale leader during leadership transitions.
765         //
766         boolean isLeaderActive = isLeaderActive();
767         if (isLeader() && isLeaderActive) {
768             handleBatchedModificationsLocal(batched, getSender());
769         } else {
770             ActorSelection leader = getLeader();
771             if (!isLeaderActive || leader == null) {
772                 messageRetrySupport.addMessageToRetry(batched, getSender(),
773                         "Could not process BatchedModifications " + batched.getTransactionId());
774             } else {
775                 // If this is not the first batch and leadership changed in between batched messages,
776                 // we need to reconstruct previous BatchedModifications from the transaction
777                 // DataTreeModification, honoring the max batched modification count, and forward all the
778                 // previous BatchedModifications to the new leader.
779                 Collection<BatchedModifications> newModifications = commitCoordinator
780                         .createForwardedBatchedModifications(batched,
781                                 datastoreContext.getShardBatchedModificationCount());
782
783                 LOG.debug("{}: Forwarding {} BatchedModifications to leader {}", persistenceId(),
784                         newModifications.size(), leader);
785
786                 for (BatchedModifications bm : newModifications) {
787                     leader.forward(bm, getContext());
788                 }
789             }
790         }
791     }
792
793     private boolean failIfIsolatedLeader(final ActorRef sender) {
794         if (isIsolatedLeader()) {
795             sender.tell(new Failure(new NoShardLeaderException(String.format(
796                     "Shard %s was the leader but has lost contact with all of its followers. Either all"
797                     + " other follower nodes are down or this node is isolated by a network partition.",
798                     persistenceId()))), getSelf());
799             return true;
800         }
801
802         return false;
803     }
804
805     protected boolean isIsolatedLeader() {
806         return getRaftState() == RaftState.IsolatedLeader;
807     }
808
809     @SuppressWarnings("checkstyle:IllegalCatch")
810     private void handleReadyLocalTransaction(final ReadyLocalTransaction message) {
811         final TransactionIdentifier txId = message.getTransactionId();
812         LOG.debug("{}: handleReadyLocalTransaction for {}", persistenceId(), txId);
813
814         boolean isLeaderActive = isLeaderActive();
815         if (isLeader() && isLeaderActive) {
816             askProtocolEncountered(txId);
817             try {
818                 commitCoordinator.handleReadyLocalTransaction(message, getSender(), this);
819             } catch (Exception e) {
820                 LOG.error("{}: Error handling ReadyLocalTransaction for Tx {}", persistenceId(), txId, e);
821                 getSender().tell(new Failure(e), getSelf());
822             }
823         } else {
824             ActorSelection leader = getLeader();
825             if (!isLeaderActive || leader == null) {
826                 messageRetrySupport.addMessageToRetry(message, getSender(),
827                         "Could not process ready local transaction " + txId);
828             } else {
829                 LOG.debug("{}: Forwarding ReadyLocalTransaction to leader {}", persistenceId(), leader);
830                 message.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
831                 leader.forward(message, getContext());
832             }
833         }
834     }
835
836     private void handleForwardedReadyTransaction(final ForwardedReadyTransaction forwardedReady) {
837         LOG.debug("{}: handleForwardedReadyTransaction for {}", persistenceId(), forwardedReady.getTransactionId());
838
839         boolean isLeaderActive = isLeaderActive();
840         if (isLeader() && isLeaderActive) {
841             askProtocolEncountered(forwardedReady.getTransactionId());
842             commitCoordinator.handleForwardedReadyTransaction(forwardedReady, getSender(), this);
843         } else {
844             ActorSelection leader = getLeader();
845             if (!isLeaderActive || leader == null) {
846                 messageRetrySupport.addMessageToRetry(forwardedReady, getSender(),
847                         "Could not process forwarded ready transaction " + forwardedReady.getTransactionId());
848             } else {
849                 LOG.debug("{}: Forwarding ForwardedReadyTransaction to leader {}", persistenceId(), leader);
850
851                 ReadyLocalTransaction readyLocal = new ReadyLocalTransaction(forwardedReady.getTransactionId(),
852                         forwardedReady.getTransaction().getSnapshot(), forwardedReady.isDoImmediateCommit(),
853                         forwardedReady.getParticipatingShardNames());
854                 readyLocal.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
855                 leader.forward(readyLocal, getContext());
856             }
857         }
858     }
859
860     private void handleAbortTransaction(final AbortTransaction abort) {
861         final TransactionIdentifier transactionId = abort.getTransactionId();
862         askProtocolEncountered(transactionId);
863         doAbortTransaction(transactionId, getSender());
864     }
865
866     final void doAbortTransaction(final Identifier transactionID, final ActorRef sender) {
867         commitCoordinator.handleAbort(transactionID, sender, this);
868     }
869
870     private void handleCreateTransaction(final Object message) {
871         if (isLeader()) {
872             createTransaction(CreateTransaction.fromSerializable(message));
873         } else if (getLeader() != null) {
874             getLeader().forward(message, getContext());
875         } else {
876             getSender().tell(new Failure(new NoShardLeaderException(
877                     "Could not create a shard transaction", persistenceId())), getSelf());
878         }
879     }
880
881     private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
882         if (isLeader()) {
883             final LocalHistoryIdentifier id = closeTransactionChain.getIdentifier();
884             askProtocolEncountered(id.getClientId());
885             store.closeTransactionChain(id);
886         } else if (getLeader() != null) {
887             getLeader().forward(closeTransactionChain, getContext());
888         } else {
889             LOG.warn("{}: Could not close transaction {}", persistenceId(), closeTransactionChain.getIdentifier());
890         }
891     }
892
893     @SuppressWarnings("checkstyle:IllegalCatch")
894     private void createTransaction(final CreateTransaction createTransaction) {
895         askProtocolEncountered(createTransaction.getTransactionId());
896
897         try {
898             if (TransactionType.fromInt(createTransaction.getTransactionType()) != TransactionType.READ_ONLY
899                     && failIfIsolatedLeader(getSender())) {
900                 return;
901             }
902
903             ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
904                 createTransaction.getTransactionId());
905
906             getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
907                     createTransaction.getTransactionId(), createTransaction.getVersion()).toSerializable(), getSelf());
908         } catch (Exception e) {
909             getSender().tell(new Failure(e), getSelf());
910         }
911     }
912
913     private ActorRef createTransaction(final int transactionType, final TransactionIdentifier transactionId) {
914         LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
915         return transactionActorFactory.newShardTransaction(TransactionType.fromInt(transactionType),
916             transactionId);
917     }
918
919     // Called on leader only
920     private void askProtocolEncountered(final TransactionIdentifier transactionId) {
921         askProtocolEncountered(transactionId.getHistoryId().getClientId());
922     }
923
924     // Called on leader only
925     private void askProtocolEncountered(final ClientIdentifier clientId) {
926         final FrontendIdentifier frontend = clientId.getFrontendId();
927         final LeaderFrontendState state = knownFrontends.get(frontend);
928         if (!(state instanceof LeaderFrontendState.Disabled)) {
929             LOG.debug("{}: encountered ask-based client {}, disabling transaction tracking", persistenceId(), clientId);
930             if (knownFrontends.isEmpty()) {
931                 knownFrontends = new HashMap<>();
932             }
933             knownFrontends.put(frontend, new LeaderFrontendState.Disabled(persistenceId(), clientId, getDataStore()));
934
935             persistPayload(clientId, DisableTrackingPayload.create(clientId,
936                 datastoreContext.getInitialPayloadSerializedBufferCapacity()), false);
937         }
938     }
939
940     private void updateSchemaContext(final UpdateSchemaContext message) {
941         updateSchemaContext(message.getEffectiveModelContext());
942     }
943
944     @VisibleForTesting
945     void updateSchemaContext(final @NonNull EffectiveModelContext schemaContext) {
946         store.updateSchemaContext(schemaContext);
947     }
948
949     private boolean isMetricsCaptureEnabled() {
950         CommonConfig config = new CommonConfig(getContext().system().settings().config());
951         return config.isMetricCaptureEnabled();
952     }
953
954     @Override
955     protected final RaftActorSnapshotCohort getRaftActorSnapshotCohort() {
956         return snapshotCohort;
957     }
958
959     @Override
960     protected final RaftActorRecoveryCohort getRaftActorRecoveryCohort() {
961         if (restoreFromSnapshot == null) {
962             return ShardRecoveryCoordinator.create(store, persistenceId(), LOG);
963         }
964
965         return ShardRecoveryCoordinator.forSnapshot(store, persistenceId(), LOG, restoreFromSnapshot.getSnapshot());
966     }
967
968     @Override
969     // non-final for testing
970     protected void onRecoveryComplete() {
971         restoreFromSnapshot = null;
972
973         //notify shard manager
974         getContext().parent().tell(new ActorInitialized(), getSelf());
975
976         // Being paranoid here - this method should only be called once but just in case...
977         if (txCommitTimeoutCheckSchedule == null) {
978             // Schedule a message to be periodically sent to check if the current in-progress
979             // transaction should be expired and aborted.
980             FiniteDuration period = FiniteDuration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
981             txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
982                     period, period, getSelf(),
983                     TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
984         }
985     }
986
987     @Override
988     protected final void applyState(final ActorRef clientActor, final Identifier identifier, final Object data) {
989         if (data instanceof Payload payload) {
990             if (payload instanceof DisableTrackingPayload disableTracking) {
991                 disableTracking(disableTracking);
992                 return;
993             }
994
995             try {
996                 store.applyReplicatedPayload(identifier, payload);
997             } catch (DataValidationFailedException | IOException e) {
998                 LOG.error("{}: Error applying replica {}", persistenceId(), identifier, e);
999             }
1000         } else {
1001             LOG.error("{}: Unknown state for {} received {}", persistenceId(), identifier, data);
1002         }
1003     }
1004
1005     @Override
1006     protected final void onStateChanged() {
1007         boolean isLeader = isLeader();
1008         boolean hasLeader = hasLeader();
1009         treeChangeSupport.onLeadershipChange(isLeader, hasLeader);
1010
1011         // If this actor is no longer the leader close all the transaction chains
1012         if (!isLeader) {
1013             if (LOG.isDebugEnabled()) {
1014                 LOG.debug(
1015                     "{}: onStateChanged: Closing all transaction chains because shard {} is no longer the leader",
1016                     persistenceId(), getId());
1017             }
1018
1019             paused = false;
1020             store.purgeLeaderState();
1021         }
1022
1023         if (hasLeader && !isIsolatedLeader()) {
1024             messageRetrySupport.retryMessages();
1025         }
1026     }
1027
1028     @Override
1029     protected final void onLeaderChanged(final String oldLeader, final String newLeader) {
1030         shardMBean.incrementLeadershipChangeCount();
1031         paused = false;
1032
1033         if (!isLeader()) {
1034             if (!knownFrontends.isEmpty()) {
1035                 LOG.debug("{}: removing frontend state for {}", persistenceId(), knownFrontends.keySet());
1036                 knownFrontends = ImmutableMap.of();
1037             }
1038
1039             requestMessageAssembler.close();
1040
1041             if (!hasLeader()) {
1042                 // No leader anywhere, nothing else to do
1043                 return;
1044             }
1045
1046             // Another leader was elected. If we were the previous leader and had pending transactions, convert
1047             // them to transaction messages and send to the new leader.
1048             ActorSelection leader = getLeader();
1049             if (leader != null) {
1050                 // Clears all pending transactions and converts them to messages to be forwarded to a new leader.
1051                 Collection<?> messagesToForward = commitCoordinator.convertPendingTransactionsToMessages(
1052                     datastoreContext.getShardBatchedModificationCount());
1053
1054                 if (!messagesToForward.isEmpty()) {
1055                     LOG.debug("{}: Forwarding {} pending transaction messages to leader {}", persistenceId(),
1056                             messagesToForward.size(), leader);
1057
1058                     for (Object message : messagesToForward) {
1059                         LOG.debug("{}: Forwarding pending transaction message {}", persistenceId(), message);
1060
1061                         leader.tell(message, self());
1062                     }
1063                 }
1064             } else {
1065                 commitCoordinator.abortPendingTransactions("The transacton was aborted due to inflight leadership "
1066                         + "change and the leader address isn't available.", this);
1067             }
1068         } else {
1069             // We have become the leader, we need to reconstruct frontend state
1070             knownFrontends = verifyNotNull(frontendMetadata.toLeaderState(this));
1071             LOG.debug("{}: became leader with frontend state for {}", persistenceId(), knownFrontends.keySet());
1072         }
1073
1074         if (!isIsolatedLeader()) {
1075             messageRetrySupport.retryMessages();
1076         }
1077     }
1078
1079     @Override
1080     protected final void pauseLeader(final Runnable operation) {
1081         LOG.debug("{}: In pauseLeader, operation: {}", persistenceId(), operation);
1082         paused = true;
1083
1084         // Tell-based protocol can replay transaction state, so it is safe to blow it up when we are paused.
1085         knownFrontends.values().forEach(LeaderFrontendState::retire);
1086         knownFrontends = ImmutableMap.of();
1087
1088         store.setRunOnPendingTransactionsComplete(operation);
1089     }
1090
1091     @Override
1092     protected final void unpauseLeader() {
1093         LOG.debug("{}: In unpauseLeader", persistenceId());
1094         paused = false;
1095
1096         store.setRunOnPendingTransactionsComplete(null);
1097
1098         // Restore tell-based protocol state as if we were becoming the leader
1099         knownFrontends = verifyNotNull(frontendMetadata.toLeaderState(this));
1100     }
1101
1102     @Override
1103     protected final OnDemandRaftState.AbstractBuilder<?, ?> newOnDemandRaftStateBuilder() {
1104         return OnDemandShardState.newBuilder()
1105             .treeChangeListenerActors(treeChangeSupport.getListenerActors())
1106             .commitCohortActors(store.getCohortActors());
1107     }
1108
1109     @Override
1110     public final String persistenceId() {
1111         return name;
1112     }
1113
1114     @Override
1115     public final String journalPluginId() {
1116         // This method may be invoked from super constructor (wonderful), hence we also need to handle the case of
1117         // the field being uninitialized because our constructor is not finished.
1118         if (datastoreContext != null && !datastoreContext.isPersistent()) {
1119             return NON_PERSISTENT_JOURNAL_ID;
1120         }
1121         return super.journalPluginId();
1122     }
1123
1124     @VisibleForTesting
1125     final ShardCommitCoordinator getCommitCoordinator() {
1126         return commitCoordinator;
1127     }
1128
1129     // non-final for mocking
1130     DatastoreContext getDatastoreContext() {
1131         return datastoreContext;
1132     }
1133
1134     @VisibleForTesting
1135     final ShardDataTree getDataStore() {
1136         return store;
1137     }
1138
1139     @VisibleForTesting
1140     // non-final for mocking
1141     ShardStats getShardMBean() {
1142         return shardMBean;
1143     }
1144
1145     public static Builder builder() {
1146         return new Builder();
1147     }
1148
1149     public abstract static class AbstractBuilder<T extends AbstractBuilder<T, S>, S extends Shard> {
1150         private final Class<? extends S> shardClass;
1151         private ShardIdentifier id;
1152         private Map<String, String> peerAddresses = Collections.emptyMap();
1153         private DatastoreContext datastoreContext;
1154         private EffectiveModelContextProvider schemaContextProvider;
1155         private DatastoreSnapshot.ShardSnapshot restoreFromSnapshot;
1156         private DataTree dataTree;
1157
1158         private volatile boolean sealed;
1159
1160         AbstractBuilder(final Class<? extends S> shardClass) {
1161             this.shardClass = shardClass;
1162         }
1163
1164         final void checkSealed() {
1165             checkState(!sealed, "Builder is already sealed - further modifications are not allowed");
1166         }
1167
1168         @SuppressWarnings("unchecked")
1169         private T self() {
1170             return (T) this;
1171         }
1172
1173         public T id(final ShardIdentifier newId) {
1174             checkSealed();
1175             id = newId;
1176             return self();
1177         }
1178
1179         public T peerAddresses(final Map<String, String> newPeerAddresses) {
1180             checkSealed();
1181             peerAddresses = newPeerAddresses;
1182             return self();
1183         }
1184
1185         public T datastoreContext(final DatastoreContext newDatastoreContext) {
1186             checkSealed();
1187             datastoreContext = newDatastoreContext;
1188             return self();
1189         }
1190
1191         public T schemaContextProvider(final EffectiveModelContextProvider newSchemaContextProvider) {
1192             checkSealed();
1193             schemaContextProvider = requireNonNull(newSchemaContextProvider);
1194             return self();
1195         }
1196
1197         public T restoreFromSnapshot(final DatastoreSnapshot.ShardSnapshot newRestoreFromSnapshot) {
1198             checkSealed();
1199             restoreFromSnapshot = newRestoreFromSnapshot;
1200             return self();
1201         }
1202
1203         public T dataTree(final DataTree newDataTree) {
1204             checkSealed();
1205             dataTree = newDataTree;
1206             return self();
1207         }
1208
1209         public ShardIdentifier getId() {
1210             return id;
1211         }
1212
1213         public Map<String, String> getPeerAddresses() {
1214             return peerAddresses;
1215         }
1216
1217         public DatastoreContext getDatastoreContext() {
1218             return datastoreContext;
1219         }
1220
1221         public EffectiveModelContext getSchemaContext() {
1222             return verifyNotNull(schemaContextProvider.getEffectiveModelContext());
1223         }
1224
1225         public DatastoreSnapshot.ShardSnapshot getRestoreFromSnapshot() {
1226             return restoreFromSnapshot;
1227         }
1228
1229         public DataTree getDataTree() {
1230             return dataTree;
1231         }
1232
1233         public TreeType getTreeType() {
1234             return switch (datastoreContext.getLogicalStoreType()) {
1235                 case CONFIGURATION -> TreeType.CONFIGURATION;
1236                 case OPERATIONAL -> TreeType.OPERATIONAL;
1237             };
1238         }
1239
1240         protected void verify() {
1241             requireNonNull(id, "id should not be null");
1242             requireNonNull(peerAddresses, "peerAddresses should not be null");
1243             requireNonNull(datastoreContext, "dataStoreContext should not be null");
1244             requireNonNull(schemaContextProvider, "schemaContextProvider should not be null");
1245         }
1246
1247         public Props props() {
1248             sealed = true;
1249             verify();
1250             return Props.create(shardClass, this);
1251         }
1252     }
1253
1254     public static class Builder extends AbstractBuilder<Builder, Shard> {
1255         Builder() {
1256             this(Shard.class);
1257         }
1258
1259         Builder(final Class<? extends Shard> shardClass) {
1260             super(shardClass);
1261         }
1262     }
1263
1264     Ticker ticker() {
1265         return Ticker.systemTicker();
1266     }
1267
1268     void scheduleNextPendingTransaction() {
1269         self().tell(RESUME_NEXT_PENDING_TRANSACTION, ActorRef.noSender());
1270     }
1271 }