+ @GuardedBy("connectionsLock")
+ @Nonnull protected abstract ConnectionConnectCohort connectionUp(@Nonnull ConnectedClientConnection<T> newConn);
+
+ private void backendConnectFinished(final Long shard, final AbstractClientConnection<T> conn,
+ final T backend, final Throwable failure) {
+ if (failure != null) {
+ LOG.error("{}: failed to resolve shard {}", persistenceId(), shard, failure);
+ conn.poison(new RuntimeRequestException("Failed to resolve shard " + shard, failure));
+ return;
+ }
+
+ LOG.debug("{}: resolved shard {} to {}", persistenceId(), shard, backend);
+ final long stamp = connectionsLock.writeLock();
+ try {
+ // Create a new connected connection
+ final ConnectedClientConnection<T> newConn = new ConnectedClientConnection<>(conn.context(),
+ conn.cookie(), backend);
+ LOG.debug("{}: resolving connection {} to {}", persistenceId(), conn, newConn);
+
+ // Start reconnecting without the old connection lock held
+ final ConnectionConnectCohort cohort = Verify.verifyNotNull(connectionUp(newConn));
+
+ // Lock the old connection and get a reference to its entries
+ final Iterable<ConnectionEntry> replayIterable = conn.startReplay();
+
+ // Finish the connection attempt
+ final ReconnectForwarder forwarder = Verify.verifyNotNull(cohort.finishReconnect(replayIterable));
+
+ // Install the forwarder, unlocking the old connection
+ conn.finishReplay(forwarder);
+
+ // Make sure new lookups pick up the new connection
+ connections.replace(shard, conn, newConn);
+ LOG.debug("{}: replaced connection {} with {}", persistenceId(), conn, newConn);
+ } finally {
+ connectionsLock.unlockWrite(stamp);
+ }
+ }
+
+ void removeConnection(final AbstractClientConnection<?> conn) {
+ connections.remove(conn.cookie(), conn);
+ LOG.debug("{}: removed connection {}", persistenceId(), conn);
+ }
+
+ @SuppressWarnings("unchecked")
+ void reconnectConnection(final ConnectedClientConnection<?> oldConn,
+ final ReconnectingClientConnection<?> newConn) {
+ final ReconnectingClientConnection<T> conn = (ReconnectingClientConnection<T>)newConn;
+ connections.replace(oldConn.cookie(), (AbstractClientConnection<T>)oldConn, conn);
+ LOG.debug("{}: connection {} reconnecting as {}", persistenceId(), oldConn, newConn);
+
+ final Long shard = oldConn.cookie();
+ resolver().refreshBackendInfo(shard, conn.getBackendInfo().get()).whenComplete(
+ (backend, failure) -> context().executeInActor(behavior -> {
+ backendConnectFinished(shard, conn, backend, failure);
+ return behavior;
+ }));
+ }
+
+ private ConnectingClientConnection<T> createConnection(final Long shard) {
+ final ConnectingClientConnection<T> conn = new ConnectingClientConnection<>(context(), shard);
+
+ resolver().getBackendInfo(shard).whenComplete((backend, failure) -> context().executeInActor(behavior -> {
+ backendConnectFinished(shard, conn, backend, failure);
+ return behavior;
+ }));
+
+ return conn;