You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cassandra.apache.org by bd...@apache.org on 2022/04/11 16:17:33 UTC
[cassandra-accord] 02/03: Initial Cassandra integration
This is an automated email from the ASF dual-hosted git repository.
bdeggleston pushed a commit to branch trunk
in repository https://gitbox.apache.org/repos/asf/cassandra-accord.git
commit fb1187bdb6a726651383bbd8ab2352a8a2be7dd6
Author: Blake Eggleston <bd...@gmail.com>
AuthorDate: Wed Dec 1 13:43:02 2021 -0800
Initial Cassandra integration
Patch by Blake Eggleston; Reviewed by Benedict Elliott Smith for CASSANDRA-17412
---
accord-core/build.gradle | 26 ++
.../main/java/accord/api/ConfigurationService.java | 15 +-
accord-core/src/main/java/accord/api/Key.java | 5 +
accord-core/src/main/java/accord/api/KeyRange.java | 6 -
.../src/main/java/accord/api/MessageSink.java | 3 +-
accord-core/src/main/java/accord/api/Read.java | 4 +-
accord-core/src/main/java/accord/api/Write.java | 3 +-
.../main/java/accord/coordinate/AcceptPhase.java | 10 +-
.../src/main/java/accord/coordinate/Agree.java | 10 +-
.../main/java/accord/coordinate/Coordinate.java | 274 +----------
.../src/main/java/accord/coordinate/Execute.java | 16 +-
.../src/main/java/accord/coordinate/Recover.java | 37 +-
.../src/main/java/accord/local/CommandStore.java | 182 +++-----
.../src/main/java/accord/local/CommandStores.java | 230 +++++++---
accord-core/src/main/java/accord/local/Node.java | 65 +--
.../src/main/java/accord/messages/Accept.java | 16 +-
.../src/main/java/accord/messages/Apply.java | 20 +-
.../main/java/accord/messages/BeginRecovery.java | 30 +-
.../src/main/java/accord/messages/Commit.java | 14 +-
.../src/main/java/accord/messages/Message.java | 1 +
.../src/main/java/accord/messages/MessageType.java | 20 +
.../src/main/java/accord/messages/PreAccept.java | 16 +-
.../src/main/java/accord/messages/ReadData.java | 39 +-
.../messages/{Message.java => ReplyContext.java} | 2 +-
.../src/main/java/accord/messages/Request.java | 2 +-
.../src/main/java/accord/messages/TxnRequest.java | 24 +-
.../main/java/accord/messages/WaitOnCommit.java | 31 +-
accord-core/src/main/java/accord/txn/Keys.java | 137 ++++++
accord-core/src/main/java/accord/txn/Txn.java | 15 +-
accord-core/src/main/java/accord/txn/Writes.java | 10 +-
.../cassandra/concurrent/ExecutionFailure.java | 180 ++++++++
.../apache/cassandra/concurrent/ExecutorPlus.java | 185 ++++++++
.../cassandra/concurrent/ImmediateExecutor.java | 44 ++
.../java/org/apache/cassandra/utils/Clock.java | 124 +++++
.../java/org/apache/cassandra/utils/Intercept.java | 31 ++
.../java/org/apache/cassandra/utils/Shared.java | 45 ++
.../cassandra/utils/concurrent/AbstractFuture.java | 508 +++++++++++++++++++++
.../cassandra/utils/concurrent/AsyncFuture.java | 162 +++++++
.../cassandra/utils/concurrent/AsyncPromise.java | 268 +++++++++++
.../cassandra/utils/concurrent/Awaitable.java | 404 ++++++++++++++++
.../cassandra/utils/concurrent/Condition.java | 104 +++++
.../apache/cassandra/utils/concurrent/Future.java | 191 ++++++++
.../utils/concurrent/ImmediateFuture.java | 52 +++
.../apache/cassandra/utils/concurrent/Inline.java | 5 +
.../cassandra/utils/concurrent/IntrusiveStack.java | 156 +++++++
.../cassandra/utils/concurrent/ListenerList.java | 376 +++++++++++++++
.../apache/cassandra/utils/concurrent/Promise.java | 128 ++++++
.../concurrent/UncheckedInterruptedException.java | 38 ++
.../cassandra/utils/concurrent/WaitQueue.java | 437 ++++++++++++++++++
accord-core/src/test/java/accord/KeysTest.java | 11 +
.../accord/burn/BurnTestConfigurationService.java | 48 +-
.../src/test/java/accord/burn/TopologyUpdate.java | 50 +-
.../java/accord/coordinate/CoordinateTest.java | 6 +-
.../test/java/accord/coordinate/RecoverTest.java | 8 +-
.../java/accord/coordinate/TopologyChangeTest.java | 6 +-
.../src/test/java/accord/impl/IntHashKey.java | 9 +-
accord-core/src/test/java/accord/impl/IntKey.java | 33 +-
.../src/test/java/accord/impl/basic/Cluster.java | 4 +-
.../src/test/java/accord/impl/basic/NodeSink.java | 5 +-
.../src/test/java/accord/impl/basic/Packet.java | 11 +-
.../src/test/java/accord/impl/list/ListAgent.java | 3 +-
.../src/test/java/accord/impl/list/ListRead.java | 23 +-
.../test/java/accord/impl/list/ListRequest.java | 15 +-
.../src/test/java/accord/impl/list/ListResult.java | 7 +
.../src/test/java/accord/impl/list/ListStore.java | 9 +
.../src/test/java/accord/impl/list/ListWrite.java | 21 +-
.../src/test/java/accord/impl/mock/EpochSync.java | 38 +-
.../test/java/accord/impl/mock/MockCluster.java | 2 +-
.../accord/impl/mock/MockConfigurationService.java | 30 +-
.../src/test/java/accord/impl/mock/MockStore.java | 4 +-
.../src/test/java/accord/impl/mock/Network.java | 21 +
.../accord/impl/mock/RecordingMessageSink.java | 5 +-
.../java/accord/impl/mock/SimpleMessageSink.java | 5 +-
.../src/test/java/accord/local/CommandTest.java | 16 +-
.../test/java/accord/messages/PreAcceptTest.java | 14 +-
.../java/accord/topology/TopologyRandomizer.java | 4 +-
.../src/test/java/accord/utils/KeyRangeTest.java | 12 -
.../src/test/java/accord/utils/MessageTask.java | 34 +-
accord-maelstrom/build.gradle | 1 +
.../src/main/java/accord/maelstrom/Cluster.java | 8 +-
.../src/main/java/accord/maelstrom/Error.java | 7 +
.../main/java/accord/maelstrom/MaelstromAgent.java | 2 +-
.../main/java/accord/maelstrom/MaelstromKey.java | 33 +-
.../main/java/accord/maelstrom/MaelstromRead.java | 17 +-
.../main/java/accord/maelstrom/MaelstromReply.java | 7 +
.../accord/maelstrom/MaelstromReplyContext.java | 23 +
.../java/accord/maelstrom/MaelstromRequest.java | 15 +-
.../main/java/accord/maelstrom/MaelstromWrite.java | 19 +-
.../src/main/java/accord/maelstrom/Main.java | 9 +-
.../src/main/java/accord/maelstrom/Packet.java | 8 +-
.../java/accord/maelstrom/SimpleConfigService.java | 7 +-
build.gradle | 1 +
92 files changed, 4436 insertions(+), 876 deletions(-)
diff --git a/accord-core/build.gradle b/accord-core/build.gradle
index 58eef52..b48c9dc 100644
--- a/accord-core/build.gradle
+++ b/accord-core/build.gradle
@@ -1,5 +1,6 @@
plugins {
id 'java'
+ id 'maven'
}
group 'accord'
@@ -33,6 +34,7 @@ dependencies {
implementation 'com.google.guava:guava:30.1.1-jre'
implementation 'com.google.code.gson:gson:2.8.7'
implementation 'ch.qos.logback:logback-classic:1.2.3'
+ implementation 'io.netty:netty-all:4.1.58.Final'
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.7.0'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.7.0'
}
@@ -46,3 +48,27 @@ task burn(type: JavaExec) {
main = 'accord.burn.BurnTest'
jvmArgs '-Dlogback.configurationFile=burn-logback.xml'
}
+
+configure(install.repositories.mavenInstaller) {
+ pom.project {
+ groupId 'accord'
+ artifactId 'accord'
+ inceptionYear '2021'
+ packaging 'jar'
+ }
+}
+
+task sourcesJar(type: Jar, dependsOn:classes) {
+ classifier = 'sources'
+ from sourceSets.main.allSource
+}
+
+task javadocJar(type: Jar, dependsOn:javadoc) {
+ classifier = 'javadoc'
+ from javadoc.destinationDir
+}
+
+artifacts {
+ archives sourcesJar
+ archives javadocJar
+}
diff --git a/accord-core/src/main/java/accord/api/ConfigurationService.java b/accord-core/src/main/java/accord/api/ConfigurationService.java
index feb9fdc..1089644 100644
--- a/accord-core/src/main/java/accord/api/ConfigurationService.java
+++ b/accord-core/src/main/java/accord/api/ConfigurationService.java
@@ -2,9 +2,7 @@ package accord.api;
import accord.local.Node;
import accord.topology.Topology;
-
-import java.util.concurrent.CompletableFuture;
-import java.util.concurrent.CompletionStage;
+import org.apache.cassandra.utils.concurrent.Future;
/**
* ConfigurationService is responsible for:
@@ -74,7 +72,7 @@ public interface ConfigurationService
* runnable once the corresponding topology has been received and applied. If the configuration service is already
* aware of the reported epoch, the runnable should be run immediately.
*/
- void fetchTopologyForEpoch(long epoch, Runnable onComplete);
+ Future<Void> fetchTopologyForEpoch(long epoch);
/**
* Alert the configuration service of epochs it may not be aware of. This is called called for every TxnRequest
@@ -82,14 +80,7 @@ public interface ConfigurationService
*/
default void reportEpoch(long epoch)
{
- fetchTopologyForEpoch(epoch, null);
- }
-
- default CompletionStage<Void> fetchTopologyForEpochStage(long epoch)
- {
- CompletableFuture<Void> result = new CompletableFuture<>();
- fetchTopologyForEpoch(epoch, () -> result.complete(null));
- return result;
+ fetchTopologyForEpoch(epoch);
}
/**
diff --git a/accord-core/src/main/java/accord/api/Key.java b/accord-core/src/main/java/accord/api/Key.java
index 2c22972..85839ac 100644
--- a/accord-core/src/main/java/accord/api/Key.java
+++ b/accord-core/src/main/java/accord/api/Key.java
@@ -5,4 +5,9 @@ package accord.api;
*/
public interface Key<K extends Key<K>> extends Comparable<K>
{
+
+ /**
+ * Returns a hash code of a key to support accord internal sharding. Hash values for equal keys must be equal.
+ */
+ int keyHash();
}
diff --git a/accord-core/src/main/java/accord/api/KeyRange.java b/accord-core/src/main/java/accord/api/KeyRange.java
index d99b70d..b045a0c 100644
--- a/accord-core/src/main/java/accord/api/KeyRange.java
+++ b/accord-core/src/main/java/accord/api/KeyRange.java
@@ -138,12 +138,6 @@ public abstract class KeyRange<K extends Key<K>>
public abstract KeyRange<K> subRange(K start, K end);
- /**
- * Split this range into roughly equally sized subranges
- * @param count the number of subranges to create
- */
- public abstract KeyRanges split(int count);
-
@Override
public boolean equals(Object o)
{
diff --git a/accord-core/src/main/java/accord/api/MessageSink.java b/accord-core/src/main/java/accord/api/MessageSink.java
index 4fb3da9..8c0c510 100644
--- a/accord-core/src/main/java/accord/api/MessageSink.java
+++ b/accord-core/src/main/java/accord/api/MessageSink.java
@@ -3,11 +3,12 @@ package accord.api;
import accord.local.Node.Id;
import accord.messages.Callback;
import accord.messages.Reply;
+import accord.messages.ReplyContext;
import accord.messages.Request;
public interface MessageSink
{
void send(Id to, Request request);
void send(Id to, Request request, Callback callback);
- void reply(Id replyingToNode, long replyingToMessage, Reply reply);
+ void reply(Id replyingToNode, ReplyContext replyContext, Reply reply);
}
diff --git a/accord-core/src/main/java/accord/api/Read.java b/accord-core/src/main/java/accord/api/Read.java
index fa2780a..0823302 100644
--- a/accord-core/src/main/java/accord/api/Read.java
+++ b/accord-core/src/main/java/accord/api/Read.java
@@ -1,6 +1,6 @@
package accord.api;
-import accord.topology.KeyRanges;
+import accord.txn.Timestamp;
/**
* A read to be performed on potentially multiple shards, the inputs of which may be fed to a {@link Query}
@@ -9,5 +9,5 @@ import accord.topology.KeyRanges;
*/
public interface Read
{
- Data read(KeyRanges ranges, Store store);
+ Data read(Key key, Timestamp executeAt, Store store);
}
diff --git a/accord-core/src/main/java/accord/api/Write.java b/accord-core/src/main/java/accord/api/Write.java
index 1479c86..03d73c1 100644
--- a/accord-core/src/main/java/accord/api/Write.java
+++ b/accord-core/src/main/java/accord/api/Write.java
@@ -1,6 +1,5 @@
package accord.api;
-import accord.topology.KeyRanges;
import accord.txn.Timestamp;
/**
@@ -10,5 +9,5 @@ import accord.txn.Timestamp;
*/
public interface Write
{
- void apply(KeyRanges range, Timestamp executeAt, Store store);
+ void apply(Key key, Timestamp executeAt, Store store);
}
diff --git a/accord-core/src/main/java/accord/coordinate/AcceptPhase.java b/accord-core/src/main/java/accord/coordinate/AcceptPhase.java
index 8e66e91..95ad791 100644
--- a/accord-core/src/main/java/accord/coordinate/AcceptPhase.java
+++ b/accord-core/src/main/java/accord/coordinate/AcceptPhase.java
@@ -2,7 +2,6 @@ package accord.coordinate;
import java.util.ArrayList;
import java.util.List;
-import java.util.concurrent.CompletableFuture;
import accord.coordinate.tracking.QuorumTracker;
import accord.topology.Topologies;
@@ -17,8 +16,9 @@ import accord.txn.TxnId;
import accord.messages.Accept;
import accord.messages.Accept.AcceptOk;
import accord.messages.Accept.AcceptReply;
+import org.apache.cassandra.utils.concurrent.AsyncPromise;
-class AcceptPhase extends CompletableFuture<Agreed>
+class AcceptPhase extends AsyncPromise<Agreed>
{
final Node node;
final Ballot ballot;
@@ -55,7 +55,7 @@ class AcceptPhase extends CompletableFuture<Agreed>
{
acceptTracker.recordFailure(from);
if (acceptTracker.hasFailed())
- completeExceptionally(new Timeout());
+ tryFailure(new Timeout());
}
});
}
@@ -67,7 +67,7 @@ class AcceptPhase extends CompletableFuture<Agreed>
if (!reply.isOK())
{
- completeExceptionally(new Preempted());
+ tryFailure(new Preempted());
return;
}
@@ -89,6 +89,6 @@ class AcceptPhase extends CompletableFuture<Agreed>
protected void agreed(Timestamp executeAt, Dependencies deps, Topologies topologies)
{
- complete(new Agreed(txnId, txn, executeAt, deps, topologies, null, null));
+ setSuccess(new Agreed(txnId, txn, executeAt, deps, topologies, null, null));
}
}
diff --git a/accord-core/src/main/java/accord/coordinate/Agree.java b/accord-core/src/main/java/accord/coordinate/Agree.java
index 06bfcb7..8a3777c 100644
--- a/accord-core/src/main/java/accord/coordinate/Agree.java
+++ b/accord-core/src/main/java/accord/coordinate/Agree.java
@@ -4,7 +4,6 @@ import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
-import java.util.concurrent.CompletionStage;
import accord.coordinate.tracking.FastPathTracker;
import accord.topology.Shard;
@@ -22,6 +21,7 @@ import accord.txn.Txn;
import accord.txn.TxnId;
import accord.messages.PreAccept.PreAcceptReply;
import com.google.common.collect.Sets;
+import org.apache.cassandra.utils.concurrent.Future;
/**
* Perform initial rounds of PreAccept and Accept until we have reached agreement about when we should execute.
@@ -150,7 +150,7 @@ class Agree extends AcceptPhase implements Callback<PreAcceptReply>
tracker.recordFailure(from);
if (tracker.hasFailed())
- completeExceptionally(new Timeout());
+ tryFailure(new Timeout());
// if no other responses are expected and the slow quorum has been satisfied, proceed
if (shouldSlowPathAccept())
@@ -184,7 +184,7 @@ class Agree extends AcceptPhase implements Callback<PreAcceptReply>
if (!receive.isOK())
{
// we've been preempted by a recovery coordinator; defer to it, and wait to hear any result
- completeExceptionally(new Preempted());
+ tryFailure(new Preempted());
return;
}
@@ -197,7 +197,7 @@ class Agree extends AcceptPhase implements Callback<PreAcceptReply>
if (!fastPath && ok.witnessedAt.epoch > txnId.epoch)
{
if (tracker.recordSupersedingEpoch(ok.witnessedAt.epoch))
- node.configService().fetchTopologyForEpoch(ok.witnessedAt.epoch, this::onEpochUpdate);
+ node.configService().fetchTopologyForEpoch(ok.witnessedAt.epoch).addListener(this::onEpochUpdate);
}
if (!tracker.hasSupersedingEpoch() && (tracker.hasMetFastPathCriteria() || shouldSlowPathAccept()))
@@ -246,7 +246,7 @@ class Agree extends AcceptPhase implements Callback<PreAcceptReply>
return preacceptOutcome != null;
}
- static CompletionStage<Agreed> agree(Node node, TxnId txnId, Txn txn)
+ static Future<Agreed> agree(Node node, TxnId txnId, Txn txn)
{
return new Agree(node, txnId, txn);
}
diff --git a/accord-core/src/main/java/accord/coordinate/Coordinate.java b/accord-core/src/main/java/accord/coordinate/Coordinate.java
index 8fa90e1..b54d124 100644
--- a/accord-core/src/main/java/accord/coordinate/Coordinate.java
+++ b/accord-core/src/main/java/accord/coordinate/Coordinate.java
@@ -1,290 +1,38 @@
package accord.coordinate;
-import java.util.concurrent.CompletableFuture;
-import java.util.concurrent.CompletionStage;
-import java.util.concurrent.Executor;
-import java.util.function.BiConsumer;
-import java.util.function.BiFunction;
-import java.util.function.Consumer;
-import java.util.function.Function;
-
import accord.api.ConfigurationService;
-import accord.local.Node;
import accord.api.Result;
+import accord.local.Node;
+import accord.txn.Ballot;
import accord.txn.Txn;
import accord.txn.TxnId;
-import accord.txn.Ballot;
+import org.apache.cassandra.utils.concurrent.Future;
public class Coordinate
{
- private static CompletionStage<Result> fetchEpochOrExecute(Node node, Agreed agreed, DebugCompletionStage<Result> result)
+ private static Future<Result> fetchEpochOrExecute(Node node, Agreed agreed)
{
long executeEpoch = agreed.executeAt.epoch;
ConfigurationService configService = node.configService();
if (executeEpoch > configService.currentEpoch())
- return configService.fetchTopologyForEpochStage(executeEpoch)
- .thenCompose(v -> fetchEpochOrExecute(node, agreed, result));
+ return configService.fetchTopologyForEpoch(executeEpoch)
+ .flatMap(v -> fetchEpochOrExecute(node, agreed));
- CompletionStage<Result> execute = Execute.execute(node, agreed);
- result.debug2 = execute;
- return execute;
+ return Execute.execute(node, agreed);
}
- private static CompletionStage<Result> andThenExecute(Node node, CompletionStage<Agreed> agree)
+ private static Future<Result> andThenExecute(Node node, Future<Agreed> agree)
{
- DebugCompletionStage<Result> result = new DebugCompletionStage<>(agree);
- result.wrapped = agree.thenCompose(agreed -> fetchEpochOrExecute(node, agreed, result));
- return result;
+ return agree.flatMap(agreed -> fetchEpochOrExecute(node, agreed));
}
- public static CompletionStage<Result> execute(Node node, TxnId txnId, Txn txn)
+ public static Future<Result> execute(Node node, TxnId txnId, Txn txn)
{
return andThenExecute(node, Agree.agree(node, txnId, txn));
}
- public static CompletionStage<Result> recover(Node node, TxnId txnId, Txn txn)
+ public static Future<Result> recover(Node node, TxnId txnId, Txn txn)
{
return andThenExecute(node, new Recover(node, new Ballot(node.uniqueNow()), txnId, txn));
}
-
- private static class DebugCompletionStage<T> implements CompletionStage<T>
- {
- final Object debug1;
- Object debug2;
- CompletionStage<T> wrapped;
-
- @Override
- public <U> CompletionStage<U> thenApply(Function<? super T, ? extends U> fn)
- {
- return wrapped.thenApply(fn);
- }
-
- @Override
- public <U> CompletionStage<U> thenApplyAsync(Function<? super T, ? extends U> fn)
- {
- return wrapped.thenApplyAsync(fn);
- }
-
- @Override
- public <U> CompletionStage<U> thenApplyAsync(Function<? super T, ? extends U> fn, Executor executor)
- {
- return wrapped.thenApplyAsync(fn, executor);
- }
-
- @Override
- public CompletionStage<Void> thenAccept(Consumer<? super T> action)
- {
- return wrapped.thenAccept(action);
- }
-
- @Override
- public CompletionStage<Void> thenAcceptAsync(Consumer<? super T> action)
- {
- return wrapped.thenAcceptAsync(action);
- }
-
- @Override
- public CompletionStage<Void> thenAcceptAsync(Consumer<? super T> action, Executor executor)
- {
- return wrapped.thenAcceptAsync(action, executor);
- }
-
- @Override
- public CompletionStage<Void> thenRun(Runnable action)
- {
- return wrapped.thenRun(action);
- }
-
- @Override
- public CompletionStage<Void> thenRunAsync(Runnable action)
- {
- return wrapped.thenRunAsync(action);
- }
-
- @Override
- public CompletionStage<Void> thenRunAsync(Runnable action, Executor executor)
- {
- return wrapped.thenRunAsync(action, executor);
- }
-
- @Override
- public <U, V> CompletionStage<V> thenCombine(CompletionStage<? extends U> other, BiFunction<? super T, ? super U, ? extends V> fn)
- {
- return wrapped.thenCombine(other, fn);
- }
-
- @Override
- public <U, V> CompletionStage<V> thenCombineAsync(CompletionStage<? extends U> other, BiFunction<? super T, ? super U, ? extends V> fn)
- {
- return wrapped.thenCombineAsync(other, fn);
- }
-
- @Override
- public <U, V> CompletionStage<V> thenCombineAsync(CompletionStage<? extends U> other, BiFunction<? super T, ? super U, ? extends V> fn, Executor executor)
- {
- return wrapped.thenCombineAsync(other, fn, executor);
- }
-
- @Override
- public <U> CompletionStage<Void> thenAcceptBoth(CompletionStage<? extends U> other, BiConsumer<? super T, ? super U> action)
- {
- return wrapped.thenAcceptBoth(other, action);
- }
-
- @Override
- public <U> CompletionStage<Void> thenAcceptBothAsync(CompletionStage<? extends U> other, BiConsumer<? super T, ? super U> action)
- {
- return wrapped.thenAcceptBothAsync(other, action);
- }
-
- @Override
- public <U> CompletionStage<Void> thenAcceptBothAsync(CompletionStage<? extends U> other, BiConsumer<? super T, ? super U> action, Executor executor)
- {
- return wrapped.thenAcceptBothAsync(other, action, executor);
- }
-
- @Override
- public CompletionStage<Void> runAfterBoth(CompletionStage<?> other, Runnable action)
- {
- return wrapped.runAfterBoth(other, action);
- }
-
- @Override
- public CompletionStage<Void> runAfterBothAsync(CompletionStage<?> other, Runnable action)
- {
- return wrapped.runAfterBothAsync(other, action);
- }
-
- @Override
- public CompletionStage<Void> runAfterBothAsync(CompletionStage<?> other, Runnable action, Executor executor)
- {
- return wrapped.runAfterBothAsync(other, action, executor);
- }
-
- @Override
- public <U> CompletionStage<U> applyToEither(CompletionStage<? extends T> other, Function<? super T, U> fn)
- {
- return wrapped.applyToEither(other, fn);
- }
-
- @Override
- public <U> CompletionStage<U> applyToEitherAsync(CompletionStage<? extends T> other, Function<? super T, U> fn)
- {
- return wrapped.applyToEitherAsync(other, fn);
- }
-
- @Override
- public <U> CompletionStage<U> applyToEitherAsync(CompletionStage<? extends T> other, Function<? super T, U> fn, Executor executor)
- {
- return wrapped.applyToEitherAsync(other, fn, executor);
- }
-
- @Override
- public CompletionStage<Void> acceptEither(CompletionStage<? extends T> other, Consumer<? super T> action)
- {
- return wrapped.acceptEither(other, action);
- }
-
- @Override
- public CompletionStage<Void> acceptEitherAsync(CompletionStage<? extends T> other, Consumer<? super T> action)
- {
- return wrapped.acceptEitherAsync(other, action);
- }
-
- @Override
- public CompletionStage<Void> acceptEitherAsync(CompletionStage<? extends T> other, Consumer<? super T> action, Executor executor)
- {
- return wrapped.acceptEitherAsync(other, action, executor);
- }
-
- @Override
- public CompletionStage<Void> runAfterEither(CompletionStage<?> other, Runnable action)
- {
- return wrapped.runAfterEither(other, action);
- }
-
- @Override
- public CompletionStage<Void> runAfterEitherAsync(CompletionStage<?> other, Runnable action)
- {
- return wrapped.runAfterEitherAsync(other, action);
- }
-
- @Override
- public CompletionStage<Void> runAfterEitherAsync(CompletionStage<?> other, Runnable action, Executor executor)
- {
- return wrapped.runAfterEitherAsync(other, action, executor);
- }
-
- @Override
- public <U> CompletionStage<U> thenCompose(Function<? super T, ? extends CompletionStage<U>> fn)
- {
- return wrapped.thenCompose(fn);
- }
-
- @Override
- public <U> CompletionStage<U> thenComposeAsync(Function<? super T, ? extends CompletionStage<U>> fn)
- {
- return wrapped.thenComposeAsync(fn);
- }
-
- @Override
- public <U> CompletionStage<U> thenComposeAsync(Function<? super T, ? extends CompletionStage<U>> fn, Executor executor)
- {
- return wrapped.thenComposeAsync(fn, executor);
- }
-
- @Override
- public <U> CompletionStage<U> handle(BiFunction<? super T, Throwable, ? extends U> fn)
- {
- return wrapped.handle(fn);
- }
-
- @Override
- public <U> CompletionStage<U> handleAsync(BiFunction<? super T, Throwable, ? extends U> fn)
- {
- return wrapped.handleAsync(fn);
- }
-
- @Override
- public <U> CompletionStage<U> handleAsync(BiFunction<? super T, Throwable, ? extends U> fn, Executor executor)
- {
- return wrapped.handleAsync(fn, executor);
- }
-
- @Override
- public CompletionStage<T> whenComplete(BiConsumer<? super T, ? super Throwable> action)
- {
- return wrapped.whenComplete(action);
- }
-
- @Override
- public CompletionStage<T> whenCompleteAsync(BiConsumer<? super T, ? super Throwable> action)
- {
- return wrapped.whenCompleteAsync(action);
- }
-
- @Override
- public CompletionStage<T> whenCompleteAsync(BiConsumer<? super T, ? super Throwable> action, Executor executor)
- {
- return wrapped.whenCompleteAsync(action, executor);
- }
-
- @Override
- public CompletionStage<T> exceptionally(Function<Throwable, ? extends T> fn)
- {
- return wrapped.exceptionally(fn);
- }
-
- @Override
- public CompletableFuture<T> toCompletableFuture()
- {
- return wrapped.toCompletableFuture();
- }
-
- private DebugCompletionStage(Object debug1)
- {
- this.debug1 = debug1;
- }
- }
-
}
diff --git a/accord-core/src/main/java/accord/coordinate/Execute.java b/accord-core/src/main/java/accord/coordinate/Execute.java
index 6e9728b..2b6d09b 100644
--- a/accord-core/src/main/java/accord/coordinate/Execute.java
+++ b/accord-core/src/main/java/accord/coordinate/Execute.java
@@ -1,8 +1,6 @@
package accord.coordinate;
import java.util.Set;
-import java.util.concurrent.CompletableFuture;
-import java.util.concurrent.CompletionStage;
import accord.api.Data;
import accord.coordinate.tracking.ReadTracker;
@@ -18,8 +16,10 @@ import accord.local.Node.Id;
import accord.messages.Commit;
import accord.messages.ReadData;
import accord.messages.ReadData.ReadOk;
+import org.apache.cassandra.utils.concurrent.AsyncPromise;
+import org.apache.cassandra.utils.concurrent.Future;
-class Execute extends CompletableFuture<Result> implements Callback<ReadReply>
+class Execute extends AsyncPromise<Result> implements Callback<ReadReply>
{
final Node node;
final TxnId txnId;
@@ -47,7 +47,7 @@ class Execute extends CompletableFuture<Result> implements Callback<ReadReply>
{
node.send(topologies.nodes(),
to -> new Apply(to, topologies, txnId, txn, executeAt, agreed.deps, agreed.applied, agreed.result));
- complete(agreed.result);
+ setSuccess(agreed.result);
}
else
{
@@ -86,7 +86,7 @@ class Execute extends CompletableFuture<Result> implements Callback<ReadReply>
if (!reply.isOK())
{
- completeExceptionally(new Preempted());
+ tryFailure(new Preempted());
return;
}
@@ -100,7 +100,7 @@ class Execute extends CompletableFuture<Result> implements Callback<ReadReply>
Result result = txn.result(data);
Writes writes = txn.execute(executeAt, data);
node.send(topologies.nodes(), to -> new Apply(to, topologies, txnId, txn, executeAt, deps, writes, result));
- complete(result);
+ setSuccess(result);
}
}
@@ -120,11 +120,11 @@ class Execute extends CompletableFuture<Result> implements Callback<ReadReply>
}
else if (readTracker.hasFailed())
{
- completeExceptionally(throwable);
+ tryFailure(throwable);
}
}
- static CompletionStage<Result> execute(Node instance, Agreed agreed)
+ static Future<Result> execute(Node instance, Agreed agreed)
{
return new Execute(instance, agreed);
}
diff --git a/accord-core/src/main/java/accord/coordinate/Recover.java b/accord-core/src/main/java/accord/coordinate/Recover.java
index 6600f22..1165d4d 100644
--- a/accord-core/src/main/java/accord/coordinate/Recover.java
+++ b/accord-core/src/main/java/accord/coordinate/Recover.java
@@ -3,8 +3,6 @@ package accord.coordinate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
-import java.util.concurrent.CompletableFuture;
-import java.util.concurrent.CompletionStage;
import java.util.concurrent.atomic.AtomicInteger;
import accord.coordinate.tracking.FastPathTracker;
@@ -24,6 +22,9 @@ import accord.messages.BeginRecovery.RecoverOk;
import accord.messages.BeginRecovery.RecoverReply;
import accord.messages.WaitOnCommit;
import accord.messages.WaitOnCommit.WaitOnCommitOk;
+import org.apache.cassandra.utils.concurrent.AsyncPromise;
+import org.apache.cassandra.utils.concurrent.Future;
+import org.apache.cassandra.utils.concurrent.Promise;
import static accord.local.Status.Accepted;
@@ -31,7 +32,7 @@ import static accord.local.Status.Accepted;
class Recover extends AcceptPhase implements Callback<RecoverReply>
{
private static final Object SENTINEL = new Object();
- static class AwaitCommit extends CompletableFuture<Object> implements Callback<WaitOnCommitOk>
+ static class AwaitCommit extends AsyncPromise<Object> implements Callback<WaitOnCommitOk>
{
final QuorumTracker tracker;
@@ -49,7 +50,7 @@ class Recover extends AcceptPhase implements Callback<RecoverReply>
tracker.recordSuccess(from);
if(tracker.hasReachedQuorum())
- complete(SENTINEL);
+ setSuccess(SENTINEL);
}
@Override
@@ -59,23 +60,23 @@ class Recover extends AcceptPhase implements Callback<RecoverReply>
tracker.recordFailure(from);
if (tracker.hasFailed())
- completeExceptionally(new Timeout());
+ tryFailure(new Timeout());
}
}
- static CompletionStage<Object> awaitCommits(Node node, Dependencies waitOn)
+ static Future<Object> awaitCommits(Node node, Dependencies waitOn)
{
AtomicInteger remaining = new AtomicInteger(waitOn.size());
- CompletableFuture<Object> future = new CompletableFuture<>();
+ Promise<Object> future = new AsyncPromise<>();
for (Map.Entry<TxnId, Txn> e : waitOn)
{
- new AwaitCommit(node, e.getKey(), e.getValue()).whenComplete((success, failure) -> {
+ new AwaitCommit(node, e.getKey(), e.getValue()).addCallback((success, failure) -> {
if (future.isDone())
return;
if (success != null && remaining.decrementAndGet() == 0)
- future.complete(SENTINEL);
+ future.setSuccess(SENTINEL);
else
- future.completeExceptionally(failure);
+ future.tryFailure(failure);
});
}
return future;
@@ -131,7 +132,7 @@ class Recover extends AcceptPhase implements Callback<RecoverReply>
if (!response.isOK())
{
- completeExceptionally(new Preempted());
+ tryFailure(new Preempted());
return;
}
@@ -170,7 +171,7 @@ class Recover extends AcceptPhase implements Callback<RecoverReply>
case ReadyToExecute:
case Executed:
case Applied:
- complete(new Agreed(txnId, txn, acceptOrCommit.executeAt, acceptOrCommit.deps, node.topology().forTxn(txn, minEpoch), acceptOrCommit.writes, acceptOrCommit.result));
+ setSuccess(new Agreed(txnId, txn, acceptOrCommit.executeAt, acceptOrCommit.deps, node.topology().forTxn(txn, minEpoch), acceptOrCommit.writes, acceptOrCommit.result));
return;
}
}
@@ -200,9 +201,9 @@ class Recover extends AcceptPhase implements Callback<RecoverReply>
earlierAcceptedNoWitness.removeAll(earlierCommittedWitness);
if (!earlierAcceptedNoWitness.isEmpty())
{
- awaitCommits(node, earlierAcceptedNoWitness).whenComplete((success, failure) -> {
+ awaitCommits(node, earlierAcceptedNoWitness).addCallback((success, failure) -> {
if (success != null) retry();
- else completeExceptionally(new Timeout());
+ else tryFailure(new Timeout());
});
return;
}
@@ -214,9 +215,9 @@ class Recover extends AcceptPhase implements Callback<RecoverReply>
private void retry()
{
- new Recover(node, ballot, txnId, txn, node.topology().forEpoch(txn, txnId.epoch)).whenComplete((success, failure) -> {
- if (success != null) complete(success);
- else completeExceptionally(failure);
+ new Recover(node, ballot, txnId, txn, node.topology().forEpoch(txn, txnId.epoch)).addCallback((success, failure) -> {
+ if (success != null) setSuccess(success);
+ else tryFailure(failure);
});
}
@@ -228,6 +229,6 @@ class Recover extends AcceptPhase implements Callback<RecoverReply>
tracker.recordFailure(from);
if (tracker.hasFailed())
- completeExceptionally(new Timeout());
+ tryFailure(new Timeout());
}
}
diff --git a/accord-core/src/main/java/accord/local/CommandStore.java b/accord-core/src/main/java/accord/local/CommandStore.java
index f3a6b95..3241cd7 100644
--- a/accord-core/src/main/java/accord/local/CommandStore.java
+++ b/accord-core/src/main/java/accord/local/CommandStore.java
@@ -10,91 +10,70 @@ import accord.txn.Keys;
import accord.txn.Timestamp;
import accord.txn.TxnId;
import com.google.common.base.Preconditions;
+import org.apache.cassandra.utils.concurrent.AsyncPromise;
+import org.apache.cassandra.utils.concurrent.Future;
+import org.apache.cassandra.utils.concurrent.Promise;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import java.util.function.Function;
-import java.util.function.IntFunction;
+import java.util.function.Supplier;
/**
* Single threaded internal shard of accord transaction metadata
*/
public abstract class CommandStore
{
- // TODO: consider sharding on key hash, rather than splitting ranges
- static class Mapping
- {
- static final Mapping EMPTY = new Mapping(KeyRanges.EMPTY, Topology.EMPTY);
- final KeyRanges ranges;
- final Topology local;
-
- public Mapping(KeyRanges ranges, Topology local)
- {
- this.ranges = ranges;
- this.local = local;
- }
-
- public Mapping withNewLocalTopology(Topology local)
- {
- return new Mapping(ranges, local);
- }
-
- static void withNewLocalTopology(Mapping[] current, Topology local, Mapping[] dst)
- {
- for (int i=0; i<current.length; i++)
- dst[i] = current[i].withNewLocalTopology(local);
- }
-
- static Mapping[] withNewLocalTopology(Mapping[] current, Topology locals)
- {
- Mapping[] result = new Mapping[current.length];
- withNewLocalTopology(current, locals, result);
- return result;
- }
- }
-
public interface Factory
{
- CommandStore create(int index,
+ CommandStore create(int generation,
+ int index,
+ int numShards,
Node.Id nodeId,
Function<Timestamp, Timestamp> uniqueNow,
Agent agent,
Store store,
- Mapping initialMapping,
- IntFunction<Mapping> mappingSupplier);
+ KeyRanges ranges,
+ Supplier<Topology> localTopologySupplier);
Factory SYNCHRONIZED = Synchronized::new;
Factory SINGLE_THREAD = SingleThread::new;
Factory SINGLE_THREAD_DEBUG = SingleThreadDebug::new;
}
+ private final int generation;
private final int index;
+ private final int numShards;
private final Node.Id nodeId;
private final Function<Timestamp, Timestamp> uniqueNow;
private final Agent agent;
private final Store store;
- private final IntFunction<Mapping> mappingSupplier;
- private Mapping rangeMap;
+ private final KeyRanges ranges;
+ private final Supplier<Topology> localTopologySupplier;
private final NavigableMap<TxnId, Command> commands = new TreeMap<>();
private final NavigableMap<Key, CommandsForKey> commandsForKey = new TreeMap<>();
- public CommandStore(int index,
+ public CommandStore(int generation,
+ int index,
+ int numShards,
Node.Id nodeId,
Function<Timestamp, Timestamp> uniqueNow,
Agent agent,
Store store,
- Mapping initialMapping,
- IntFunction<Mapping> mappingSupplier)
+ KeyRanges ranges,
+ Supplier<Topology> localTopologySupplier)
{
+ this.generation = generation;
this.index = index;
+ this.numShards = numShards;
this.nodeId = nodeId;
this.uniqueNow = uniqueNow;
this.agent = agent;
this.store = store;
- this.rangeMap = initialMapping;
- this.mappingSupplier = mappingSupplier;
+ this.ranges = ranges;
+ this.localTopologySupplier = localTopologySupplier;
}
public Command command(TxnId txnId)
@@ -139,13 +118,12 @@ public abstract class CommandStore
public long epoch()
{
- return rangeMap.local.epoch();
+ return localTopologySupplier.get().epoch();
}
public KeyRanges ranges()
{
- // TODO: check thread safety of callers
- return rangeMap.ranges;
+ return ranges;
}
void purgeRanges(KeyRanges removed)
@@ -161,7 +139,7 @@ public abstract class CommandStore
if (forKey != null)
{
for (Command command : forKey)
- if (command.txn() != null && !rangeMap.ranges.intersects(command.txn().keys))
+ if (command.txn() != null && !ranges.intersects(command.txn().keys))
commands.remove(command.txnId());
}
keyIterator.remove();
@@ -213,9 +191,14 @@ public abstract class CommandStore
return index;
}
+ public boolean hashIntersects(Key key)
+ {
+ return CommandStores.keyIndex(key, numShards) == index;
+ }
+
public boolean intersects(Keys keys)
{
- return rangeMap.ranges.intersects(keys);
+ return keys.any(ranges, this::hashIntersects);
}
public static void onEach(Collection<CommandStore> stores, Consumer<? super CommandStore> consumer)
@@ -224,47 +207,38 @@ public abstract class CommandStore
store.process(consumer);
}
- private void refreshRangeMap()
- {
- rangeMap = mappingSupplier.apply(index);
- }
-
- <R> void processInternal(Function<? super CommandStore, R> function, CompletableFuture<R> future)
+ <R> void processInternal(Function<? super CommandStore, R> function, Promise<R> promise)
{
try
{
- refreshRangeMap();
- future.complete(function.apply(this));
+ promise.setSuccess(function.apply(this));
}
catch (Throwable e)
{
- future.completeExceptionally(e);
+ promise.tryFailure(e);
}
}
- void processInternal(Consumer<? super CommandStore> consumer, CompletableFuture<Void> future)
+ void processInternal(Consumer<? super CommandStore> consumer, Promise<Void> promise)
{
try
{
- refreshRangeMap();
consumer.accept(this);
- future.complete(null);
+ promise.setSuccess(null);
}
catch (Throwable e)
{
- future.completeExceptionally(e);
+ promise.tryFailure(e);
}
}
- public abstract <R> CompletionStage<R> process(Function<? super CommandStore, R> function);
-
- public abstract CompletionStage<Void> process(Consumer<? super CommandStore> consumer);
+ public abstract Future<Void> process(Consumer<? super CommandStore> consumer);
public void processBlocking(Consumer<? super CommandStore> consumer)
{
try
{
- process(consumer).toCompletableFuture().get();
+ process(consumer).get();
}
catch (InterruptedException e)
{
@@ -280,31 +254,25 @@ public abstract class CommandStore
public static class Synchronized extends CommandStore
{
- public Synchronized(int index,
+ public Synchronized(int generation,
+ int index,
+ int numShards,
Node.Id nodeId,
Function<Timestamp, Timestamp> uniqueNow,
Agent agent,
Store store,
- Mapping initialMapping,
- IntFunction<Mapping> mappingSupplier)
+ KeyRanges ranges,
+ Supplier<Topology> localTopologySupplier)
{
- super(index, nodeId, uniqueNow, agent, store, initialMapping, mappingSupplier);
+ super(generation, index, numShards, nodeId, uniqueNow, agent, store, ranges, localTopologySupplier);
}
@Override
- public synchronized <R> CompletionStage<R> process(Function<? super CommandStore, R> func)
+ public synchronized Future<Void> process(Consumer<? super CommandStore> consumer)
{
- CompletableFuture<R> future = new CompletableFuture<>();
- processInternal(func, future);
- return future;
- }
-
- @Override
- public synchronized CompletionStage<Void> process(Consumer<? super CommandStore> consumer)
- {
- CompletableFuture<Void> future = new CompletableFuture<>();
- processInternal(consumer, future);
- return future;
+ AsyncPromise<Void> promise = new AsyncPromise<>();
+ processInternal(consumer, promise);
+ return promise;
}
@Override
@@ -315,23 +283,7 @@ public abstract class CommandStore
{
private final ExecutorService executor;
- private class FunctionWrapper<R> extends CompletableFuture<R> implements Runnable
- {
- private final Function<? super CommandStore, R> function;
-
- public FunctionWrapper(Function<? super CommandStore, R> function)
- {
- this.function = function;
- }
-
- @Override
- public void run()
- {
- processInternal(function, this);
- }
- }
-
- private class ConsumerWrapper extends CompletableFuture<Void> implements Runnable
+ private class ConsumerWrapper extends AsyncPromise<Void> implements Runnable
{
private final Consumer<? super CommandStore> consumer;
@@ -347,15 +299,17 @@ public abstract class CommandStore
}
}
- public SingleThread(int index,
+ public SingleThread(int generation,
+ int index,
+ int numShards,
Node.Id nodeId,
Function<Timestamp, Timestamp> uniqueNow,
Agent agent,
Store store,
- Mapping initialMapping,
- IntFunction<Mapping> mappingSupplier)
+ KeyRanges ranges,
+ Supplier<Topology> localTopologySupplier)
{
- super(index, nodeId, uniqueNow, agent, store, initialMapping, mappingSupplier);
+ super(generation, index, numShards, nodeId, uniqueNow, agent, store, ranges, localTopologySupplier);
executor = Executors.newSingleThreadExecutor(r -> {
Thread thread = new Thread(r);
thread.setName(CommandStore.class.getSimpleName() + '[' + nodeId + ':' + index + ']');
@@ -364,15 +318,7 @@ public abstract class CommandStore
}
@Override
- public <R> CompletionStage<R> process(Function<? super CommandStore, R> function)
- {
- FunctionWrapper<R> future = new FunctionWrapper<>(function);
- executor.execute(future);
- return future;
- }
-
- @Override
- public CompletionStage<Void> process(Consumer<? super CommandStore> consumer)
+ public Future<Void> process(Consumer<? super CommandStore> consumer)
{
ConsumerWrapper future = new ConsumerWrapper(consumer);
executor.execute(future);
@@ -390,15 +336,17 @@ public abstract class CommandStore
{
private final AtomicReference<Thread> expectedThread = new AtomicReference<>();
- public SingleThreadDebug(int index,
+ public SingleThreadDebug(int generation,
+ int index,
+ int numShards,
Node.Id nodeId,
Function<Timestamp, Timestamp> uniqueNow,
Agent agent,
Store store,
- Mapping initialMapping,
- IntFunction<Mapping> mappingSupplier)
+ KeyRanges ranges,
+ Supplier<Topology> localTopologySupplier)
{
- super(index, nodeId, uniqueNow, agent, store, initialMapping, mappingSupplier);
+ super(generation, index, numShards, nodeId, uniqueNow, agent, store, ranges, localTopologySupplier);
}
private void assertThread()
@@ -444,14 +392,14 @@ public abstract class CommandStore
}
@Override
- <R> void processInternal(Function<? super CommandStore, R> function, CompletableFuture<R> future)
+ <R> void processInternal(Function<? super CommandStore, R> function, Promise<R> future)
{
assertThread();
super.processInternal(function, future);
}
@Override
- void processInternal(Consumer<? super CommandStore> consumer, CompletableFuture<Void> future)
+ void processInternal(Consumer<? super CommandStore> consumer, Promise<Void> future)
{
assertThread();
super.processInternal(consumer, future);
diff --git a/accord-core/src/main/java/accord/local/CommandStores.java b/accord-core/src/main/java/accord/local/CommandStores.java
index b087962..8e5886c 100644
--- a/accord-core/src/main/java/accord/local/CommandStores.java
+++ b/accord-core/src/main/java/accord/local/CommandStores.java
@@ -1,18 +1,17 @@
package accord.local;
import accord.api.Agent;
-import accord.api.KeyRange;
+import accord.api.Key;
import accord.api.Store;
-import accord.local.CommandStore.Mapping;
import accord.messages.TxnRequest;
import accord.topology.KeyRanges;
import accord.topology.Topology;
import accord.txn.Keys;
import accord.txn.Timestamp;
import com.google.common.base.Preconditions;
+import org.apache.cassandra.utils.concurrent.Future;
import java.util.*;
-import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.function.*;
import java.util.stream.Stream;
@@ -23,133 +22,218 @@ import java.util.stream.StreamSupport;
*/
public class CommandStores
{
- static class Mappings
+ static class StoreGroup
{
- static final Mappings EMPTY = new Mappings(Topology.EMPTY, Topology.EMPTY, new CommandStore[0], new Mapping[0]);
- final Topology cluster;
final CommandStore[] stores;
+ final KeyRanges ranges;
+
+ public StoreGroup(CommandStore[] stores, KeyRanges ranges)
+ {
+ this.stores = stores;
+ this.ranges = ranges;
+ }
+
+ private static class AccumulatingBitset extends BitSet implements Keys.KeyAccumulator<Keys>
+ {
+ final int numStores;
+ boolean isDone = false;
+ public AccumulatingBitset(int numStores)
+ {
+ super(numStores);
+ this.numStores = numStores;
+ }
+
+ @Override
+ public Keys accumulate(Key key, Keys keys)
+ {
+ int idx = keyIndex(key, numStores);
+ if (get(idx))
+ return keys;
+ set(idx);
+ isDone = cardinality() == numStores;
+ return keys;
+ }
+
+ @Override
+ public boolean isDone()
+ {
+ return isDone;
+ }
+ }
+
+ public Stream<CommandStore> stream()
+ {
+ return StreamSupport.stream(new ShardSpliterator(stores), false);
+ }
+
+ public Stream<CommandStore> stream(Keys keys)
+ {
+ AccumulatingBitset bitSet = new AccumulatingBitset(stores.length);
+ keys.accumulate(ranges, bitSet, keys);
+ if (bitSet.cardinality() == 0)
+ return null;
+ return StreamSupport.stream(new ShardSpliterator(stores, bitSet::get), false);
+ }
+
+ public Stream<CommandStore> stream(TxnRequest.Scope scope)
+ {
+ AccumulatingBitset bitSet = new AccumulatingBitset(stores.length);
+ for (int i=0, mi=scope.size(); i<mi; i++)
+ {
+ Keys keys = scope.get(i).keys;
+ keys.accumulate(ranges, bitSet, keys);
+ if (bitSet.isDone)
+ break;
+ }
+ if (bitSet.cardinality() == 0)
+ return null;
+ return StreamSupport.stream(new ShardSpliterator(stores, bitSet::get), false);
+ }
+ }
+
+ static int keyIndex(Key key, int numShards)
+ {
+ return (int) (Integer.toUnsignedLong(key.keyHash()) % numShards);
+ }
+
+ static class StoreGroups
+ {
+ static final StoreGroups EMPTY = new StoreGroups(new StoreGroup[0], Topology.EMPTY, Topology.EMPTY);
+ final StoreGroup[] groups;
+ final Topology global;
final Topology local;
- final Mapping[] mappings;
- public Mappings(Topology cluster, Topology local, CommandStore[] stores, Mapping[] mappings)
+ public StoreGroups(StoreGroup[] groups, Topology global, Topology local)
{
- Preconditions.checkArgument(stores.length == mappings.length);
- this.cluster = cluster;
+ this.groups = groups;
+ this.global = global;
this.local = local;
- this.stores = stores;
- this.mappings = mappings;
}
- int size()
+ StoreGroups withNewTopology(Topology global, Topology local)
+ {
+ return new StoreGroups(groups, global, local);
+ }
+
+ public Stream<CommandStore> stream()
+ {
+ Stream<CommandStore> stream = null;
+ for (StoreGroup group : groups)
+ {
+ Stream<CommandStore> nextStream = group.stream();
+ if (nextStream == null) continue;
+ stream = stream != null ? Stream.concat(stream, nextStream) : nextStream;
+ }
+
+ return stream != null ? stream : Stream.empty();
+ }
+
+ public Stream<CommandStore> stream(Keys keys)
{
- return stores.length;
+ Stream<CommandStore> stream = null;
+ for (StoreGroup group : groups)
+ {
+ Stream<CommandStore> nextStream = group.stream(keys);
+ if (nextStream == null) continue;
+ stream = stream != null ? Stream.concat(stream, nextStream) : nextStream;
+ }
+
+ return stream != null ? stream : Stream.empty();
}
- Mappings withNewTopology(Topology cluster, Topology local)
+ public Stream<CommandStore> stream(TxnRequest.Scope scope)
{
- return new Mappings(cluster, local, stores, Mapping.withNewLocalTopology(mappings, local));
+ Stream<CommandStore> stream = null;
+ for (StoreGroup group : groups)
+ {
+ Stream<CommandStore> nextStream = group.stream(scope);
+ if (nextStream == null) continue;
+ stream = stream != null ? Stream.concat(stream, nextStream) : nextStream;
+ }
+
+ return stream != null ? stream : Stream.empty();
}
}
private final Node.Id node;
- private final BiFunction<Integer, Mapping, CommandStore> shardFactory;
+ private final Function<Timestamp, Timestamp> uniqueNow;
+ private final Agent agent;
+ private final Store store;
+ private final CommandStore.Factory shardFactory;
private final int numShards;
- private volatile Mappings mappings = Mappings.EMPTY;
+ private volatile StoreGroups groups = StoreGroups.EMPTY;
public CommandStores(int num, Node.Id node, Function<Timestamp, Timestamp> uniqueNow, Agent agent, Store store, CommandStore.Factory shardFactory)
{
this.node = node;
this.numShards = num;
- this.shardFactory = (idx, mapping) -> shardFactory.create(idx, node, uniqueNow, agent, store, mapping, this::getRangeMapping);
+ this.uniqueNow = uniqueNow;
+ this.agent = agent;
+ this.store = store;
+ this.shardFactory = shardFactory;
+ }
+
+ private CommandStore createCommandStore(int generation, int index, KeyRanges ranges)
+ {
+ return shardFactory.create(generation, index, numShards, node, uniqueNow, agent, store, ranges, this::getLocalTopology);
}
- private Mapping getRangeMapping(int idx)
+ private Topology getLocalTopology()
{
- return mappings.mappings[idx];
+ return groups.local;
}
public synchronized void shutdown()
{
- for (CommandStore commandStore : mappings.stores)
- commandStore.shutdown();
+ for (StoreGroup group : groups.groups)
+ for (CommandStore commandStore : group.stores)
+ commandStore.shutdown();
}
public Stream<CommandStore> stream()
{
- return StreamSupport.stream(new ShardSpliterator(mappings.stores), false);
+ return groups.stream();
}
public Stream<CommandStore> forKeys(Keys keys)
{
- Mappings stores = mappings;
- IntPredicate predicate = i -> stores.mappings[i].ranges.intersects(keys);
- return StreamSupport.stream(new ShardSpliterator(stores.stores, predicate), false);
+ return groups.stream(keys);
}
public Stream<CommandStore> forScope(TxnRequest.Scope scope)
{
- Mappings stores = mappings;
- IntPredicate predicate = i -> scope.intersects(stores.mappings[i].ranges);
- return StreamSupport.stream(new ShardSpliterator(stores.stores, predicate), false);
- }
-
- static List<KeyRanges> shardRanges(KeyRanges ranges, int shards)
- {
- List<List<KeyRange>> sharded = new ArrayList<>(shards);
- for (int i=0; i<shards; i++)
- sharded.add(new ArrayList<>(ranges.size()));
-
- for (KeyRange range : ranges)
- {
- KeyRanges split = range.split(shards);
- Preconditions.checkState(split.size() <= shards);
- for (int i=0; i<split.size(); i++)
- sharded.get(i).add(split.get(i));
- }
-
- List<KeyRanges> result = new ArrayList<>(shards);
- for (int i=0; i<shards; i++)
- {
- result.add(new KeyRanges(sharded.get(i).toArray(KeyRange[]::new)));
- }
-
- return result;
+ return groups.stream(scope);
}
public synchronized void updateTopology(Topology cluster)
{
Preconditions.checkArgument(!cluster.isSubset(), "Use full topology for CommandStores.updateTopology");
- Mappings current = mappings;
- if (cluster.epoch() <= current.cluster.epoch())
+ StoreGroups current = groups;
+ if (cluster.epoch() <= current.global.epoch())
return;
Topology local = cluster.forNode(node);
- KeyRanges currentRanges = Arrays.stream(current.mappings).map(mapping -> mapping.ranges).reduce(KeyRanges.EMPTY, (l, r) -> l.union(r)).mergeTouching();
+ KeyRanges currentRanges = Arrays.stream(current.groups).map(group -> group.ranges).reduce(KeyRanges.EMPTY, (l, r) -> l.union(r)).mergeTouching();
KeyRanges added = local.ranges().difference(currentRanges);
if (added.isEmpty())
{
- mappings = mappings.withNewTopology(cluster, local);
+ groups = groups.withNewTopology(cluster, local);
return;
}
+ int newGeneration = current.groups.length;
+ StoreGroup[] newGroups = new StoreGroup[current.groups.length + 1];
+ CommandStore[] newStores = new CommandStore[numShards];
+ System.arraycopy(current.groups, 0, newGroups, 0, current.groups.length);
- List<KeyRanges> sharded = shardRanges(added, numShards);
- Mapping[] newMappings = new Mapping[current.size() + sharded.size()];
- CommandStore[] newStores = new CommandStore[current.size() + sharded.size()];
- Mapping.withNewLocalTopology(current.mappings, local, newMappings);
- System.arraycopy(current.stores, 0, newStores, 0, current.size());
+ for (int i=0; i<numShards; i++)
+ newStores[i] = createCommandStore(newGeneration, i, added);
- for (int i=0; i<sharded.size(); i++)
- {
- int idx = current.size() + i;
- Mapping mapping = new Mapping(sharded.get(i), local);
- newMappings[idx] = mapping;
- newStores[idx] = shardFactory.apply(idx, mapping);
- }
+ newGroups[current.groups.length] = new StoreGroup(newStores, added);
- mappings = new Mappings(cluster, local, newStores, newMappings);
+ groups = new StoreGroups(newGroups, cluster, local);
}
private static class ShardSpliterator implements Spliterator<CommandStore>
@@ -179,7 +263,7 @@ public class CommandStores
continue;
try
{
- commandStores[idx].process(action).toCompletableFuture().get();
+ commandStores[idx].process(action).get();
break;
}
catch (InterruptedException | ExecutionException e)
@@ -197,11 +281,11 @@ public class CommandStores
if (i >= commandStores.length)
return;
- List<CompletableFuture<Void>> futures = new ArrayList<>(commandStores.length - i);
+ List<Future<Void>> futures = new ArrayList<>(commandStores.length - i);
for (; i< commandStores.length; i++)
{
if (predicate.test(i))
- futures.add(commandStores[i].process(action).toCompletableFuture());
+ futures.add(commandStores[i].process(action));
}
try
diff --git a/accord-core/src/main/java/accord/local/Node.java b/accord-core/src/main/java/accord/local/Node.java
index 37168cb..9a37a03 100644
--- a/accord-core/src/main/java/accord/local/Node.java
+++ b/accord-core/src/main/java/accord/local/Node.java
@@ -1,8 +1,6 @@
package accord.local;
import java.util.*;
-import java.util.concurrent.CompletableFuture;
-import java.util.concurrent.CompletionStage;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
@@ -14,6 +12,10 @@ import java.util.stream.Stream;
import accord.api.*;
import accord.coordinate.Coordinate;
import accord.messages.*;
+import accord.messages.Callback;
+import accord.messages.ReplyContext;
+import accord.messages.Request;
+import accord.messages.Reply;
import accord.topology.Shard;
import accord.topology.Topology;
import accord.topology.TopologyManager;
@@ -21,6 +23,7 @@ import accord.txn.Keys;
import accord.txn.Timestamp;
import accord.txn.Txn;
import accord.txn.TxnId;
+import org.apache.cassandra.utils.concurrent.Future;
public class Node implements ConfigurationService.Listener
{
@@ -83,7 +86,7 @@ public class Node implements ConfigurationService.Listener
// TODO: this really needs to be thought through some more, as it needs to be per-instance in some cases, and per-node in others
private final Scheduler scheduler;
- private final Map<TxnId, CompletionStage<Result>> coordinating = new ConcurrentHashMap<>();
+ private final Map<TxnId, Future<Result>> coordinating = new ConcurrentHashMap<>();
private final Set<TxnId> pendingRecovery = Collections.newSetFromMap(new ConcurrentHashMap<>());
public Node(Id id, MessageSink messageSink, ConfigurationService configService, LongSupplier nowSupplier,
@@ -266,9 +269,9 @@ public class Node implements ConfigurationService.Listener
messageSink.send(to, send);
}
- public void reply(Id replyingToNode, long replyingToMessage, Reply send)
+ public void reply(Id replyingToNode, ReplyContext replyContext, Reply send)
{
- messageSink.reply(replyingToNode, replyingToMessage, send);
+ messageSink.reply(replyingToNode, replyContext, send);
}
public TxnId nextTxnId()
@@ -276,30 +279,29 @@ public class Node implements ConfigurationService.Listener
return new TxnId(uniqueNow());
}
- public CompletionStage<Result> coordinate(TxnId txnId, Txn txn)
+ public Future<Result> coordinate(TxnId txnId, Txn txn)
{
// TODO: The combination of updating the epoch of the next timestamp with epochs we don’t have topologies for,
// and requiring preaccept to talk to its topology epoch means that learning of a new epoch via timestamp
// (ie not via config service) will halt any new txns from a node until it receives this topology
if (txnId.epoch > configService.currentEpoch())
- return configService.fetchTopologyForEpochStage(txnId.epoch).thenCompose(v -> coordinate(txnId, txn));
+ return configService.fetchTopologyForEpoch(txnId.epoch).flatMap(v -> coordinate(txnId, txn));
- CompletionStage<Result> result = Coordinate.execute(this, txnId, txn);
+ Future<Result> result = Coordinate.execute(this, txnId, txn);
coordinating.put(txnId, result);
// TODO (now): error handling
- result.handle((success, fail) ->
- {
- coordinating.remove(txnId);
- // if we don't succeed, try again in 30s to make sure somebody finishes it
- // TODO: this is an ugly liveness mechanism
- if (fail != null && pendingRecovery.add(txnId))
- scheduler.once(() -> { pendingRecovery.remove(txnId); recover(txnId, txn); } , 30L, TimeUnit.SECONDS);
- return null;
- });
+ result.addCallback((success, fail) ->
+ {
+ coordinating.remove(txnId);
+ // if we don't succeed, try again in 30s to make sure somebody finishes it
+ // TODO: this is an ugly liveness mechanism
+ if (fail != null && pendingRecovery.add(txnId))
+ scheduler.once(() -> { pendingRecovery.remove(txnId); recover(txnId, txn); } , 30L, TimeUnit.SECONDS);
+ });
return result;
}
- public CompletionStage<Result> coordinate(Txn txn)
+ public Future<Result> coordinate(Txn txn)
{
return coordinate(nextTxnId(), txn);
}
@@ -309,43 +311,42 @@ public class Node implements ConfigurationService.Listener
{
if (txnId.epoch > configService.currentEpoch())
{
- configService.fetchTopologyForEpoch(txnId.epoch, () -> recover(txnId, txn));
+ configService.fetchTopologyForEpoch(txnId.epoch).addListener(() -> recover(txnId, txn));
return;
}
- CompletionStage<Result> result = coordinating.get(txnId);
+ Future<Result> result = coordinating.get(txnId);
if (result != null)
return;
if (txnId.epoch > topology().epoch())
{
- configService().fetchTopologyForEpoch(txnId.epoch, () -> recover(txnId, txn));
+ configService().fetchTopologyForEpoch(txnId.epoch).addListener(() -> recover(txnId, txn));
return;
}
result = Coordinate.recover(this, txnId, txn);
coordinating.putIfAbsent(txnId, result);
// TODO (now): error handling
- result.handle((success, fail) -> {
- coordinating.remove(txnId);
- agent.onRecover(this, success, fail);
- // if we don't succeed, try again in 30s to make sure somebody finishes it
- // TODO: this is an ugly liveness mechanism
- if (fail != null && pendingRecovery.add(txnId))
- scheduler.once(() -> { pendingRecovery.remove(txnId); recover(txnId, txn); } , 30L, TimeUnit.SECONDS);
- return null;
+ result.addCallback((success, fail) -> {
+ coordinating.remove(txnId);
+ agent.onRecover(this, success, fail);
+ // if we don't succeed, try again in 30s to make sure somebody finishes it
+ // TODO: this is an ugly liveness mechanism
+ if (fail != null && pendingRecovery.add(txnId))
+ scheduler.once(() -> { pendingRecovery.remove(txnId); recover(txnId, txn); } , 30L, TimeUnit.SECONDS);
});
}
- public void receive(Request request, Id from, long messageId)
+ public void receive(Request request, Id from, ReplyContext replyContext)
{
long unknownEpoch = topology().maxUnknownEpoch(request);
if (unknownEpoch > 0)
{
- configService.fetchTopologyForEpoch(unknownEpoch, () -> receive(request, from, messageId));
+ configService.fetchTopologyForEpoch(unknownEpoch).addListener(() -> receive(request, from, replyContext));
return;
}
- scheduler.now(() -> request.process(this, from, messageId));
+ scheduler.now(() -> request.process(this, from, replyContext));
}
public Scheduler scheduler()
diff --git a/accord-core/src/main/java/accord/messages/Accept.java b/accord-core/src/main/java/accord/messages/Accept.java
index 3a3a5ac..a9c581a 100644
--- a/accord-core/src/main/java/accord/messages/Accept.java
+++ b/accord-core/src/main/java/accord/messages/Accept.java
@@ -34,9 +34,9 @@ public class Accept extends TxnRequest
this(Scope.forTopologies(dst, topologies, txn), ballot, txnId, txn, executeAt, deps);
}
- public void process(Node on, Node.Id replyToNode, long replyToMessage)
+ public void process(Node on, Node.Id replyToNode, ReplyContext replyContext)
{
- on.reply(replyToNode, replyToMessage, on.local(scope()).map(instance -> {
+ on.reply(replyToNode, replyContext, on.local(scope()).map(instance -> {
Command command = instance.command(txnId);
if (!command.accept(ballot, txn, executeAt, deps))
return new AcceptNack(txnId, command.promised());
@@ -53,8 +53,20 @@ public class Accept extends TxnRequest
}).orElseThrow());
}
+ @Override
+ public MessageType type()
+ {
+ return MessageType.ACCEPT_REQ;
+ }
+
public interface AcceptReply extends Reply
{
+ @Override
+ default MessageType type()
+ {
+ return MessageType.ACCEPT_RSP;
+ }
+
boolean isOK();
}
diff --git a/accord-core/src/main/java/accord/messages/Apply.java b/accord-core/src/main/java/accord/messages/Apply.java
index 4e9b328..7f296e6 100644
--- a/accord-core/src/main/java/accord/messages/Apply.java
+++ b/accord-core/src/main/java/accord/messages/Apply.java
@@ -12,13 +12,13 @@ import accord.txn.TxnId;
public class Apply extends TxnRequest
{
- final TxnId txnId;
- final Txn txn;
+ public final TxnId txnId;
+ public final Txn txn;
// TODO: these only need to be sent if we don't know if this node has witnessed a Commit
- final Dependencies deps;
- final Timestamp executeAt;
- final Writes writes;
- final Result result;
+ public final Dependencies deps;
+ public final Timestamp executeAt;
+ public final Writes writes;
+ public final Result result;
public Apply(Scope scope, TxnId txnId, Txn txn, Timestamp executeAt, Dependencies deps, Writes writes, Result result)
{
@@ -36,11 +36,17 @@ public class Apply extends TxnRequest
this(Scope.forTopologies(to, topologies, txn), txnId, txn, executeAt, deps, writes, result);
}
- public void process(Node node, Id replyToNode, long replyToMessage)
+ public void process(Node node, Id replyToNode, ReplyContext replyContext)
{
node.local(scope()).forEach(instance -> instance.command(txnId).apply(txn, deps, executeAt, writes, result));
}
+ @Override
+ public MessageType type()
+ {
+ return MessageType.APPLY_REQ;
+ }
+
@Override
public String toString()
{
diff --git a/accord-core/src/main/java/accord/messages/BeginRecovery.java b/accord-core/src/main/java/accord/messages/BeginRecovery.java
index a3c10bf..4d6e2e5 100644
--- a/accord-core/src/main/java/accord/messages/BeginRecovery.java
+++ b/accord-core/src/main/java/accord/messages/BeginRecovery.java
@@ -24,9 +24,9 @@ import static accord.messages.PreAccept.calculateDeps;
public class BeginRecovery extends TxnRequest
{
- final TxnId txnId;
- final Txn txn;
- final Ballot ballot;
+ public final TxnId txnId;
+ public final Txn txn;
+ public final Ballot ballot;
public BeginRecovery(Scope scope, TxnId txnId, Txn txn, Ballot ballot)
{
@@ -41,7 +41,7 @@ public class BeginRecovery extends TxnRequest
this(Scope.forTopologies(to, topologies, txn), txnId, txn, ballot);
}
- public void process(Node node, Id replyToNode, long replyToMessage)
+ public void process(Node node, Id replyToNode, ReplyContext replyContext)
{
RecoverReply reply = node.local(scope()).map(instance -> {
Command command = instance.command(txnId);
@@ -142,7 +142,7 @@ public class BeginRecovery extends TxnRequest
ok1.writes, ok1.result);
}).orElseThrow();
- node.reply(replyToNode, replyToMessage, reply);
+ node.reply(replyToNode, replyContext, reply);
if (reply instanceof RecoverOk && ((RecoverOk) reply).status == Applied)
{
// disseminate directly
@@ -150,7 +150,7 @@ public class BeginRecovery extends TxnRequest
ConfigurationService configService = node.configService();
if (ok.executeAt.epoch > configService.currentEpoch())
{
- configService.fetchTopologyForEpoch(ok.executeAt.epoch, () -> disseminateApply(node, ok));
+ configService.fetchTopologyForEpoch(ok.executeAt.epoch).addListener(() -> disseminateApply(node, ok));
return;
}
disseminateApply(node, ok);
@@ -163,9 +163,21 @@ public class BeginRecovery extends TxnRequest
Topologies topologies = node.topology().forKeys(txn.keys, ok.executeAt.epoch);
node.send(topologies.nodes(), to -> new Apply(to, topologies, txnId, txn, ok.executeAt, ok.deps, ok.writes, ok.result));
}
+
+ @Override
+ public MessageType type()
+ {
+ return MessageType.RECOVER_REQ;
+ }
public interface RecoverReply extends Reply
{
+ @Override
+ default MessageType type()
+ {
+ return MessageType.RECOVER_RSP;
+ }
+
boolean isOK();
}
@@ -182,7 +194,7 @@ public class BeginRecovery extends TxnRequest
public final Writes writes;
public final Result result;
- RecoverOk(TxnId txnId, Status status, Ballot accepted, Timestamp executeAt, Dependencies deps, Dependencies earlierCommittedWitness, Dependencies earlierAcceptedNoWitness, boolean rejectsFastPath, Writes writes, Result result)
+ public RecoverOk(TxnId txnId, Status status, Ballot accepted, Timestamp executeAt, Dependencies deps, Dependencies earlierCommittedWitness, Dependencies earlierAcceptedNoWitness, boolean rejectsFastPath, Writes writes, Result result)
{
this.txnId = txnId;
this.accepted = accepted;
@@ -222,8 +234,8 @@ public class BeginRecovery extends TxnRequest
public static class RecoverNack implements RecoverReply
{
- final Ballot supersededBy;
- private RecoverNack(Ballot supersededBy)
+ public final Ballot supersededBy;
+ public RecoverNack(Ballot supersededBy)
{
this.supersededBy = supersededBy;
}
diff --git a/accord-core/src/main/java/accord/messages/Commit.java b/accord-core/src/main/java/accord/messages/Commit.java
index 16cba6f..57d13e2 100644
--- a/accord-core/src/main/java/accord/messages/Commit.java
+++ b/accord-core/src/main/java/accord/messages/Commit.java
@@ -11,8 +11,8 @@ import accord.txn.TxnId;
// TODO: CommitOk responses, so we can send again if no reply received? Or leave to recovery?
public class Commit extends ReadData
{
- final Dependencies deps;
- final boolean read;
+ public final Dependencies deps;
+ public final boolean read;
public Commit(Scope scope, TxnId txnId, Txn txn, Timestamp executeAt, Dependencies deps, boolean read)
{
@@ -26,10 +26,16 @@ public class Commit extends ReadData
this(Scope.forTopologies(to, topologies, txn), txnId, txn, executeAt, deps, read);
}
- public void process(Node node, Id from, long messageId)
+ public void process(Node node, Id from, ReplyContext replyContext)
{
node.local(scope()).forEach(instance -> instance.command(txnId).commit(txn, deps, executeAt));
- if (read) super.process(node, from, messageId);
+ if (read) super.process(node, from, replyContext);
+ }
+
+ @Override
+ public MessageType type()
+ {
+ return MessageType.COMMIT_REQ;
}
@Override
diff --git a/accord-core/src/main/java/accord/messages/Message.java b/accord-core/src/main/java/accord/messages/Message.java
index 928fcc7..7bba983 100644
--- a/accord-core/src/main/java/accord/messages/Message.java
+++ b/accord-core/src/main/java/accord/messages/Message.java
@@ -2,4 +2,5 @@ package accord.messages;
public interface Message
{
+ MessageType type();
}
diff --git a/accord-core/src/main/java/accord/messages/MessageType.java b/accord-core/src/main/java/accord/messages/MessageType.java
new file mode 100644
index 0000000..c60b35d
--- /dev/null
+++ b/accord-core/src/main/java/accord/messages/MessageType.java
@@ -0,0 +1,20 @@
+package accord.messages;
+
+/**
+ * meant to assist implementations map accord messages to their own messaging systems
+ */
+public enum MessageType
+{
+ PREACCEPT_REQ,
+ PREACCEPT_RSP,
+ ACCEPT_REQ,
+ ACCEPT_RSP,
+ COMMIT_REQ,
+ APPLY_REQ,
+ READ_REQ,
+ READ_RSP,
+ RECOVER_REQ,
+ RECOVER_RSP,
+ WAIT_ON_COMMIT_REQ,
+ WAIT_ON_COMMIT_RSP
+}
diff --git a/accord-core/src/main/java/accord/messages/PreAccept.java b/accord-core/src/main/java/accord/messages/PreAccept.java
index e6d4d6a..0dcfe4b 100644
--- a/accord-core/src/main/java/accord/messages/PreAccept.java
+++ b/accord-core/src/main/java/accord/messages/PreAccept.java
@@ -31,9 +31,9 @@ public class PreAccept extends TxnRequest
this(Scope.forTopologies(to, topologies, txn), txnId, txn);
}
- public void process(Node node, Id from, long messageId)
+ public void process(Node node, Id from, ReplyContext replyContext)
{
- node.reply(from, messageId, node.local(scope()).map(instance -> {
+ node.reply(from, replyContext, node.local(scope()).map(instance -> {
// note: this diverges from the paper, in that instead of waiting for JoinShard,
// we PreAccept to both old and new topologies and require quorums in both.
// This necessitates sending to ALL replicas of old topology, not only electorate (as fast path may be unreachable).
@@ -53,8 +53,20 @@ public class PreAccept extends TxnRequest
}).orElseThrow());
}
+ @Override
+ public MessageType type()
+ {
+ return MessageType.PREACCEPT_REQ;
+ }
+
public interface PreAcceptReply extends Reply
{
+ @Override
+ default MessageType type()
+ {
+ return MessageType.PREACCEPT_RSP;
+ }
+
boolean isOK();
}
diff --git a/accord-core/src/main/java/accord/messages/ReadData.java b/accord-core/src/main/java/accord/messages/ReadData.java
index 77f1ee0..e35d4bc 100644
--- a/accord-core/src/main/java/accord/messages/ReadData.java
+++ b/accord-core/src/main/java/accord/messages/ReadData.java
@@ -11,6 +11,7 @@ import accord.local.Node.Id;
import accord.api.Data;
import accord.topology.KeyRanges;
import accord.topology.Topologies;
+import accord.txn.Keys;
import accord.txn.Txn;
import accord.txn.TxnId;
import accord.txn.Timestamp;
@@ -24,19 +25,21 @@ public class ReadData extends TxnRequest
final TxnId txnId;
final Node node;
final Node.Id replyToNode;
- final long replyToMessage;
+ final Keys keyScope;
+ final ReplyContext replyContext;
Data data;
boolean isObsolete; // TODO: respond with the Executed result we have stored?
Set<CommandStore> waitingOn;
Scheduled waitingOnReporter;
- LocalRead(TxnId txnId, Node node, Id replyToNode, long replyToMessage)
+ LocalRead(TxnId txnId, Node node, Id replyToNode, Keys keyScope, ReplyContext replyContext)
{
this.txnId = txnId;
this.node = node;
this.replyToNode = replyToNode;
- this.replyToMessage = replyToMessage;
+ this.keyScope = keyScope;
+ this.replyContext = replyContext;
// TODO: this is messy, we want a complete separate liveness mechanism that ensures progress for all transactions
this.waitingOnReporter = node.scheduler().once(new ReportWaiting(), 1L, TimeUnit.SECONDS);
}
@@ -59,7 +62,7 @@ public class ReadData extends TxnRequest
if (blockedBy == null) return;
blockedBy.addListener(this);
assert blockedBy.status().compareTo(Status.NotWitnessed) > 0;
- node.reply(replyToNode, replyToMessage, new ReadWaiting(txnId, blockedBy.txnId(), blockedBy.txn(), blockedBy.executeAt(), blockedBy.status()));
+ node.reply(replyToNode, replyContext, new ReadWaiting(txnId, blockedBy.txnId(), blockedBy.txn(), blockedBy.executeAt(), blockedBy.status()));
}
}
@@ -88,14 +91,14 @@ public class ReadData extends TxnRequest
private void read(Command command)
{
// TODO: threading/futures (don't want to perform expensive reads within this mutually exclusive context)
- Data next = command.txn().read(command);
+ Data next = command.txn().read(command, keyScope);
data = data == null ? next : data.merge(next);
waitingOn.remove(command.commandStore);
if (waitingOn.isEmpty())
{
waitingOnReporter.cancel();
- node.reply(replyToNode, replyToMessage, new ReadOk(data));
+ node.reply(replyToNode, replyContext, new ReadOk(data));
}
}
@@ -114,7 +117,7 @@ public class ReadData extends TxnRequest
});
// FIXME: this may result in redundant messages being sent when a shard is split across several command shards
node.send(nodes, to -> new Apply(to, topologies, command.txnId(), command.txn(), command.executeAt(), command.savedDeps(), command.writes(), command.result()));
- node.reply(replyToNode, replyToMessage, new ReadNack());
+ node.reply(replyToNode, replyContext, new ReadNack());
}
}
@@ -149,9 +152,9 @@ public class ReadData extends TxnRequest
}
}
- final TxnId txnId;
- final Txn txn;
- final Timestamp executeAt;
+ public final TxnId txnId;
+ public final Txn txn;
+ public final Timestamp executeAt;
public ReadData(Scope scope, TxnId txnId, Txn txn, Timestamp executeAt)
{
@@ -166,13 +169,25 @@ public class ReadData extends TxnRequest
this(Scope.forTopologies(to, topologies, txn), txnId, txn, executeAt);
}
- public void process(Node node, Node.Id from, long messageId)
+ public void process(Node node, Node.Id from, ReplyContext replyContext)
{
- new LocalRead(txnId, node, from, messageId).setup(txnId, txn, scope());
+ new LocalRead(txnId, node, from, scope().keys(), replyContext).setup(txnId, txn, scope());
+ }
+
+ @Override
+ public MessageType type()
+ {
+ return MessageType.READ_REQ;
}
public static class ReadReply implements Reply
{
+ @Override
+ public MessageType type()
+ {
+ return MessageType.READ_RSP;
+ }
+
public boolean isOK()
{
return true;
diff --git a/accord-core/src/main/java/accord/messages/Message.java b/accord-core/src/main/java/accord/messages/ReplyContext.java
similarity index 50%
copy from accord-core/src/main/java/accord/messages/Message.java
copy to accord-core/src/main/java/accord/messages/ReplyContext.java
index 928fcc7..7ba23f1 100644
--- a/accord-core/src/main/java/accord/messages/Message.java
+++ b/accord-core/src/main/java/accord/messages/ReplyContext.java
@@ -1,5 +1,5 @@
package accord.messages;
-public interface Message
+public interface ReplyContext
{
}
diff --git a/accord-core/src/main/java/accord/messages/Request.java b/accord-core/src/main/java/accord/messages/Request.java
index 50ffbd5..8899bd9 100644
--- a/accord-core/src/main/java/accord/messages/Request.java
+++ b/accord-core/src/main/java/accord/messages/Request.java
@@ -5,5 +5,5 @@ import accord.local.Node.Id;
public interface Request extends Message
{
- void process(Node on, Id from, long messageId);
+ void process(Node on, Id from, ReplyContext replyContext);
}
diff --git a/accord-core/src/main/java/accord/messages/TxnRequest.java b/accord-core/src/main/java/accord/messages/TxnRequest.java
index 2d74fce..606825b 100644
--- a/accord-core/src/main/java/accord/messages/TxnRequest.java
+++ b/accord-core/src/main/java/accord/messages/TxnRequest.java
@@ -79,22 +79,22 @@ public abstract class TxnRequest implements Request
}
private final long maxEpoch;
- private final KeysForEpoch[] ranges;
+ private final KeysForEpoch[] epochs;
public Scope(long maxEpoch, KeysForEpoch... epochKeys)
{
this.maxEpoch = maxEpoch;
- this.ranges = epochKeys;
+ this.epochs = epochKeys;
}
public int size()
{
- return ranges.length;
+ return epochs.length;
}
public KeysForEpoch get(int i)
{
- return ranges[i];
+ return epochs[i];
}
public static Scope forTopologies(Node.Id node, Topologies topologies, Keys keys)
@@ -125,7 +125,7 @@ public abstract class TxnRequest implements Request
public boolean intersects(KeyRanges ranges)
{
- for (KeysForEpoch keysForEpoch : this.ranges)
+ for (KeysForEpoch keysForEpoch : this.epochs)
{
if (ranges.intersects(keysForEpoch.keys))
return true;
@@ -134,20 +134,28 @@ public abstract class TxnRequest implements Request
return false;
}
+ public Keys keys()
+ {
+ Keys keys = epochs[0].keys;
+ for (int i = 1; i< epochs.length; i++)
+ keys = keys.merge(epochs[i].keys);
+ return keys;
+ }
+
@Override
public boolean equals(Object o)
{
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Scope that = (Scope) o;
- return maxEpoch == that.maxEpoch && Arrays.equals(ranges, that.ranges);
+ return maxEpoch == that.maxEpoch && Arrays.equals(epochs, that.epochs);
}
@Override
public int hashCode()
{
int result = Objects.hash(maxEpoch);
- result = 31 * result + Arrays.hashCode(ranges);
+ result = 31 * result + Arrays.hashCode(epochs);
return result;
}
@@ -155,7 +163,7 @@ public abstract class TxnRequest implements Request
public String toString()
{
return "TxnRequestScope{" +
- "ranges=" + Arrays.toString(ranges) +
+ "epochs=" + Arrays.toString(epochs) +
'}';
}
}
diff --git a/accord-core/src/main/java/accord/messages/WaitOnCommit.java b/accord-core/src/main/java/accord/messages/WaitOnCommit.java
index c6b8ad4..a09324f 100644
--- a/accord-core/src/main/java/accord/messages/WaitOnCommit.java
+++ b/accord-core/src/main/java/accord/messages/WaitOnCommit.java
@@ -17,16 +17,16 @@ public class WaitOnCommit extends TxnRequest
final Node node;
final Id replyToNode;
final TxnId txnId;
- final long replyToMessage;
+ final ReplyContext replyContext;
final AtomicInteger waitingOn = new AtomicInteger();
- LocalWait(Node node, Id replyToNode, TxnId txnId, long replyToMessage)
+ LocalWait(Node node, Id replyToNode, TxnId txnId, ReplyContext replyContext)
{
this.node = node;
this.replyToNode = replyToNode;
this.txnId = txnId;
- this.replyToMessage = replyToMessage;
+ this.replyContext = replyContext;
}
@Override
@@ -54,7 +54,7 @@ public class WaitOnCommit extends TxnRequest
private void ack()
{
if (waitingOn.decrementAndGet() == 0)
- node.reply(replyToNode, replyToMessage, new WaitOnCommitOk());
+ node.reply(replyToNode, replyContext, WaitOnCommitOk.INSTANCE);
}
void process(CommandStore instance)
@@ -84,8 +84,8 @@ public class WaitOnCommit extends TxnRequest
}
}
- final TxnId txnId;
- final Keys keys;
+ public final TxnId txnId;
+ public final Keys keys;
public WaitOnCommit(Scope scope, TxnId txnId, Keys keys)
{
@@ -99,12 +99,27 @@ public class WaitOnCommit extends TxnRequest
this(Scope.forTopologies(to, topologies, keys), txnId, keys);
}
- public void process(Node node, Id replyToNode, long replyToMessage)
+ public void process(Node node, Id replyToNode, ReplyContext replyContext)
{
- new LocalWait(node, replyToNode, txnId, replyToMessage).setup(keys);
+ new LocalWait(node, replyToNode, txnId, replyContext).setup(keys);
+ }
+
+ @Override
+ public MessageType type()
+ {
+ return MessageType.WAIT_ON_COMMIT_REQ;
}
public static class WaitOnCommitOk implements Reply
{
+ public static final WaitOnCommitOk INSTANCE = new WaitOnCommitOk();
+
+ private WaitOnCommitOk() {}
+
+ @Override
+ public MessageType type()
+ {
+ return MessageType.WAIT_ON_COMMIT_RSP;
+ }
}
}
diff --git a/accord-core/src/main/java/accord/txn/Keys.java b/accord-core/src/main/java/accord/txn/Keys.java
index e28377b..cf6388b 100644
--- a/accord-core/src/main/java/accord/txn/Keys.java
+++ b/accord-core/src/main/java/accord/txn/Keys.java
@@ -1,12 +1,14 @@
package accord.txn;
import java.util.*;
+import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import accord.api.Key;
import accord.api.KeyRange;
import accord.topology.KeyRanges;
+import com.google.common.base.Preconditions;
@SuppressWarnings("rawtypes")
public class Keys implements Iterable<Key>
@@ -65,6 +67,50 @@ public class Keys implements Iterable<Key>
return new Keys(selection);
}
+ public Keys merge(Keys that)
+ {
+ int thisIdx = 0;
+ int thatIdx = 0;
+ Key[] result = new Key[this.size() + that.size()];
+ int resultSize = 0;
+
+ while (thisIdx < this.size() && thatIdx < that.size())
+ {
+ Key thisKey = this.keys[thisIdx];
+ Key thatKey = that.keys[thatIdx];
+ int cmp = thisKey.compareTo(thatKey);
+ Key minKey;
+ if (cmp == 0)
+ {
+ minKey = thisKey;
+ thisIdx++;
+ thatIdx++;
+ }
+ else if (cmp < 0)
+ {
+ minKey = thisKey;
+ thisIdx++;
+ }
+ else
+ {
+ minKey = thatKey;
+ thatIdx++;
+ }
+ result[resultSize++] = minKey;
+ }
+
+ while (thisIdx < this.size())
+ result[resultSize++] = this.keys[thisIdx++];
+
+ while (thatIdx < that.size())
+ result[resultSize++] = that.keys[thatIdx++];
+
+ if (resultSize < result.length)
+ result = Arrays.copyOf(result, resultSize);
+
+ return new Keys(result);
+ }
+
public boolean isEmpty()
{
return keys.length == 0;
@@ -179,5 +225,96 @@ public class Keys implements Iterable<Key>
return result != null ? new Keys(result) : EMPTY;
}
+ public interface KeyAccumulator<V>
+ {
+ V accumulate(Key key, V value);
+ default boolean isDone()
+ {
+ return false;
+ }
+ }
+ /**
+ * Count the number of keys matching the predicate and intersecting with the given ranges.
+ * If terminateAfter is greater than 0, the method will return once terminateAfter matches are encountered
+ */
+ public <V> V accumulate(KeyRanges ranges, KeyAccumulator<V> accumulator, V value)
+ {
+ int keyLB = 0;
+ int keyHB = size();
+ int rangeLB = 0;
+ int rangeHB = ranges.rangeIndexForKey(keys[keyHB-1]);
+ rangeHB = rangeHB < 0 ? -1 - rangeHB : rangeHB + 1;
+
+ for (;rangeLB<rangeHB && keyLB<keyHB;)
+ {
+ Key key = keys[keyLB];
+ rangeLB = ranges.rangeIndexForKey(rangeLB, ranges.size(), key);
+
+ if (rangeLB < 0)
+ {
+ rangeLB = -1 -rangeLB;
+ if (rangeLB >= rangeHB)
+ break;
+ keyLB = ranges.get(rangeLB).lowKeyIndex(this, keyLB, keyHB);
+ }
+ else
+ {
+ KeyRange<?> range = ranges.get(rangeLB);
+ int highKey = range.higherKeyIndex(this, keyLB, keyHB);
+
+ for (int i=keyLB; i<highKey; i++)
+ {
+ value = accumulator.accumulate(keys[i], value);
+ if (accumulator.isDone())
+ return value;
+ }
+
+ keyLB = highKey;
+ rangeLB++;
+ }
+
+ if (keyLB < 0)
+ keyLB = -1 - keyLB;
+ }
+
+ return value;
+ }
+
+ public <V> V accumulate(KeyRanges ranges, KeyAccumulator<V> accumulator)
+ {
+ return accumulate(ranges, accumulator, null);
+ }
+
+ private static class TerminatingKeyAccumulator<V> implements KeyAccumulator<V>
+ {
+ private boolean isDone = false;
+ private final Predicate<Key> predicate;
+
+ public TerminatingKeyAccumulator(Predicate<Key> predicate)
+ {
+ this.predicate = predicate;
+ }
+
+ @Override
+ final public V accumulate(Key key, V value)
+ {
+ Preconditions.checkState(!isDone);
+ isDone = predicate.test(key);
+ return value;
+ }
+
+ @Override
+ final public boolean isDone()
+ {
+ return isDone;
+ }
+ }
+
+ public boolean any(KeyRanges ranges, Predicate<Key> predicate)
+ {
+ TerminatingKeyAccumulator<Void> accumulator = new TerminatingKeyAccumulator<>(predicate);
+ accumulate(ranges, accumulator, null);
+ return accumulator.isDone();
+ }
}
diff --git a/accord-core/src/main/java/accord/txn/Txn.java b/accord-core/src/main/java/accord/txn/Txn.java
index 75c96d8..9466a1c 100644
--- a/accord-core/src/main/java/accord/txn/Txn.java
+++ b/accord-core/src/main/java/accord/txn/Txn.java
@@ -88,15 +88,16 @@ public class Txn
return "read:" + read.toString() + (update != null ? ", update:" + update : "");
}
- public Data read(KeyRanges range, Store store)
+ public Data read(Command command, Keys keyScope)
{
- return read.read(range, store);
- }
+ return keyScope.accumulate(command.commandStore.ranges(), (key, accumulate) -> {
+ CommandStore commandStore = command.commandStore;
+ if (!commandStore.hashIntersects(key))
+ return accumulate;
- public Data read(Command command)
- {
- CommandStore commandStore = command.commandStore;
- return read(commandStore.ranges(), commandStore.store());
+ Data result = read.read(key, command.executeAt(), commandStore.store());
+ return accumulate != null ? accumulate.merge(result) : result;
+ });
}
public Timestamp maxConflict(CommandStore commandStore)
diff --git a/accord-core/src/main/java/accord/txn/Writes.java b/accord-core/src/main/java/accord/txn/Writes.java
index 42d7a88..019ed8b 100644
--- a/accord-core/src/main/java/accord/txn/Writes.java
+++ b/accord-core/src/main/java/accord/txn/Writes.java
@@ -18,8 +18,14 @@ public class Writes
public void apply(CommandStore commandStore)
{
- if (write != null)
- write.apply(commandStore.ranges(), executeAt, commandStore.store());
+ if (write == null)
+ return;
+
+ keys.accumulate(commandStore.ranges(), (key, accumulate) -> {
+ if (commandStore.hashIntersects(key))
+ write.apply(key, executeAt, commandStore.store());
+ return accumulate;
+ });
}
@Override
diff --git a/accord-core/src/main/java/org/apache/cassandra/concurrent/ExecutionFailure.java b/accord-core/src/main/java/org/apache/cassandra/concurrent/ExecutionFailure.java
new file mode 100644
index 0000000..a38820f
--- /dev/null
+++ b/accord-core/src/main/java/org/apache/cassandra/concurrent/ExecutionFailure.java
@@ -0,0 +1,180 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.concurrent;
+
+//import org.apache.cassandra.db.compaction.CompactionInterruptedException;
+//import org.apache.cassandra.utils.Closeable;
+//import org.apache.cassandra.utils.JVMStabilityInspector;
+//import org.apache.cassandra.utils.WithResources;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.concurrent.Callable;
+import java.util.concurrent.Future;
+
+///**
+// * Standardised handling of failures during execution - mostly this involves invoking a thread's
+// * {@link Thread.UncaughtExceptionHandler} or
+// * {@link JVMStabilityInspector#uncaughtException(Thread, Throwable)},
+// * with special handling for {@link CompactionInterruptedException}.
+// * This class also provides wrappers for {@link WithResources} with {@link Runnable} and {@link Callable}.
+// */
+public class ExecutionFailure
+{
+ private static final Logger logger = LoggerFactory.getLogger(ExecutionFailure.class);
+
+// /**
+// * Invoke the relevant {@link Thread.UncaughtExceptionHandler},
+// * ignoring (except for logging) any {@link CompactionInterruptedException}
+// */
+ public static void handle(Throwable t)
+ {
+ try
+ {
+// if (t instanceof CompactionInterruptedException)
+// {
+// // TODO: should we check to see there aren't nested CompactionInterruptedException?
+// logger.info(t.getMessage());
+// if (t.getSuppressed() != null && t.getSuppressed().length > 0)
+// logger.warn("Interruption of compaction encountered exceptions:", t);
+// else
+// logger.trace("Full interruption stack trace:", t);
+// }
+// else
+// {
+// Thread thread = Thread.currentThread();
+// Thread.UncaughtExceptionHandler handler = thread.getUncaughtExceptionHandler();
+// if (handler == null || handler.equals(thread.getThreadGroup()))
+// handler = JVMStabilityInspector::uncaughtException;
+// handler.uncaughtException(thread, t);
+// }
+ Thread thread = Thread.currentThread();
+ thread.getUncaughtExceptionHandler().uncaughtException(thread, t);
+ }
+ catch (Throwable shouldNeverHappen)
+ {
+ logger.error("Unexpected error while handling unexpected error", shouldNeverHappen);
+ }
+ }
+
+// /**
+// * See {@link #propagating(WithResources, Runnable)}
+// */
+// static Runnable propagating(Runnable wrap)
+// {
+// return wrap instanceof FutureTask<?> ? wrap : propagating(WithResources.none(), wrap);
+// }
+//
+// /**
+// * In the case of plain executions, we want to handle exceptions without the full {@link FutureTask} machinery
+// * while still propagating the exception to the encapsulating Future
+// */
+// static Runnable propagating(WithResources withResources, Runnable wrap)
+// {
+// return enforceOptions(withResources, wrap, true);
+// }
+//
+// /**
+// * See {@link #suppressing(WithResources, Runnable)}
+// */
+// static Runnable suppressing(Runnable wrap)
+// {
+// return wrap instanceof FutureTask<?> ? wrap : suppressing(WithResources.none(), wrap);
+// }
+//
+// /**
+// * In the case of scheduled periodic tasks, we don't want exceptions propagating to cancel the recurring execution.
+// */
+// static Runnable suppressing(WithResources withResources, Runnable wrap)
+// {
+// return enforceOptions(withResources, wrap, false);
+// }
+//
+// /**
+// * Encapsulate the execution, propagating or suppressing any exceptions as requested.
+// *
+// * note that if {@code wrap} is a {@link Future} its exceptions may not be captured,
+// * however the codebase should be using our internal {@link Future} variants which handle exceptions in the
+// * desired way.
+// */
+// private static Runnable enforceOptions(WithResources withResources, Runnable wrap, boolean propagate)
+// {
+// return new Runnable()
+// {
+// @Override
+// public void run()
+// {
+// try (Closeable close = withResources.get())
+// {
+// wrap.run();
+// }
+// catch (Throwable t)
+// {
+// handle(t);
+// if (propagate)
+// throw t;
+// }
+// }
+//
+// @Override
+// public String toString()
+// {
+// return wrap.toString();
+// }
+// };
+// }
+//
+// /**
+// * See {@link #enforceOptions(WithResources, Callable)}
+// */
+// static <V> Callable<V> propagating(Callable<V> wrap)
+// {
+// return enforceOptions(WithResources.none(), wrap);
+// }
+//
+// /**
+// * In the case of non-recurring scheduled tasks, we want to handle exceptions without the full {@link FutureTask}
+// * machinery, while still propagating the exception to the encapsulating Future
+// */
+// static <V> Callable<V> enforceOptions(WithResources withResources, Callable<V> wrap)
+// {
+// return new Callable<V>()
+// {
+// @Override
+// public V call() throws Exception
+// {
+// try (Closeable close = withResources.get())
+// {
+// return wrap.call();
+// }
+// catch (Throwable t)
+// {
+// handle(t);
+// throw t;
+// }
+// }
+//
+// @Override
+// public String toString()
+// {
+// return wrap.toString();
+// }
+// };
+// }
+}
diff --git a/accord-core/src/main/java/org/apache/cassandra/concurrent/ExecutorPlus.java b/accord-core/src/main/java/org/apache/cassandra/concurrent/ExecutorPlus.java
new file mode 100644
index 0000000..4ed759c
--- /dev/null
+++ b/accord-core/src/main/java/org/apache/cassandra/concurrent/ExecutorPlus.java
@@ -0,0 +1,185 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.concurrent;
+
+import org.apache.cassandra.utils.Shared;
+//import org.apache.cassandra.utils.WithResources;
+import org.apache.cassandra.utils.concurrent.Future;
+
+import java.util.Collection;
+import java.util.List;
+import java.util.concurrent.*;
+
+import static org.apache.cassandra.utils.Shared.Recursive.INTERFACES;
+import static org.apache.cassandra.utils.Shared.Scope.SIMULATION;
+
+///**
+// * Cassandra's extension of {@link ExecutorService}, using our own {@link Future}, supporting
+// * {@link #inExecutor()}, and execution with associated resources {@link #execute(WithResources, Runnable)}
+// * (which is primarily used for encapsulating {@link ExecutorLocals} without leaking implementing classes).
+// */
+@Shared(scope = SIMULATION, inner = INTERFACES)
+//public interface ExecutorPlus extends ExecutorService, ResizableThreadPool
+public interface ExecutorPlus extends ExecutorService
+{
+ interface MaximumPoolSizeListener
+ {
+ /**
+ * Listener to follow changes to the maximum pool size
+ */
+ void onUpdateMaximumPoolSize(int maximumPoolSize);
+ }
+
+ /**
+ * MAY execute {@code task} immediately, if the calling thread is permitted to do so.
+ */
+ default void maybeExecuteImmediately(Runnable task)
+ {
+ execute(task);
+ }
+
+ /**
+ * Overrides {@link ExecutorService#submit(Callable)} to return a Cassandra {@link Future}
+ */
+ @Override
+ <T> Future<T> submit(Callable<T> task);
+
+ /**
+ * Overrides {@link ExecutorService#submit(Runnable, Object)} to return a Cassandra {@link Future}
+ */
+ @Override
+ <T> Future<T> submit(Runnable task, T result);
+
+ /**
+ * Overrides {@link ExecutorService#submit(Runnable)} to return a Cassandra {@link Future}
+ */
+ @Override
+ Future<?> submit(Runnable task);
+//
+// /*
+// * ==============================================
+// * WithResources variants of submit and execute.
+// *
+// * (We need a way to inject a TraceState directly into the Executor context without going through
+// * the global Tracing sessions; see CASSANDRA-5668)
+// * ==============================================
+// */
+//
+// /**
+// * Invoke {@code task}. The invoking thread will first instantiate the resources provided before
+// * invoking {@code task}, so that thread state may be modified and cleaned up.
+// *
+// * The invoking thread will execute something semantically equivlent to:
+// *
+// * <code>
+// * try (Closeable close = withResources.get())
+// * {
+// * task.run();
+// * }
+// * </code>
+// *
+// * @param withResources the resources to create and hold while executing {@code task}
+// * @param task the task to execute
+// */
+// void execute(WithResources withResources, Runnable task);
+//
+// /**
+// * Invoke {@code task}, returning a future representing this computation.
+// * The invoking thread will first instantiate the resources provided before
+// * invoking {@code task}, so that thread state may be modified and cleaned up.
+// *
+// * The invoking thread will execute something semantically equivlent to:
+// *
+// * <code>
+// * try (Closeable close = withResources.get())
+// * {
+// * return task.call();
+// * }
+// * </code>
+// *
+// * @param withResources the resources to create and hold while executing {@code task}
+// * @param task the task to execute
+// */
+// <T> Future<T> submit(WithResources withResources, Callable<T> task);
+//
+// /**
+// * Invoke {@code task}, returning a future yielding {@code null} if successful,
+// * or the abnormal termination of {@code task} otherwise.
+// *
+// * The invoking thread will first instantiate the resources provided before
+// * invoking {@code task}, so that thread state may be modified and cleaned up
+// *
+// * <code>
+// * try (Closeable close = withResources.get())
+// * {
+// * task.run();
+// * return null;
+// * }
+// * </code>
+// *
+// * @param withResources the resources to create and hold while executing {@code task}
+// * @param task the task to execute
+// */
+// Future<?> submit(WithResources withResources, Runnable task);
+//
+// /**
+// * Invoke {@code task}, returning a future yielding {@code result} if successful,
+// * or the abnormal termination of {@code task} otherwise.
+// *
+// * The invoking thread will first instantiate the resources provided before
+// * invoking {@code task}, so that thread state may be modified and cleaned up.
+// *
+// * The invoking thread will execute something semantically equivlent to:
+// *
+// * <code>
+// * try (Closeable close = withResources.get())
+// * {
+// * task.run();
+// * return result;
+// * }
+// * </code>
+// *
+// * @param withResources the resources to create and hold while executing {@code task}
+// * @param task the task to execute
+// * @param result the result if successful
+// */
+// <T> Future<T> submit(WithResources withResources, Runnable task, T result);
+
+ /**
+ * @return true iff the caller is a worker thread actively serving this executor
+ */
+ boolean inExecutor();
+
+ default <T> List<java.util.concurrent.Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) throws InterruptedException
+ {
+ throw new UnsupportedOperationException();
+ }
+ default <T> List<java.util.concurrent.Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException
+ {
+ throw new UnsupportedOperationException();
+ }
+ default <T> T invokeAny(Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException
+ {
+ throw new UnsupportedOperationException();
+ }
+ default <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException
+ {
+ throw new UnsupportedOperationException();
+ }
+}
diff --git a/accord-core/src/main/java/org/apache/cassandra/concurrent/ImmediateExecutor.java b/accord-core/src/main/java/org/apache/cassandra/concurrent/ImmediateExecutor.java
new file mode 100644
index 0000000..2d4c323
--- /dev/null
+++ b/accord-core/src/main/java/org/apache/cassandra/concurrent/ImmediateExecutor.java
@@ -0,0 +1,44 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.concurrent;
+
+//import org.apache.cassandra.utils.Closeable;
+//import org.apache.cassandra.utils.WithResources;
+//import org.apache.cassandra.utils.concurrent.Future;
+//import org.apache.cassandra.utils.concurrent.ImmediateFuture;
+//
+//import java.util.Collections;
+//import java.util.List;
+//import java.util.concurrent.Callable;
+import java.util.concurrent.Executor;
+//import java.util.concurrent.TimeUnit;
+
+//public class ImmediateExecutor implements LocalAwareExecutorPlus
+public class ImmediateExecutor implements Executor
+{
+ public static final ImmediateExecutor INSTANCE = new ImmediateExecutor();
+
+ private ImmediateExecutor() {}
+
+ @Override
+ public void execute(Runnable command)
+ {
+ command.run();;
+ }
+}
diff --git a/accord-core/src/main/java/org/apache/cassandra/utils/Clock.java b/accord-core/src/main/java/org/apache/cassandra/utils/Clock.java
new file mode 100644
index 0000000..d1c8da6
--- /dev/null
+++ b/accord-core/src/main/java/org/apache/cassandra/utils/Clock.java
@@ -0,0 +1,124 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.cassandra.utils;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.concurrent.TimeUnit;
+
+//import static org.apache.cassandra.config.CassandrandraRelevantProperties.CLOCK_GLOBAL;
+import static org.apache.cassandra.utils.Shared.Scope.SIMULATION;
+
+/**
+ * Wrapper around time related functions that are either implemented by using the default JVM calls
+ * or by using a custom implementation for testing purposes.
+ *
+ * See {@link Global#instance} for how to use a custom implementation.
+ *
+ * Please note that {@link java.time.Clock} wasn't used, as it would not be possible to provide an
+ * implementation for {@link #nanoTime()} with the exact same properties of {@link System#nanoTime()}.
+ */
+@Shared(scope = SIMULATION)
+public interface Clock
+{
+ static final Logger logger = LoggerFactory.getLogger(Clock.class);
+
+ public static class Global
+ {
+ /**
+ * Static singleton object that will be instantiated by default with a system clock
+ * implementation. Set <code>cassandra.clock</code> system property to a FQCN to use a
+ * different implementation instead.
+ */
+ private static final Clock instance;
+
+ static
+ {
+// String classname = CLOCK_GLOBAL.getString();
+ String classname = System.getProperty("cassandra.clock");
+ Clock clock = new Default();
+ if (classname != null)
+ {
+ try
+ {
+ logger.debug("Using custom clock implementation: {}", classname);
+ clock = (Clock) Class.forName(classname).newInstance();
+ }
+ catch (Exception e)
+ {
+ logger.error("Failed to load clock implementation {}", classname, e);
+ }
+ }
+ instance = clock;
+ }
+
+ /**
+ * Semantically equivalent to {@link System#nanoTime()}
+ */
+ public static long nanoTime()
+ {
+ return instance.nanoTime();
+ }
+
+ /**
+ * Semantically equivalent to {@link System#currentTimeMillis()}
+ */
+ public static long currentTimeMillis()
+ {
+ return instance.currentTimeMillis();
+ }
+ }
+
+ public static class Default implements Clock
+ {
+ /**
+ * {@link System#nanoTime()}
+ */
+ public long nanoTime()
+ {
+ return System.nanoTime(); // checkstyle: permit system clock
+ }
+
+ /**
+ * {@link System#currentTimeMillis()}
+ */
+ public long currentTimeMillis()
+ {
+ return System.currentTimeMillis(); // checkstyle: permit system clock
+ }
+ }
+
+ /**
+ * Semantically equivalent to {@link System#nanoTime()}
+ */
+ public long nanoTime();
+
+ /**
+ * Semantically equivalent to {@link System#currentTimeMillis()}
+ */
+ public long currentTimeMillis();
+
+ @Intercept
+ public static void waitUntil(long deadlineNanos) throws InterruptedException
+ {
+ long waitNanos = Global.nanoTime() - deadlineNanos;
+ if (waitNanos > 0)
+ TimeUnit.NANOSECONDS.sleep(waitNanos);
+ }
+}
diff --git a/accord-core/src/main/java/org/apache/cassandra/utils/Intercept.java b/accord-core/src/main/java/org/apache/cassandra/utils/Intercept.java
new file mode 100644
index 0000000..b81947b
--- /dev/null
+++ b/accord-core/src/main/java/org/apache/cassandra/utils/Intercept.java
@@ -0,0 +1,31 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.utils;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+// a marker to indicate that the method is intercepted by the Simulator
+@Retention(RetentionPolicy.SOURCE)
+@Target({ ElementType.METHOD })
+public @interface Intercept
+{
+}
diff --git a/accord-core/src/main/java/org/apache/cassandra/utils/Shared.java b/accord-core/src/main/java/org/apache/cassandra/utils/Shared.java
new file mode 100644
index 0000000..abc8ad2
--- /dev/null
+++ b/accord-core/src/main/java/org/apache/cassandra/utils/Shared.java
@@ -0,0 +1,45 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.utils;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+///**
+// * Tells jvm-dtest that a class should be shared accross all {@link ClassLoader}s.
+// *
+// * Jvm-dtest relies on classloader isolation to run multiple cassandra instances in the same JVM, this makes it
+// * so some classes do not get shared (outside a blesssed set of classes/packages). When the default behavior
+// * is not desirable, this annotation will tell jvm-dtest to share the class accross all class loaders.
+// *
+// * This is the oposite of {@link Isolated}.
+// */
+@Retention(RetentionPolicy.RUNTIME)
+@Target({ ElementType.TYPE })
+public @interface Shared
+{
+ enum Scope { ANY, SIMULATION }
+ enum Recursive { NONE, INTERFACES /*(and enums and exceptions) */, ALL }
+ Scope[] scope() default Scope.ANY;
+ Recursive inner() default Recursive.NONE;
+ Recursive ancestors() default Recursive.NONE;
+ Recursive members() default Recursive.NONE;
+}
diff --git a/accord-core/src/main/java/org/apache/cassandra/utils/concurrent/AbstractFuture.java b/accord-core/src/main/java/org/apache/cassandra/utils/concurrent/AbstractFuture.java
new file mode 100644
index 0000000..e203d0e
--- /dev/null
+++ b/accord-core/src/main/java/org/apache/cassandra/utils/concurrent/AbstractFuture.java
@@ -0,0 +1,508 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.utils.concurrent;
+
+import com.google.common.base.Preconditions;
+import com.google.common.util.concurrent.AsyncFunction;
+import com.google.common.util.concurrent.FutureCallback;
+import com.google.common.util.concurrent.ListenableFuture;
+import io.netty.util.concurrent.GenericFutureListener;
+import io.netty.util.internal.ThrowableUtil;
+import org.apache.cassandra.utils.concurrent.ListenerList.*;
+
+import javax.annotation.Nullable;
+import java.util.concurrent.*;
+import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
+import java.util.function.BiConsumer;
+import java.util.function.Consumer;
+import java.util.function.Function;
+
+import static java.util.concurrent.atomic.AtomicReferenceFieldUpdater.newUpdater;
+import static org.apache.cassandra.utils.concurrent.ListenerList.*;
+
+/**
+ * Our default {@link Future} implementation, with all state being managed without locks (except those used by the JVM).
+ *
+ * Some implementation comments versus Netty's default promise:
+ * - We permit efficient initial state declaration, avoiding unnecessary CAS or lock acquisitions when mutating
+ * a Promise we are ourselves constructing (and can easily add more; only those we use have been added)
+ * - We guarantee the order of invocation of listeners (and callbacks etc, and with respect to each other)
+ * - We save some space when registering listeners, especially if there is only one listener, as we perform no
+ * extra allocations in this case.
+ * - We implement our invocation list as a concurrent stack, that is cleared on notification
+ * - We handle special values slightly differently.
+ * - We do not use a special value for null, instead using a special value to indicate the result has not been set.
+ * This means that once isSuccess() holds, the result must be a correctly typed object (modulo generics pitfalls).
+ * - All special values are also instances of FailureHolder, which simplifies a number of the logical conditions.
+ */
+@SuppressWarnings({ "rawtypes", "unchecked" })
+public abstract class AbstractFuture<V> implements Future<V>
+{
+ protected static final FailureHolder UNSET = new FailureHolder(null);
+ protected static final FailureHolder UNCANCELLABLE = new FailureHolder(null);
+ protected static final FailureHolder CANCELLED = new FailureHolder(ThrowableUtil.unknownStackTrace(new CancellationException(), AbstractFuture.class, "cancel(...)"));
+
+ static class FailureHolder
+ {
+ final Throwable cause;
+ FailureHolder(Throwable cause)
+ {
+ this.cause = cause;
+ }
+ }
+
+ private static Throwable cause(Object result)
+ {
+ return result instanceof FailureHolder ? ((FailureHolder) result).cause : null;
+ }
+ static boolean isSuccess(Object result)
+ {
+ return !(result instanceof FailureHolder);
+ }
+ static boolean isCancelled(Object result)
+ {
+ return result == CANCELLED;
+ }
+ static boolean isDone(Object result)
+ {
+ return result != UNSET && result != UNCANCELLABLE;
+ }
+
+ volatile Object result;
+ volatile ListenerList<V> listeners; // either a ListenerList or GenericFutureListener (or null)
+ static final AtomicReferenceFieldUpdater<AbstractFuture, Object> resultUpdater = newUpdater(AbstractFuture.class, Object.class, "result");
+ static final AtomicReferenceFieldUpdater<AbstractFuture, ListenerList> listenersUpdater = newUpdater(AbstractFuture.class, ListenerList.class, "listeners");
+
+ protected AbstractFuture(FailureHolder initialState)
+ {
+ // TODO: document visibility of constructor (i.e. must be safe published)
+ resultUpdater.lazySet(this, initialState);
+ }
+
+ public AbstractFuture()
+ {
+ this(UNSET);
+ }
+
+ protected AbstractFuture(V immediateSuccess)
+ {
+ resultUpdater.lazySet(this, immediateSuccess);
+ }
+
+ protected AbstractFuture(Throwable immediateFailure)
+ {
+ this(new FailureHolder(immediateFailure));
+ }
+
+ protected AbstractFuture(GenericFutureListener<? extends io.netty.util.concurrent.Future<? super V>> listener)
+ {
+ this();
+ listenersUpdater.lazySet(this, new GenericFutureListenerList(listener));
+ }
+
+ protected AbstractFuture(FailureHolder initialState, GenericFutureListener<? extends io.netty.util.concurrent.Future<? super V>> listener)
+ {
+ this(initialState);
+ listenersUpdater.lazySet(this, new GenericFutureListenerList(listener));
+ }
+
+ public Executor notifyExecutor()
+ {
+ return null;
+ }
+
+ protected boolean trySuccess(V v)
+ {
+ return trySet(v);
+ }
+
+ protected boolean tryFailure(Throwable throwable)
+ {
+ return trySet(new FailureHolder(throwable));
+ }
+
+ protected boolean setUncancellable()
+ {
+ if (trySet(UNCANCELLABLE))
+ return true;
+ return isUncancellable();
+ }
+
+ protected boolean setUncancellableExclusive()
+ {
+ return trySet(UNCANCELLABLE);
+ }
+
+ protected boolean isUncancellable()
+ {
+ Object result = this.result;
+ return result == UNCANCELLABLE || (isDone(result) && !isCancelled(result));
+ }
+
+ public boolean cancel(boolean b)
+ {
+ return trySet(CANCELLED);
+ }
+
+ /**
+ * Shared implementation of various promise completion methods.
+ * Updates the result if it is possible to do so, returning success/failure.
+ *
+ * If the promise is UNSET the new value will succeed;
+ * if it is UNCANCELLABLE it will succeed only if the new value is not CANCELLED
+ * otherwise it will fail, as isDone() is implied
+ *
+ * If the update succeeds, and the new state implies isDone(), any listeners and waiters will be notified
+ */
+ abstract boolean trySet(Object v);
+
+ @Override
+ public boolean isSuccess()
+ {
+ return isSuccess(result);
+ }
+
+ @Override
+ public boolean isCancelled()
+ {
+ return isCancelled(result);
+ }
+
+ @Override
+ public boolean isDone()
+ {
+ return isDone(result);
+ }
+
+ @Override
+ public boolean isCancellable()
+ {
+ return result == UNSET;
+ }
+
+ @Override
+ public Throwable cause()
+ {
+ return cause(result);
+ }
+
+ /**
+ * if isSuccess(), returns the value, otherwise returns null
+ */
+ @Override
+ public V getNow()
+ {
+ Object result = this.result;
+ if (isSuccess(result))
+ return (V) result;
+ return null;
+ }
+
+ /**
+ * Shared implementation of get() after suitable await(); assumes isDone(), and returns
+ * either the success result or throws the suitable exception under failure
+ */
+ protected V getWhenDone() throws ExecutionException
+ {
+ Object result = this.result;
+ if (isSuccess(result))
+ return (V) result;
+ if (result == CANCELLED)
+ throw new CancellationException();
+ throw new ExecutionException(((FailureHolder) result).cause);
+ }
+
+ @Override
+ public V get() throws InterruptedException, ExecutionException
+ {
+ await();
+ return getWhenDone();
+ }
+
+ @Override
+ public V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException
+ {
+ if (!await(timeout, unit))
+ throw new TimeoutException();
+ return getWhenDone();
+ }
+
+ /**
+ * Logically append {@code newListener} to {@link #listeners}
+ * (at this stage it is a stack, so we actually prepend)
+ */
+ abstract void appendListener(ListenerList<V> newListener);
+
+ /**
+ * Support {@link com.google.common.util.concurrent.Futures#addCallback} natively
+ *
+ * See {@link #addListener(GenericFutureListener)} for ordering semantics.
+ */
+ @Override
+ public AbstractFuture<V> addCallback(FutureCallback<? super V> callback)
+ {
+ appendListener(new CallbackListener<>(this, callback));
+ return this;
+ }
+
+ /**
+ * Support {@link com.google.common.util.concurrent.Futures#addCallback} natively
+ *
+ * See {@link #addListener(GenericFutureListener)} for ordering semantics.
+ */
+ @Override
+ public AbstractFuture<V> addCallback(BiConsumer<? super V, Throwable> callback)
+ {
+ appendListener(new CallbackBiConsumerListener<>(this, callback, null));
+ return this;
+ }
+
+ @Override
+ public Future<V> addCallback(BiConsumer<? super V, Throwable> callback, Executor executor)
+ {
+ appendListener(new CallbackBiConsumerListener<>(this, callback, executor));
+ return this;
+ }
+
+ /**
+ * Support {@link com.google.common.util.concurrent.Futures#addCallback} natively
+ *
+ * See {@link #addListener(GenericFutureListener)} for ordering semantics.
+ */
+ @Override
+ public AbstractFuture<V> addCallback(FutureCallback<? super V> callback, Executor executor)
+ {
+ Preconditions.checkNotNull(executor);
+ appendListener(new CallbackListenerWithExecutor<>(this, callback, executor));
+ return this;
+ }
+
+ /**
+ * Support more fluid version of {@link com.google.common.util.concurrent.Futures#addCallback}
+ *
+ * See {@link #addListener(GenericFutureListener)} for ordering semantics.
+ */
+ @Override
+ public AbstractFuture<V> addCallback(Consumer<? super V> onSuccess, Consumer<? super Throwable> onFailure)
+ {
+ appendListener(new CallbackLambdaListener<>(this, onSuccess, onFailure, null));
+ return this;
+ }
+
+ /**
+ * Support more fluid version of {@link com.google.common.util.concurrent.Futures#addCallback}
+ *
+ * See {@link #addListener(GenericFutureListener)} for ordering semantics.
+ */
+ @Override
+ public AbstractFuture<V> addCallback(Consumer<? super V> onSuccess, Consumer<? super Throwable> onFailure, Executor executor)
+ {
+ appendListener(new CallbackLambdaListener<>(this, onSuccess, onFailure, executor));
+ return this;
+ }
+
+ /**
+ * Support {@link com.google.common.util.concurrent.Futures#transform(ListenableFuture, com.google.common.base.Function, Executor)} natively
+ *
+ * See {@link #addListener(GenericFutureListener)} for ordering semantics.
+ */
+ protected <T> Future<T> map(AbstractFuture<T> result, Function<? super V, ? extends T> mapper, @Nullable Executor executor)
+ {
+ addListener(() -> {
+ try
+ {
+ if (isSuccess()) result.trySet(mapper.apply(getNow()));
+ else result.tryFailure(cause());
+ }
+ catch (Throwable t)
+ {
+ result.tryFailure(t);
+ throw t;
+ }
+ }, executor);
+ return result;
+ }
+
+ /**
+ * Support {@link com.google.common.util.concurrent.Futures#transformAsync(ListenableFuture, AsyncFunction, Executor)} natively
+ *
+ * See {@link #addListener(GenericFutureListener)} for ordering semantics.
+ */
+ protected <T> Future<T> flatMap(AbstractFuture<T> result, Function<? super V, ? extends Future<T>> flatMapper, @Nullable Executor executor)
+ {
+ addListener(() -> {
+ try
+ {
+ if (isSuccess()) flatMapper.apply(getNow()).addListener(propagate(result));
+ else result.tryFailure(cause());
+ }
+ catch (Throwable t)
+ {
+ result.tryFailure(t);
+ throw t;
+ }
+ }, executor);
+ return result;
+ }
+
+ /**
+ * Add a listener to be invoked once this future completes.
+ * Listeners are submitted to {@link #notifyExecutor} in the order they are added (or the specified executor
+ * in the case of {@link #addListener(Runnable, Executor)}.
+ * if {@link #notifyExecutor} is unset, they are invoked in the order they are added.
+ * The ordering holds across all variants of this method.
+ */
+ public Future<V> addListener(GenericFutureListener<? extends io.netty.util.concurrent.Future<? super V>> listener)
+ {
+ appendListener(new GenericFutureListenerList(listener));
+ return this;
+ }
+
+ /**
+ * Add a listener to be invoked once this future completes.
+ * Listeners are submitted to their {@code #executor} (or {@link #notifyExecutor}) in the order they are added;
+ * if {@link #notifyExecutor} is unset, they are invoked in the order they are added.
+ * The ordering holds across all variants of this method.
+ */
+ public void addListener(Runnable task, @Nullable Executor executor)
+ {
+ appendListener(new RunnableWithExecutor(task, executor));
+ }
+
+ /**
+ * Add a listener to be invoked once this future completes.
+ * Listeners are submitted to {@link #notifyExecutor} in the order they are added (or the specified executor
+ * in the case of {@link #addListener(Runnable, Executor)}.
+ * if {@link #notifyExecutor} is unset, they are invoked in the order they are added.
+ * The ordering holds across all variants of this method.
+ */
+ public void addListener(Runnable task)
+ {
+ appendListener(new RunnableWithNotifyExecutor(task));
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public Future<V> addListeners(GenericFutureListener<? extends io.netty.util.concurrent.Future<? super V>>... listeners)
+ {
+ // this could be more efficient if we cared, but we do not
+ return addListener(future -> {
+ for (GenericFutureListener<? extends io.netty.util.concurrent.Future<? super V>> listener : listeners)
+ notifyListener((GenericFutureListener<io.netty.util.concurrent.Future<? super V>>)listener, future);
+ });
+ }
+
+ @Override
+ public Future<V> removeListener(GenericFutureListener<? extends io.netty.util.concurrent.Future<? super V>> listener)
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public Future<V> removeListeners(GenericFutureListener<? extends io.netty.util.concurrent.Future<? super V>>... listeners)
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public boolean await(long timeout, TimeUnit unit) throws InterruptedException
+ {
+ return Awaitable.await(this, timeout, unit);
+ }
+
+ @Override
+ public boolean awaitThrowUncheckedOnInterrupt(long time, TimeUnit units) throws UncheckedInterruptedException
+ {
+ return Awaitable.awaitThrowUncheckedOnInterrupt(this, time, units);
+ }
+
+ @Override
+ public boolean awaitUninterruptibly(long timeout, TimeUnit unit)
+ {
+ return Awaitable.awaitUninterruptibly(this, timeout, unit);
+ }
+
+ @Override
+ public boolean awaitUntilThrowUncheckedOnInterrupt(long nanoTimeDeadline) throws UncheckedInterruptedException
+ {
+ return Awaitable.awaitUntilThrowUncheckedOnInterrupt(this, nanoTimeDeadline);
+ }
+
+ @Override
+ public boolean awaitUntilUninterruptibly(long nanoTimeDeadline)
+ {
+ return Awaitable.awaitUntilUninterruptibly(this, nanoTimeDeadline);
+ }
+
+ /**
+ * Wait for this future to complete {@link Awaitable#awaitUninterruptibly()}
+ */
+ @Override
+ public Future<V> awaitUninterruptibly()
+ {
+ return Awaitable.awaitUninterruptibly(this);
+ }
+
+ /**
+ * Wait for this future to complete {@link Awaitable#awaitThrowUncheckedOnInterrupt()}
+ */
+ @Override
+ public Future<V> awaitThrowUncheckedOnInterrupt() throws UncheckedInterruptedException
+ {
+ return Awaitable.awaitThrowUncheckedOnInterrupt(this);
+ }
+
+ public String toString()
+ {
+ String description = description();
+ String state = state();
+ return description == null ? state : (state + ' ' + description);
+ }
+
+ private String state()
+ {
+ Object result = this.result;
+ if (isSuccess(result))
+ return "(success: " + result + ')';
+ if (result == UNCANCELLABLE)
+ return "(uncancellable)";
+ if (result == CANCELLED)
+ return "(cancelled)";
+ if (isDone(result))
+ return "(failure: " + ((FailureHolder) result).cause + ')';
+ return "(incomplete)";
+ }
+
+ protected String description()
+ {
+ return null;
+ }
+
+ /**
+ * @return a listener that will propagate to {@code to} the result of the future it is invoked with
+ */
+ private static <V> GenericFutureListener<? extends Future<V>> propagate(AbstractFuture<? super V> to)
+ {
+ return from -> {
+ if (from.isSuccess()) to.trySuccess(from.getNow());
+ else to.tryFailure(from.cause());
+ };
+ }
+}
diff --git a/accord-core/src/main/java/org/apache/cassandra/utils/concurrent/AsyncFuture.java b/accord-core/src/main/java/org/apache/cassandra/utils/concurrent/AsyncFuture.java
new file mode 100644
index 0000000..bace7bd
--- /dev/null
+++ b/accord-core/src/main/java/org/apache/cassandra/utils/concurrent/AsyncFuture.java
@@ -0,0 +1,162 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.utils.concurrent;
+
+import com.google.common.util.concurrent.AsyncFunction;
+import com.google.common.util.concurrent.ListenableFuture;
+import io.netty.util.concurrent.GenericFutureListener;
+
+import javax.annotation.Nullable;
+import java.util.concurrent.Executor;
+import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
+import java.util.function.Function;
+
+/**
+ * Our default {@link Future} implementation, with all state being managed without locks (except those used by the JVM).
+ *
+ * Some implementation comments versus Netty's default promise:
+ * - We permit efficient initial state declaration, avoiding unnecessary CAS or lock acquisitions when mutating
+ * a Promise we are ourselves constructing (and can easily add more; only those we use have been added)
+ * - We guarantee the order of invocation of listeners (and callbacks etc, and with respect to each other)
+ * - We save some space when registering listeners, especially if there is only one listener, as we perform no
+ * extra allocations in this case.
+ * - We implement our invocation list as a concurrent stack, that is cleared on notification
+ * - We handle special values slightly differently.
+ * - We do not use a special value for null, instead using a special value to indicate the result has not been set.
+ * This means that once isSuccess() holds, the result must be a correctly typed object (modulo generics pitfalls).
+ * - All special values are also instances of FailureHolder, which simplifies a number of the logical conditions.
+ */
+public class AsyncFuture<V> extends AbstractFuture<V>
+{
+ @SuppressWarnings({ "rawtypes" })
+ private static final AtomicReferenceFieldUpdater<AsyncFuture, WaitQueue> waitingUpdater = AtomicReferenceFieldUpdater.newUpdater(AsyncFuture.class, WaitQueue.class, "waiting");
+ @SuppressWarnings({ "unused" })
+ private volatile WaitQueue waiting;
+
+ public AsyncFuture()
+ {
+ super();
+ }
+
+ protected AsyncFuture(V immediateSuccess)
+ {
+ super(immediateSuccess);
+ }
+
+ protected AsyncFuture(Throwable immediateFailure)
+ {
+ super(immediateFailure);
+ }
+
+ protected AsyncFuture(FailureHolder initialState)
+ {
+ super(initialState);
+ }
+
+ protected AsyncFuture(GenericFutureListener<? extends io.netty.util.concurrent.Future<? super V>> listener)
+ {
+ super(listener);
+ }
+
+ protected AsyncFuture(FailureHolder initialState, GenericFutureListener<? extends io.netty.util.concurrent.Future<? super V>> listener)
+ {
+ super(initialState, listener);
+ }
+
+ /**
+ * Shared implementation of various promise completion methods.
+ * Updates the result if it is possible to do so, returning success/failure.
+ *
+ * If the promise is UNSET the new value will succeed;
+ * if it is UNCANCELLABLE it will succeed only if the new value is not CANCELLED
+ * otherwise it will fail, as isDone() is implied
+ *
+ * If the update succeeds, and the new state implies isDone(), any listeners and waiters will be notified
+ */
+ boolean trySet(Object v)
+ {
+ while (true)
+ {
+ Object current = result;
+ if (isDone(current) || (current == UNCANCELLABLE && (v == CANCELLED || v == UNCANCELLABLE)))
+ return false;
+ if (resultUpdater.compareAndSet(this, current, v))
+ {
+ if (v != UNCANCELLABLE)
+ {
+ ListenerList.notify(listenersUpdater, this);
+ AsyncAwaitable.signalAll(waitingUpdater, this);
+ }
+ return true;
+ }
+ }
+ }
+
+ /**
+ * Logically append {@code newListener} to {@link #listeners}
+ * (at this stage it is a stack, so we actually prepend)
+ *
+ * @param newListener must be either a {@link ListenerList} or {@link GenericFutureListener}
+ */
+ void appendListener(ListenerList<V> newListener)
+ {
+ ListenerList.push(listenersUpdater, this, newListener);
+ if (isDone())
+ ListenerList.notify(listenersUpdater, this);
+ }
+
+ /**
+ * Support {@link com.google.common.util.concurrent.Futures#transform(ListenableFuture, com.google.common.base.Function, Executor)} natively
+ *
+ * See {@link #addListener(GenericFutureListener)} for ordering semantics.
+ */
+ @Override
+ public <T> Future<T> map(Function<? super V, ? extends T> mapper, Executor executor)
+ {
+ return map(new AsyncFuture<>(), mapper, executor);
+ }
+
+ /**
+ * Support {@link com.google.common.util.concurrent.Futures#transformAsync(ListenableFuture, AsyncFunction, Executor)} natively
+ *
+ * See {@link #addListener(GenericFutureListener)} for ordering semantics.
+ */
+ @Override
+ public <T> Future<T> flatMap(Function<? super V, ? extends Future<T>> flatMapper, @Nullable Executor executor)
+ {
+ return flatMap(new AsyncFuture<>(), flatMapper, executor);
+ }
+
+ /**
+ * Wait for this future to complete {@link Awaitable#await()}
+ */
+ @Override
+ public AsyncFuture<V> await() throws InterruptedException
+ {
+ //noinspection unchecked
+ return AsyncAwaitable.await(waitingUpdater, Future::isDone, this);
+ }
+
+ @Override
+ public boolean awaitUntil(long nanoTimeDeadline) throws InterruptedException
+ {
+ return AsyncAwaitable.awaitUntil(waitingUpdater, Future::isDone, this, nanoTimeDeadline);
+ }
+}
+
diff --git a/accord-core/src/main/java/org/apache/cassandra/utils/concurrent/AsyncPromise.java b/accord-core/src/main/java/org/apache/cassandra/utils/concurrent/AsyncPromise.java
new file mode 100644
index 0000000..b97c3a2
--- /dev/null
+++ b/accord-core/src/main/java/org/apache/cassandra/utils/concurrent/AsyncPromise.java
@@ -0,0 +1,268 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.utils.concurrent;
+
+import com.google.common.util.concurrent.FutureCallback;
+import io.netty.util.concurrent.Future;
+import io.netty.util.concurrent.GenericFutureListener;
+
+import java.util.concurrent.Executor;
+import java.util.function.Consumer;
+
+/**
+ * Extends {@link AsyncFuture} to implement the {@link Promise} interface.
+ */
+public class AsyncPromise<V> extends AsyncFuture<V> implements Promise<V>
+{
+ public static class WithExecutor<V> extends AsyncPromise<V>
+ {
+ final Executor notifyExecutor;
+ protected WithExecutor(Executor notifyExecutor)
+ {
+ this.notifyExecutor = notifyExecutor;
+ }
+
+ protected WithExecutor(Executor notifyExecutor, FailureHolder initialState)
+ {
+ super(initialState);
+ this.notifyExecutor = notifyExecutor;
+ }
+
+ protected WithExecutor(Executor notifyExecutor, GenericFutureListener<? extends Future<? super V>> listener)
+ {
+ super(listener);
+ this.notifyExecutor = notifyExecutor;
+ }
+
+ @Override
+ public Executor notifyExecutor()
+ {
+ return notifyExecutor;
+ }
+ }
+
+ public AsyncPromise() {}
+
+ AsyncPromise(FailureHolder initialState)
+ {
+ super(initialState);
+ }
+
+ public AsyncPromise(GenericFutureListener<? extends io.netty.util.concurrent.Future<? super V>> listener)
+ {
+ super(listener);
+ }
+
+ AsyncPromise(FailureHolder initialState, GenericFutureListener<? extends io.netty.util.concurrent.Future<? super V>> listener)
+ {
+ super(initialState, listener);
+ }
+
+ public static <V> AsyncPromise<V> withExecutor(Executor executor)
+ {
+ return new WithExecutor<>(executor);
+ }
+
+ public static <V> AsyncPromise<V> uncancellable()
+ {
+ return new AsyncPromise<>(UNCANCELLABLE);
+ }
+
+ public static <V> AsyncPromise<V> uncancellable(Executor executor)
+ {
+ return new WithExecutor<>(executor, UNCANCELLABLE);
+ }
+
+ public static <V> AsyncPromise<V> uncancellable(GenericFutureListener<? extends Future<? super V>> listener)
+ {
+ return new AsyncPromise<>(UNCANCELLABLE, listener);
+ }
+
+ /**
+ * Complete the promise successfully if not already complete
+ * @throws IllegalStateException if already set
+ */
+ @Override
+ public Promise<V> setSuccess(V v)
+ {
+ if (!trySuccess(v))
+ throw new IllegalStateException("complete already: " + this);
+ return this;
+ }
+
+ /**
+ * Complete the promise successfully if not already complete
+ * @return true iff completed promise
+ */
+ @Override
+ public boolean trySuccess(V v)
+ {
+ return super.trySuccess(v);
+ }
+
+ /**
+ * Complete the promise abnormally if not already complete
+ * @throws IllegalStateException if already set
+ */
+ @Override
+ public Promise<V> setFailure(Throwable throwable)
+ {
+ if (!tryFailure(throwable))
+ throw new IllegalStateException("complete already: " + this);
+ return this;
+ }
+
+ /**
+ * Complete the promise abnormally if not already complete
+ * @return true iff completed promise
+ */
+ @Override
+ public boolean tryFailure(Throwable throwable)
+ {
+ return super.tryFailure(throwable);
+ }
+
+ /**
+ * Prevent a future caller from cancelling this promise
+ * @return true if the promise is now uncancellable (whether or not we did this)
+ */
+ @Override
+ public boolean setUncancellable()
+ {
+ return super.setUncancellable();
+ }
+
+ /**
+ * Prevent a future caller from cancelling this promise
+ * @return true iff this invocation set it to uncancellable, whether or not now uncancellable
+ */
+ @Override
+ public boolean setUncancellableExclusive()
+ {
+ return super.setUncancellableExclusive();
+ }
+
+ @Override
+ public boolean isUncancellable()
+ {
+ return super.isUncancellable();
+ }
+
+ /**
+ * waits for completion; in case of failure rethrows the original exception without a new wrapping exception
+ * so may cause problems for reporting stack traces
+ */
+ @Override
+ public Promise<V> sync() throws InterruptedException
+ {
+ super.sync();
+ return this;
+ }
+
+ /**
+ * waits for completion; in case of failure rethrows the original exception without a new wrapping exception
+ * so may cause problems for reporting stack traces
+ */
+ @Override
+ public Promise<V> syncUninterruptibly()
+ {
+ super.syncUninterruptibly();
+ return this;
+ }
+
+ @Override
+ public AsyncPromise<V> addListener(GenericFutureListener<? extends Future<? super V>> listener)
+ {
+ super.addListener(listener);
+ return this;
+ }
+
+ @Override
+ public AsyncPromise<V> addListeners(GenericFutureListener<? extends io.netty.util.concurrent.Future<? super V>>... listeners)
+ {
+ super.addListeners(listeners);
+ return this;
+ }
+
+ @Override
+ public AsyncPromise<V> removeListener(GenericFutureListener<? extends io.netty.util.concurrent.Future<? super V>> listener)
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public AsyncPromise<V> removeListeners(GenericFutureListener<? extends io.netty.util.concurrent.Future<? super V>>... listeners)
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public AsyncPromise<V> addCallback(FutureCallback<? super V> callback)
+ {
+ super.addCallback(callback);
+ return this;
+ }
+
+ @Override
+ public AsyncPromise<V> addCallback(FutureCallback<? super V> callback, Executor executor)
+ {
+ super.addCallback(callback, executor);
+ return this;
+ }
+
+ @Override
+ public AsyncPromise<V> addCallback(Consumer<? super V> onSuccess, Consumer<? super Throwable> onFailure)
+ {
+ super.addCallback(onSuccess, onFailure);
+ return this;
+ }
+
+ /**
+ * Wait for this promise to complete
+ * @throws InterruptedException if interrupted
+ */
+ @Override
+ public AsyncPromise<V> await() throws InterruptedException
+ {
+ super.await();
+ return this;
+ }
+
+ /**
+ * Wait uninterruptibly for this promise to complete
+ */
+ @Override
+ public AsyncPromise<V> awaitUninterruptibly()
+ {
+ super.awaitUninterruptibly();
+ return this;
+ }
+
+ /**
+ * Wait for this promise to complete, throwing any interrupt as an UncheckedInterruptedException
+ * @throws UncheckedInterruptedException if interrupted
+ */
+ @Override
+ public AsyncPromise<V> awaitThrowUncheckedOnInterrupt() throws UncheckedInterruptedException
+ {
+ super.awaitThrowUncheckedOnInterrupt();
+ return this;
+ }
+}
+
diff --git a/accord-core/src/main/java/org/apache/cassandra/utils/concurrent/Awaitable.java b/accord-core/src/main/java/org/apache/cassandra/utils/concurrent/Awaitable.java
new file mode 100644
index 0000000..f75582d
--- /dev/null
+++ b/accord-core/src/main/java/org/apache/cassandra/utils/concurrent/Awaitable.java
@@ -0,0 +1,404 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.utils.concurrent;
+
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
+import java.util.function.Predicate;
+
+//import net.nicoulaj.compilecommand.annotations.Inline;
+import org.apache.cassandra.utils.Shared;
+
+import org.apache.cassandra.utils.Intercept;
+
+import static org.apache.cassandra.utils.Clock.Global.nanoTime;
+import static org.apache.cassandra.utils.concurrent.WaitQueue.newWaitQueue;
+import static org.apache.cassandra.utils.Shared.Scope.SIMULATION;
+
+/**
+ * A generic signal consumer, supporting all of the typical patterns used in Cassandra.
+ * All of the methods defined in {@link Awaitable} may be waited on without a loop,
+ * as this interface declares that there are no spurious wake-ups.
+ */
+@Shared(scope = SIMULATION)
+public interface Awaitable
+{
+ /**
+ * Await until the deadline (in nanoTime), throwing any interrupt.
+ * No spurious wakeups.
+ * @return true if we were signalled, false if the deadline elapsed
+ * @throws InterruptedException if interrupted
+ */
+ boolean awaitUntil(long nanoTimeDeadline) throws InterruptedException;
+
+ /**
+ * Await until the deadline (in nanoTime), throwing any interrupt as an unchecked exception.
+ * No spurious wakeups.
+ * @return true if we were signalled, false if the deadline elapsed
+ * @throws UncheckedInterruptedException if interrupted
+ */
+ boolean awaitUntilThrowUncheckedOnInterrupt(long nanoTimeDeadline) throws UncheckedInterruptedException;
+
+ /**
+ * Await until the deadline (in nanoTime), ignoring interrupts (but maintaining the interrupt flag on exit).
+ * No spurious wakeups.
+ * @return true if we were signalled, false if the deadline elapsed
+ */
+ boolean awaitUntilUninterruptibly(long nanoTimeDeadline);
+
+ /**
+ * Await for the specified period, throwing any interrupt.
+ * No spurious wakeups.
+ * @return true if we were signalled, false if the timeout elapses
+ * @throws InterruptedException if interrupted
+ */
+ boolean await(long time, TimeUnit units) throws InterruptedException;
+
+ /**
+ * Await for the specified period, throwing any interrupt as an unchecked exception.
+ * No spurious wakeups.
+ * @return true if we were signalled, false if the timeout elapses
+ * @throws UncheckedInterruptedException if interrupted
+ */
+ boolean awaitThrowUncheckedOnInterrupt(long time, TimeUnit units) throws UncheckedInterruptedException;
+
+ /**
+ * Await until the deadline (in nanoTime), ignoring interrupts (but maintaining the interrupt flag on exit).
+ * No spurious wakeups.
+ * @return true if we were signalled, false if the timeout elapses
+ */
+ boolean awaitUninterruptibly(long time, TimeUnit units);
+
+ /**
+ * Await indefinitely, throwing any interrupt.
+ * No spurious wakeups.
+ * @throws InterruptedException if interrupted
+ */
+ Awaitable await() throws InterruptedException;
+
+ /**
+ * Await indefinitely, throwing any interrupt as an unchecked exception.
+ * No spurious wakeups.
+ * @throws UncheckedInterruptedException if interrupted
+ */
+ Awaitable awaitThrowUncheckedOnInterrupt() throws UncheckedInterruptedException;
+
+ /**
+ * Await indefinitely, ignoring interrupts (but maintaining the interrupt flag on exit).
+ * No spurious wakeups.
+ */
+ Awaitable awaitUninterruptibly();
+
+ public static boolean await(Awaitable await, long time, TimeUnit unit) throws InterruptedException
+ {
+ return await.awaitUntil(nanoTime() + unit.toNanos(time));
+ }
+
+ public static boolean awaitThrowUncheckedOnInterrupt(Awaitable await, long time, TimeUnit units) throws UncheckedInterruptedException
+ {
+ return awaitUntilThrowUncheckedOnInterrupt(await, nanoTime() + units.toNanos(time));
+ }
+
+ public static boolean awaitUninterruptibly(Awaitable await, long time, TimeUnit units)
+ {
+ return awaitUntilUninterruptibly(await, nanoTime() + units.toNanos(time));
+ }
+
+ public static <A extends Awaitable> A awaitThrowUncheckedOnInterrupt(A await) throws UncheckedInterruptedException
+ {
+ try
+ {
+ await.await();
+ }
+ catch (InterruptedException e)
+ {
+ throw new UncheckedInterruptedException();
+ }
+ return await;
+ }
+
+ public static boolean awaitUntilThrowUncheckedOnInterrupt(Awaitable await, long nanoTimeDeadline) throws UncheckedInterruptedException
+ {
+ try
+ {
+ return await.awaitUntil(nanoTimeDeadline);
+ }
+ catch (InterruptedException e)
+ {
+ throw new UncheckedInterruptedException();
+ }
+ }
+
+ /**
+ * {@link Awaitable#awaitUntilUninterruptibly(long)}
+ */
+ public static boolean awaitUntilUninterruptibly(Awaitable await, long nanoTimeDeadline)
+ {
+ boolean interrupted = false;
+ boolean result;
+ while (true)
+ {
+ try
+ {
+ result = await.awaitUntil(nanoTimeDeadline);
+ break;
+ }
+ catch (InterruptedException e)
+ {
+ interrupted = true;
+ }
+ }
+ if (interrupted)
+ Thread.currentThread().interrupt();
+ return result;
+ }
+
+ /**
+ * {@link Awaitable#awaitUninterruptibly()}
+ */
+ public static <A extends Awaitable> A awaitUninterruptibly(A await)
+ {
+ boolean interrupted = false;
+ while (true)
+ {
+ try
+ {
+ await.await();
+ break;
+ }
+ catch (InterruptedException e)
+ {
+ interrupted = true;
+ }
+ }
+ if (interrupted)
+ Thread.currentThread().interrupt();
+ return await;
+ }
+
+ abstract class AbstractAwaitable implements Awaitable
+ {
+ protected AbstractAwaitable() {}
+
+ /**
+ * {@link Awaitable#await(long, TimeUnit)}
+ */
+ @Override
+ public boolean await(long time, TimeUnit unit) throws InterruptedException
+ {
+ return Awaitable.await(this, time, unit);
+ }
+
+ /**
+ * {@link Awaitable#awaitThrowUncheckedOnInterrupt(long, TimeUnit)}
+ */
+ @Override
+ public boolean awaitThrowUncheckedOnInterrupt(long time, TimeUnit units) throws UncheckedInterruptedException
+ {
+ return Awaitable.awaitThrowUncheckedOnInterrupt(this, time, units);
+ }
+
+ /**
+ * {@link Awaitable#awaitUninterruptibly(long, TimeUnit)}
+ */
+ public boolean awaitUninterruptibly(long time, TimeUnit units)
+ {
+ return awaitUntilUninterruptibly(nanoTime() + units.toNanos(time));
+ }
+
+ /**
+ * {@link Awaitable#awaitThrowUncheckedOnInterrupt()}
+ */
+ public Awaitable awaitThrowUncheckedOnInterrupt() throws UncheckedInterruptedException
+ {
+ return Awaitable.awaitThrowUncheckedOnInterrupt(this);
+ }
+
+ /**
+ * {@link Awaitable#awaitUntilThrowUncheckedOnInterrupt(long)}
+ */
+ public boolean awaitUntilThrowUncheckedOnInterrupt(long nanoTimeDeadline) throws UncheckedInterruptedException
+ {
+ return Awaitable.awaitUntilThrowUncheckedOnInterrupt(this, nanoTimeDeadline);
+ }
+
+ /**
+ * {@link Awaitable#awaitUntilUninterruptibly(long)}
+ */
+ public boolean awaitUntilUninterruptibly(long nanoTimeDeadline)
+ {
+ return Awaitable.awaitUntilUninterruptibly(this, nanoTimeDeadline);
+ }
+
+ /**
+ * {@link Awaitable#awaitUninterruptibly()}
+ */
+ public Awaitable awaitUninterruptibly()
+ {
+ return Awaitable.awaitUninterruptibly(this);
+ }
+ }
+
+ /**
+ * A barebones asynchronous {@link Awaitable}.
+ * If your state is minimal, or can be updated concurrently, extend this class.
+ */
+ abstract class AsyncAwaitable extends AbstractAwaitable
+ {
+ /**
+ * Maintain an internal variable containing a lazily-initialized wait queue
+ * @return null if is done
+ */
+ @Inline
+ private static <A extends Awaitable> WaitQueue.Signal register(AtomicReferenceFieldUpdater<A, WaitQueue> waitingUpdater, Predicate<A> isDone, A awaitable)
+ {
+ if (isDone.test(awaitable))
+ return null;
+
+ WaitQueue waiting = waitingUpdater.get(awaitable);
+ if (waiting == null)
+ {
+ if (!waitingUpdater.compareAndSet(awaitable, null, waiting = newWaitQueue()))
+ {
+ waiting = waitingUpdater.get(awaitable);
+ if (waiting == null)
+ {
+ assert isDone.test(awaitable);
+ return null;
+ }
+ }
+ }
+
+ WaitQueue.Signal s = waiting.register();
+ if (!isDone.test(awaitable))
+ return s;
+
+ s.cancel();
+ return null;
+ }
+
+ @Inline
+ static <A extends Awaitable> A await(AtomicReferenceFieldUpdater<A, WaitQueue> waitingUpdater, Predicate<A> isDone, A awaitable) throws InterruptedException
+ {
+ WaitQueue.Signal s = register(waitingUpdater, isDone, awaitable);
+ if (s != null)
+ s.await();
+ return awaitable;
+ }
+
+ @Inline
+ static <A extends Awaitable> boolean awaitUntil(AtomicReferenceFieldUpdater<A, WaitQueue> waitingUpdater, Predicate<A> isDone, A awaitable, long nanoTimeDeadline) throws InterruptedException
+ {
+ WaitQueue.Signal s = register(waitingUpdater, isDone, awaitable);
+ return s == null || s.awaitUntil(nanoTimeDeadline) || isDone.test(awaitable);
+ }
+
+ @Inline
+ static <A extends Awaitable> void signalAll(AtomicReferenceFieldUpdater<A, WaitQueue> waitingUpdater, A awaitable)
+ {
+ WaitQueue waiting = waitingUpdater.get(awaitable);
+ if (waiting == null)
+ return;
+
+ waiting.signalAll();
+ waitingUpdater.lazySet(awaitable, null);
+ }
+
+ private static final AtomicReferenceFieldUpdater<AsyncAwaitable, WaitQueue> waitingUpdater = AtomicReferenceFieldUpdater.newUpdater(AsyncAwaitable.class, WaitQueue.class, "waiting");
+ private volatile WaitQueue waiting;
+
+ protected AsyncAwaitable() {}
+
+ /**
+ * {@link Awaitable#await()}
+ */
+ public Awaitable await() throws InterruptedException
+ {
+ return await(waitingUpdater, AsyncAwaitable::isSignalled, this);
+ }
+
+ /**
+ * {@link Awaitable#awaitUntil(long)}
+ */
+ public boolean awaitUntil(long nanoTimeDeadline) throws InterruptedException
+ {
+ return awaitUntil(waitingUpdater, AsyncAwaitable::isSignalled, this, nanoTimeDeadline);
+ }
+
+ /**
+ * Signal any waiting threads; {@link #isSignalled()} must return {@code true} before this method is invoked.
+ */
+ protected void signal()
+ {
+ signalAll(waitingUpdater, this);
+ }
+
+ /**
+ * Return true once signalled. Unidirectional; once true, must never again be false.
+ */
+ protected abstract boolean isSignalled();
+ }
+
+ /**
+ * A barebones {@link Awaitable} that uses mutual exclusion.
+ * If your state will be updated while holding the object monitor, extend this class.
+ */
+ abstract class SyncAwaitable extends AbstractAwaitable
+ {
+ protected SyncAwaitable() {}
+
+ /**
+ * {@link Awaitable#await()}
+ */
+ public synchronized Awaitable await() throws InterruptedException
+ {
+ while (!isSignalled())
+ wait();
+ return this;
+ }
+
+ /**
+ * {@link Awaitable#awaitUntil(long)}
+ */
+ public synchronized boolean awaitUntil(long nanoTimeDeadline) throws InterruptedException
+ {
+ while (true)
+ {
+ if (isSignalled()) return true;
+ if (!waitUntil(this, nanoTimeDeadline)) return false;
+ }
+ }
+
+ /**
+ * Return true once signalled. Unidirectional; once true, must never again be false.
+ */
+ protected abstract boolean isSignalled();
+
+ @Intercept
+ public static boolean waitUntil(Object monitor, long deadlineNanos) throws InterruptedException
+ {
+ long wait = deadlineNanos - nanoTime();
+ if (wait <= 0)
+ return false;
+
+ monitor.wait((wait + 999999) / 1000000);
+ return true;
+ }
+ }
+}
diff --git a/accord-core/src/main/java/org/apache/cassandra/utils/concurrent/Condition.java b/accord-core/src/main/java/org/apache/cassandra/utils/concurrent/Condition.java
new file mode 100644
index 0000000..eb97848
--- /dev/null
+++ b/accord-core/src/main/java/org/apache/cassandra/utils/concurrent/Condition.java
@@ -0,0 +1,104 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.utils.concurrent;
+
+import org.apache.cassandra.utils.Intercept;
+import org.apache.cassandra.utils.Shared;
+
+import static org.apache.cassandra.utils.Shared.Scope.SIMULATION;
+
+/**
+ * Simpler API than java.util.concurrent.Condition; would be nice to extend it, but also nice
+ * to share API with Future, for which Netty's API is incompatible with java.util.concurrent.Condition
+ *
+ * {@link Awaitable} for explicit external signals.
+ */
+@Shared(scope = SIMULATION)
+public interface Condition extends Awaitable
+{
+ /**
+ * Returns true once signalled. Unidirectional; once true, will never again be false.
+ */
+ boolean isSignalled();
+
+ /**
+ * Signal the condition as met, and wake all waiting threads.
+ */
+ void signal();
+
+ /**
+ * Signal the condition as met, and wake all waiting threads.
+ */
+ default void signalAll() { signal(); }
+
+ /**
+ * Factory method used to capture and redirect instantiations for simulation
+ */
+ @Intercept
+ static Condition newOneTimeCondition()
+ {
+ return new Async();
+ }
+
+ /**
+ * An asynchronous {@link Condition}. Typically lower overhead than {@link Sync}.
+ */
+ public static class Async extends AsyncAwaitable implements Condition
+ {
+ private volatile boolean signaled = false;
+
+ // WARNING: if extending this class, consider simulator interactions
+ protected Async() {}
+
+ public boolean isSignalled()
+ {
+ return signaled;
+ }
+
+ public void signal()
+ {
+ signaled = true;
+ super.signal();
+ }
+ }
+
+ /**
+ * A {@link Condition} based on its object monitor.
+ * WARNING: lengthy operations performed while holding the lock may prevent timely notification of waiting threads
+ * that a deadline has passed.
+ */
+ public static class Sync extends SyncAwaitable implements Condition
+ {
+ private boolean signaled = false;
+
+ // this can be instantiated directly, as we intercept monitors directly with byte weaving
+ public Sync() {}
+
+ public synchronized boolean isSignalled()
+ {
+ return signaled;
+ }
+
+ public synchronized void signal()
+ {
+ signaled = true;
+ notifyAll();
+ }
+ }
+}
diff --git a/accord-core/src/main/java/org/apache/cassandra/utils/concurrent/Future.java b/accord-core/src/main/java/org/apache/cassandra/utils/concurrent/Future.java
new file mode 100644
index 0000000..69dc83d
--- /dev/null
+++ b/accord-core/src/main/java/org/apache/cassandra/utils/concurrent/Future.java
@@ -0,0 +1,191 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.utils.concurrent;
+
+import java.util.concurrent.Executor;
+import java.util.function.BiConsumer;
+import java.util.function.Consumer;
+import java.util.function.Function;
+
+import com.google.common.util.concurrent.AsyncFunction;
+import com.google.common.util.concurrent.FutureCallback;
+import com.google.common.util.concurrent.ListenableFuture; // checkstyle: permit this import
+
+import io.netty.util.concurrent.GenericFutureListener;
+
+import io.netty.util.internal.PlatformDependent;
+import org.apache.cassandra.utils.Shared;
+
+import static java.util.concurrent.TimeUnit.MILLISECONDS;
+import static org.apache.cassandra.utils.Shared.Recursive.INTERFACES;
+import static org.apache.cassandra.utils.Shared.Scope.SIMULATION;
+
+/**
+ * A Future that integrates several different (but equivalent) APIs used within Cassandra into a single concept,
+ * integrating also with our {@link Awaitable} abstraction, to overall improve coherency and clarity in the codebase.
+ */
+@Shared(scope = SIMULATION, ancestors = INTERFACES)
+public interface Future<V> extends io.netty.util.concurrent.Future<V>, ListenableFuture<V>, Awaitable
+{
+ /**
+ * Wait indefinitely for this future to complete, throwing any interrupt
+ * @throws InterruptedException if interrupted
+ */
+ @Override
+ Future<V> await() throws InterruptedException;
+
+ /**
+ * Wait indefinitely for this future to complete
+ */
+ @Override
+ Future<V> awaitUninterruptibly();
+
+ /**
+ * Wait indefinitely for this promise to complete, throwing any interrupt as an UncheckedInterruptedException
+ * @throws UncheckedInterruptedException if interrupted
+ */
+ @Override
+ Future<V> awaitThrowUncheckedOnInterrupt();
+
+ default void rethrowIfFailed()
+ {
+ Throwable cause = this.cause();
+ if (cause != null)
+ {
+ PlatformDependent.throwException(cause);
+ }
+ }
+
+ /**
+ * waits for completion; in case of failure rethrows the original exception without a new wrapping exception
+ * so may cause problems for reporting stack traces
+ */
+ @Override
+ default Future<V> sync() throws InterruptedException
+ {
+ await();
+ rethrowIfFailed();
+ return this;
+ }
+
+ /**
+ * waits for completion; in case of failure rethrows the original exception without a new wrapping exception
+ * so may cause problems for reporting stack traces
+ */
+ @Override
+ default Future<V> syncUninterruptibly()
+ {
+ awaitUninterruptibly();
+ rethrowIfFailed();
+ return this;
+ }
+
+ @Deprecated
+ @Override
+ default boolean await(long l) throws InterruptedException
+ {
+ return await(l, MILLISECONDS);
+ }
+
+ @Deprecated
+ @Override
+ default boolean awaitUninterruptibly(long l)
+ {
+ return awaitUninterruptibly(l, MILLISECONDS);
+ }
+
+ /**
+ * Support {@link com.google.common.util.concurrent.Futures#addCallback} natively
+ */
+ Future<V> addCallback(BiConsumer<? super V, Throwable> callback);
+
+ /**
+ * Support {@link com.google.common.util.concurrent.Futures#addCallback} natively
+ */
+ Future<V> addCallback(BiConsumer<? super V, Throwable> callback, Executor executor);
+
+ /**
+ * Support {@link com.google.common.util.concurrent.Futures#addCallback} natively
+ */
+ Future<V> addCallback(FutureCallback<? super V> callback);
+
+ /**
+ * Support {@link com.google.common.util.concurrent.Futures#addCallback} natively
+ */
+ Future<V> addCallback(FutureCallback<? super V> callback, Executor executor);
+
+ /**
+ * Support {@link com.google.common.util.concurrent.Futures#addCallback} natively
+ */
+ Future<V> addCallback(Consumer<? super V> onSuccess, Consumer<? super Throwable> onFailure);
+
+ /**
+ * Support {@link com.google.common.util.concurrent.Futures#addCallback} natively
+ */
+ Future<V> addCallback(Consumer<? super V> onSuccess, Consumer<? super Throwable> onFailure, Executor executor);
+
+ /**
+ * Support {@link com.google.common.util.concurrent.Futures#transform(ListenableFuture, com.google.common.base.Function, Executor)} natively
+ */
+ default <T> Future<T> map(Function<? super V, ? extends T> mapper)
+ {
+ return map(mapper, null);
+ }
+
+ /**
+ * Support {@link com.google.common.util.concurrent.Futures#transform(ListenableFuture, com.google.common.base.Function, Executor)} natively
+ */
+ <T> Future<T> map(Function<? super V, ? extends T> mapper, Executor executor);
+
+ /**
+ * Support {@link com.google.common.util.concurrent.Futures#transformAsync(ListenableFuture, AsyncFunction, Executor)} natively
+ */
+ default <T> Future<T> flatMap(Function<? super V, ? extends Future<T>> flatMapper)
+ {
+ return flatMap(flatMapper, null);
+ }
+
+ /**
+ * Support {@link com.google.common.util.concurrent.Futures#transformAsync(ListenableFuture, AsyncFunction, Executor)} natively
+ */
+ <T> Future<T> flatMap(Function<? super V, ? extends Future<T>> flatMapper, Executor executor);
+
+ /**
+ * Invoke {@code runnable} on completion, using {@code executor}.
+ *
+ * Tasks are submitted to their executors in the order they were added to this Future.
+ */
+ @Override
+ void addListener(Runnable runnable, Executor executor);
+
+ /**
+ * Invoke {@code runnable} on completion. Depending on the implementation and its configuration, this
+ * may be executed immediately by the notifying/completing thread, or asynchronously by an executor.
+ * Tasks are executed, or submitted to the executor, in the order they were added to this Future.
+ */
+ void addListener(Runnable runnable);
+
+ Executor notifyExecutor();
+
+ @Override Future<V> addListener(GenericFutureListener<? extends io.netty.util.concurrent.Future<? super V>> genericFutureListener);
+ @Override Future<V> addListeners(GenericFutureListener<? extends io.netty.util.concurrent.Future<? super V>>... genericFutureListeners);
+ @Override Future<V> removeListener(GenericFutureListener<? extends io.netty.util.concurrent.Future<? super V>> genericFutureListener);
+ @Override Future<V> removeListeners(GenericFutureListener<? extends io.netty.util.concurrent.Future<? super V>>... genericFutureListeners);
+}
+
diff --git a/accord-core/src/main/java/org/apache/cassandra/utils/concurrent/ImmediateFuture.java b/accord-core/src/main/java/org/apache/cassandra/utils/concurrent/ImmediateFuture.java
new file mode 100644
index 0000000..159d580
--- /dev/null
+++ b/accord-core/src/main/java/org/apache/cassandra/utils/concurrent/ImmediateFuture.java
@@ -0,0 +1,52 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.utils.concurrent;
+
+public class ImmediateFuture<V> extends AsyncFuture<V>
+{
+ private ImmediateFuture(V value)
+ {
+ super(value);
+ }
+
+ private ImmediateFuture(Throwable cause)
+ {
+ super(cause);
+ }
+
+ private ImmediateFuture(FailureHolder failure)
+ {
+ super(failure);
+ }
+
+ public static <V> ImmediateFuture<V> success(V value)
+ {
+ return new ImmediateFuture<>(value);
+ }
+
+ public static <V> ImmediateFuture<V> failure(Throwable cause)
+ {
+ return new ImmediateFuture<>(cause);
+ }
+
+ public static <V> ImmediateFuture<V> cancelled()
+ {
+ return new ImmediateFuture<>(CANCELLED);
+ }
+}
diff --git a/accord-core/src/main/java/org/apache/cassandra/utils/concurrent/Inline.java b/accord-core/src/main/java/org/apache/cassandra/utils/concurrent/Inline.java
new file mode 100644
index 0000000..02e71eb
--- /dev/null
+++ b/accord-core/src/main/java/org/apache/cassandra/utils/concurrent/Inline.java
@@ -0,0 +1,5 @@
+package org.apache.cassandra.utils.concurrent;
+
+public @interface Inline
+{
+}
diff --git a/accord-core/src/main/java/org/apache/cassandra/utils/concurrent/IntrusiveStack.java b/accord-core/src/main/java/org/apache/cassandra/utils/concurrent/IntrusiveStack.java
new file mode 100644
index 0000000..7ff7387
--- /dev/null
+++ b/accord-core/src/main/java/org/apache/cassandra/utils/concurrent/IntrusiveStack.java
@@ -0,0 +1,156 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.utils.concurrent;
+
+//import net.nicoulaj.compilecommand.annotations.Inline;
+
+import java.util.Iterator;
+import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
+import java.util.function.BiFunction;
+import java.util.function.Consumer;
+
+/**
+ * An efficient stack/list that is expected to be ordinarily either empty or close to, and for which
+ * we need concurrent insertions and do not need to support removal - i.e. the list is semi immutable.
+ *
+ * This is an intrusive stack, and for simplicity we treat all
+ *
+ * @param <T>
+ */
+public class IntrusiveStack<T extends IntrusiveStack<T>> implements Iterable<T>
+{
+ static class Itr<T extends IntrusiveStack<T>> implements Iterator<T>
+ {
+ private T next;
+
+ Itr(T next)
+ {
+ this.next = next;
+ }
+
+ @Override
+ public boolean hasNext()
+ {
+ return next != null;
+ }
+
+ @Override
+ public T next()
+ {
+ T result = next;
+ next = result.next;
+ return result;
+ }
+ }
+
+ T next;
+
+ @Inline
+ protected static <O, T extends IntrusiveStack<T>> void push(AtomicReferenceFieldUpdater<? super O, T> headUpdater, O owner, T prepend)
+ {
+ push(headUpdater, owner, prepend, (prev, next) -> {
+ next.next = prev;
+ return next;
+ });
+ }
+
+ protected static <O, T extends IntrusiveStack<T>> void push(AtomicReferenceFieldUpdater<O, T> headUpdater, O owner, T prepend, BiFunction<T, T, T> combine)
+ {
+ while (true)
+ {
+ T head = headUpdater.get(owner);
+ if (headUpdater.compareAndSet(owner, head, combine.apply(head, prepend)))
+ return;
+ }
+ }
+
+ protected static <O, T extends IntrusiveStack<T>> void pushExclusive(AtomicReferenceFieldUpdater<O, T> headUpdater, O owner, T prepend, BiFunction<T, T, T> combine)
+ {
+ T head = headUpdater.get(owner);
+ headUpdater.lazySet(owner, combine.apply(head, prepend));
+ }
+
+ protected static <T extends IntrusiveStack<T>, O> Iterable<T> iterable(AtomicReferenceFieldUpdater<O, T> headUpdater, O owner)
+ {
+ return iterable(headUpdater.get(owner));
+ }
+
+ protected static <T extends IntrusiveStack<T>> Iterable<T> iterable(T list)
+ {
+ return list == null ? () -> iterator(null) : list;
+ }
+
+ protected static <T extends IntrusiveStack<T>> Iterator<T> iterator(T list)
+ {
+ return new Itr<>(list);
+ }
+
+ protected static int size(IntrusiveStack<?> list)
+ {
+ int size = 0;
+ while (list != null)
+ {
+ ++size;
+ list = list.next;
+ }
+ return size;
+ }
+
+ // requires exclusive ownership (incl. with readers)
+ protected T reverse()
+ {
+ return reverse((T) this);
+ }
+
+ // requires exclusive ownership (incl. with readers)
+ protected static <T extends IntrusiveStack<T>> T reverse(T list)
+ {
+ T prev = null;
+ T cur = list;
+ while (cur != null)
+ {
+ T next = cur.next;
+ cur.next = prev;
+ prev = cur;
+ cur = next;
+ }
+ return prev;
+ }
+
+ @Override
+ public void forEach(Consumer<? super T> forEach)
+ {
+ forEach((T)this, forEach);
+ }
+
+ protected static <T extends IntrusiveStack<T>> void forEach(T list, Consumer<? super T> forEach)
+ {
+ while (list != null)
+ {
+ forEach.accept(list);
+ list = list.next;
+ }
+ }
+
+ @Override
+ public Iterator<T> iterator()
+ {
+ return new Itr<>((T) this);
+ }
+}
diff --git a/accord-core/src/main/java/org/apache/cassandra/utils/concurrent/ListenerList.java b/accord-core/src/main/java/org/apache/cassandra/utils/concurrent/ListenerList.java
new file mode 100644
index 0000000..c82b80c
--- /dev/null
+++ b/accord-core/src/main/java/org/apache/cassandra/utils/concurrent/ListenerList.java
@@ -0,0 +1,376 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.utils.concurrent;
+
+import com.google.common.util.concurrent.FutureCallback;
+import io.netty.util.concurrent.EventExecutor;
+import io.netty.util.concurrent.GenericFutureListener;
+//import net.nicoulaj.compilecommand.annotations.Inline;
+import org.apache.cassandra.concurrent.ExecutionFailure;
+import org.apache.cassandra.concurrent.ExecutorPlus;
+import org.apache.cassandra.concurrent.ImmediateExecutor;
+
+import javax.annotation.Nullable;
+import java.util.concurrent.Executor;
+import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
+import java.util.function.BiConsumer;
+import java.util.function.Consumer;
+
+import static org.apache.cassandra.utils.concurrent.ListenerList.Notifying.NOTIFYING;
+
+/**
+ * Encapsulate one or more items in a linked-list that is immutable whilst shared, forming a prepend-only list (or stack).
+ * Once the list is ready to consume, exclusive ownership is taken by clearing the shared variable containing it, after
+ * which the list may be invoked using {@link #notify}, which reverses the list before invoking the work it contains.
+ */
+abstract class ListenerList<V> extends IntrusiveStack<ListenerList<V>>
+{
+ abstract void notifySelf(Executor notifyExecutor, Future<V> future);
+
+ static ListenerList pushHead(ListenerList prev, ListenerList next)
+ {
+ if (prev instanceof Notifying<?>)
+ {
+ Notifying result = new Notifying();
+ result.next = next;
+ next.next = prev == NOTIFYING ? null : prev;
+ return result;
+ }
+ next.next = prev;
+ return next;
+ }
+
+ /**
+ * Logically append {@code newListener} to {@link #listeners}
+ * (at this stage it is a stack, so we actually prepend)
+ *
+ * @param newListener must be either a {@link ListenerList} or {@link GenericFutureListener}
+ */
+ @Inline
+ static <T> void push(AtomicReferenceFieldUpdater<? super T, ListenerList> updater, T in, ListenerList newListener)
+ {
+ IntrusiveStack.push(updater, in, newListener, ListenerList::pushHead);
+ }
+
+ /**
+ * Logically append {@code newListener} to {@link #listeners}
+ * (at this stage it is a stack, so we actually prepend)
+ *
+ * @param newListener must be either a {@link ListenerList} or {@link GenericFutureListener}
+ */
+ @Inline
+ static <T> void pushExclusive(AtomicReferenceFieldUpdater<? super T, ListenerList> updater, T in, ListenerList newListener)
+ {
+ IntrusiveStack.pushExclusive(updater, in, newListener, ListenerList::pushHead);
+ }
+
+ static <V, T extends Future<V>> void notify(AtomicReferenceFieldUpdater<? super T, ListenerList> updater, T in)
+ {
+ while (true)
+ {
+ ListenerList<V> listeners = updater.get(in);
+ if (listeners == null || listeners instanceof Notifying)
+ return; // either no listeners, or we are already notifying listeners, so we'll get to the new one when ready
+
+ if (updater.compareAndSet(in, listeners, NOTIFYING))
+ {
+ while (true)
+ {
+ notify(listeners, in);
+ if (updater.compareAndSet(in, NOTIFYING, null))
+ return;
+
+ listeners = updater.getAndSet(in, NOTIFYING);
+ }
+ }
+ }
+ }
+
+ /**
+ * Requires exclusive ownership of {@code head}.
+ *
+ * Task submission occurs in the order the operations were submitted; if all of the executors
+ * are immediate or unspecified this guarantees execution order.
+ * Tasks are submitted to the executor individually, as this simplifies semantics and
+ * we anticipate few listeners in practice, and even fewer with indirect executors.
+ *
+ * @param head must be either a {@link ListenerList} or {@link GenericFutureListener}
+ */
+ static <T> void notify(ListenerList<T> head, Future<T> future)
+ {
+ Executor notifyExecutor = future.notifyExecutor();
+ if (inExecutor(notifyExecutor))
+ notifyExecutor = null;
+
+ notify(head, notifyExecutor, future);
+ }
+
+ private static <T> void notify(ListenerList<T> head, Executor notifyExecutor, Future<T> future)
+ {
+ head = reverse(head);
+ forEach(head, i -> i.notifySelf(notifyExecutor, future));
+ }
+
+ /**
+ * Notify {@code listener} on the invoking thread, handling any exceptions
+ */
+ static <F extends io.netty.util.concurrent.Future<?>> void notifyListener(GenericFutureListener<F> listener, F future)
+ {
+ try
+ {
+ listener.operationComplete(future);
+ }
+ catch (Throwable t)
+ {
+ // TODO: suboptimal package interdependency - move FutureTask etc here?
+ ExecutionFailure.handle(t);
+ }
+ }
+
+ /**
+ * Notify {@code listener} using {@code notifyExecutor} if set, and handling exceptions otherwise
+ */
+ static <F extends io.netty.util.concurrent.Future<?>> void notifyListener(Executor notifyExecutor, GenericFutureListener<F> listener, F future)
+ {
+ if (notifyExecutor == null) notifyListener(listener, future);
+ else safeExecute(notifyExecutor, () -> notifyListener(listener, future));
+ }
+
+ /**
+ * Notify {@code listener} using {@code notifyExecutor} if set, and handling exceptions otherwise
+ */
+ static void notifyListener(@Nullable Executor notifyExecutor, Runnable listener)
+ {
+ safeExecute(notifyExecutor, listener);
+ }
+
+ private static void safeExecute(@Nullable Executor notifyExecutor, Runnable runnable)
+ {
+ if (notifyExecutor == null)
+ notifyExecutor = ImmediateExecutor.INSTANCE;
+ try
+ {
+ notifyExecutor.execute(runnable);
+ }
+ catch (Exception | Error e)
+ {
+ // TODO: suboptimal package interdependency - move FutureTask etc here?
+ ExecutionFailure.handle(e);
+ }
+ }
+
+ /**
+ * Encapsulate a regular listener in a linked list
+ */
+ static class GenericFutureListenerList<V> extends ListenerList<V>
+ {
+ final GenericFutureListener listener;
+
+ GenericFutureListenerList(GenericFutureListener listener)
+ {
+ this.listener = listener;
+ }
+
+ @Override
+ void notifySelf(Executor notifyExecutor, Future<V> future)
+ {
+ notifyListener(notifyExecutor, listener, future);
+ }
+ }
+
+ /**
+ * Encapsulates the invocation of a callback with everything needed to submit for execution
+ * without incurring significant further overhead as a list
+ */
+ static class CallbackListener<V> extends ListenerList<V> implements Runnable
+ {
+ final Future<V> future;
+ final FutureCallback<? super V> callback;
+
+ CallbackListener(Future<V> future, FutureCallback<? super V> callback)
+ {
+ this.future = future;
+ this.callback = callback;
+ }
+
+ @Override
+ public void run()
+ {
+ if (future.isSuccess()) callback.onSuccess(future.getNow());
+ else callback.onFailure(future.cause());
+ }
+
+ @Override
+ void notifySelf(Executor notifyExecutor, Future<V> future)
+ {
+ notifyListener(notifyExecutor, this);
+ }
+ }
+
+ /**
+ * Encapsulates the invocation of a callback with everything needed to submit for execution
+ * without incurring significant further overhead as a list
+ */
+ static class CallbackBiConsumerListener<V> extends ListenerList<V> implements Runnable
+ {
+ final Future<V> future;
+ final BiConsumer<? super V, Throwable> callback;
+ final Executor executor;
+
+ CallbackBiConsumerListener(Future<V> future, BiConsumer<? super V, Throwable> callback, Executor executor)
+ {
+ this.future = future;
+ this.callback = callback;
+ this.executor = executor;
+ }
+
+ @Override
+ public void run()
+ {
+ if (future.isSuccess()) callback.accept(future.getNow(), null);
+ else callback.accept(null, future.cause());
+ }
+
+ @Override
+ void notifySelf(Executor notifyExecutor, Future<V> future)
+ {
+ notifyListener(executor == null ? notifyExecutor : executor, this);
+ }
+ }
+
+ /**
+ * Encapsulates the invocation of a callback with everything needed to submit for execution
+ * without incurring significant further overhead as a list
+ */
+ static class CallbackListenerWithExecutor<V> extends CallbackListener<V>
+ {
+ final Executor executor;
+ CallbackListenerWithExecutor(Future<V> future, FutureCallback<? super V> callback, Executor executor)
+ {
+ super(future, callback);
+ this.executor = executor;
+ }
+
+ @Override
+ void notifySelf(Executor notifyExecutor, Future<V> future)
+ {
+ notifyListener(executor, this);
+ }
+ }
+
+ /**
+ * Encapsulates the invocation of a callback with everything needed to submit for execution
+ * without incurring significant further overhead as a list
+ */
+ static class CallbackLambdaListener<V> extends ListenerList<V> implements Runnable
+ {
+ final Future<V> future;
+ final Consumer<? super V> onSuccess;
+ final Consumer<? super Throwable> onFailure;
+ final Executor executor;
+
+ CallbackLambdaListener(Future<V> future, Consumer<? super V> onSuccess, Consumer<? super Throwable> onFailure, Executor executor)
+ {
+ this.future = future;
+ this.onSuccess = onSuccess;
+ this.onFailure = onFailure;
+ this.executor = executor;
+ }
+
+ @Override
+ public void run()
+ {
+ if (future.isSuccess()) onSuccess.accept(future.getNow());
+ else onFailure.accept(future.cause());
+ }
+
+ @Override
+ void notifySelf(Executor notifyExecutor, Future future)
+ {
+ notifyListener(executor == null ? notifyExecutor : executor, this);
+ }
+ }
+
+ /**
+ * Encapsulate a task, executable on completion by {@link Future#notifyExecutor}, in a linked list for storing in
+ * {@link #listeners}, either as a listener on its own (since we need to encapsulate it anyway), or alongside
+ * other listeners in a list
+ */
+ static class RunnableWithNotifyExecutor<V> extends ListenerList<V>
+ {
+ final Runnable task;
+ RunnableWithNotifyExecutor(Runnable task)
+ {
+ this.task = task;
+ }
+
+ @Override
+ void notifySelf(Executor notifyExecutor, Future<V> future)
+ {
+ notifyListener(notifyExecutor, task);
+ }
+ }
+
+ /**
+ * Encapsulate a task executable on completion in a linked list for storing in {@link #listeners},
+ * either as a listener on its own (since we need to encapsulate it anyway), or alongside other listeners
+ * in a list
+ */
+ static class RunnableWithExecutor<V> extends ListenerList<V>
+ {
+ final Runnable task;
+ @Nullable final Executor executor;
+ RunnableWithExecutor(Runnable task, @Nullable Executor executor)
+ {
+ this.task = task;
+ this.executor = executor;
+ }
+
+ @Override
+ void notifySelf(Executor notifyExecutor, Future<V> future)
+ {
+ notifyListener(inExecutor(executor) ? null : executor, task);
+ }
+ }
+
+ /**
+ * Dummy that indicates listeners are already being notified after the future was completed,
+ * so we cannot notify them ourselves whilst maintaining the guaranteed invocation order.
+ * The invocation of the list can be left to the thread already notifying listeners.
+ */
+ static class Notifying<V> extends ListenerList<V>
+ {
+ static final Notifying NOTIFYING = new Notifying();
+
+ @Override
+ void notifySelf(Executor notifyExecutor, Future<V> future)
+ {
+ }
+ }
+
+ /**
+ * @return true iff the invoking thread is executing {@code executor}
+ */
+ static boolean inExecutor(Executor executor)
+ {
+ return (executor instanceof EventExecutor && ((EventExecutor) executor).inEventLoop())
+ || (executor instanceof ExecutorPlus && ((ExecutorPlus) executor).inExecutor());
+ }
+}
+
diff --git a/accord-core/src/main/java/org/apache/cassandra/utils/concurrent/Promise.java b/accord-core/src/main/java/org/apache/cassandra/utils/concurrent/Promise.java
new file mode 100644
index 0000000..2e84d33
--- /dev/null
+++ b/accord-core/src/main/java/org/apache/cassandra/utils/concurrent/Promise.java
@@ -0,0 +1,128 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.utils.concurrent;
+
+import com.google.common.util.concurrent.FutureCallback;
+import io.netty.util.concurrent.GenericFutureListener;
+import org.apache.cassandra.utils.Shared;
+
+import java.util.concurrent.Executor;
+import java.util.concurrent.ExecutorService;
+import java.util.function.Consumer;
+
+import static org.apache.cassandra.utils.Shared.Recursive.INTERFACES;
+import static org.apache.cassandra.utils.Shared.Scope.SIMULATION;
+
+/**
+ * A Promise that integrates {@link io.netty.util.concurrent.Promise} with our {@link Future} API
+ * to improve clarity and coherence in the codebase.
+ */
+@Shared(scope = SIMULATION, ancestors = INTERFACES)
+public interface Promise<V> extends io.netty.util.concurrent.Promise<V>, Future<V>
+{
+ public static <V> GenericFutureListener<? extends Future<V>> listener(FutureCallback<V> callback)
+ {
+ return future -> {
+ if (future.isSuccess()) callback.onSuccess(future.getNow());
+ else callback.onFailure(future.cause());
+ };
+ }
+
+ public static <V> GenericFutureListener<? extends Future<V>> listener(ExecutorService executor, FutureCallback<V> callback)
+ {
+ return future -> executor.execute(() -> {
+ if (future.isSuccess()) callback.onSuccess(future.getNow());
+ else callback.onFailure(future.cause());
+ });
+ }
+
+ @Override
+ Promise<V> addCallback(FutureCallback<? super V> callback);
+
+ Promise<V> addCallback(FutureCallback<? super V> callback, Executor executor);
+
+ Promise<V> addCallback(Consumer<? super V> onSuccess, Consumer<? super Throwable> onFailure);
+
+ @Override
+ Promise<V> addListener(GenericFutureListener<? extends io.netty.util.concurrent.Future<? super V>> var1);
+
+ @Override
+ Promise<V> addListeners(GenericFutureListener<? extends io.netty.util.concurrent.Future<? super V>>... var1);
+
+ @Override
+ Promise<V> removeListener(GenericFutureListener<? extends io.netty.util.concurrent.Future<? super V>> var1);
+
+ @Override
+ Promise<V> removeListeners(GenericFutureListener<? extends io.netty.util.concurrent.Future<? super V>>... var1);
+
+ /**
+ * Complete the promise successfully if not already complete
+ * @throws IllegalStateException if already set
+ */
+ @Override
+ Promise<V> setSuccess(V v) throws IllegalStateException;
+
+ /**
+ * Complete the promise abnormally if not already complete
+ * @throws IllegalStateException if already set
+ */
+ @Override
+ Promise<V> setFailure(Throwable throwable) throws IllegalStateException;
+
+ /**
+ * Prevent a future caller from cancelling this promise
+ * @return true iff this invocation set it to uncancellable, whether or not now uncancellable
+ */
+ boolean setUncancellableExclusive();
+
+ /**
+ * Wait indefinitely for this promise to complete, throwing any interrupt
+ * @throws InterruptedException if interrupted
+ */
+ @Override
+ Promise<V> await() throws InterruptedException;
+
+ /**
+ * Wait indefinitely for this promise to complete
+ */
+ @Override
+ Promise<V> awaitUninterruptibly();
+
+ /**
+ * Wait indefinitely for this promise to complete, throwing any interrupt as an UncheckedInterruptedException
+ * @throws UncheckedInterruptedException if interrupted
+ */
+ @Override
+ Promise<V> awaitThrowUncheckedOnInterrupt();
+
+ /**
+ * waits for completion; in case of failure rethrows the original exception without a new wrapping exception
+ * so may cause problems for reporting stack traces
+ */
+ @Override
+ Promise<V> sync() throws InterruptedException;
+
+ /**
+ * waits for completion; in case of failure rethrows the original exception without a new wrapping exception
+ * so may cause problems for reporting stack traces
+ */
+ @Override
+ Promise<V> syncUninterruptibly();
+}
+
diff --git a/accord-core/src/main/java/org/apache/cassandra/utils/concurrent/UncheckedInterruptedException.java b/accord-core/src/main/java/org/apache/cassandra/utils/concurrent/UncheckedInterruptedException.java
new file mode 100644
index 0000000..d7248e8
--- /dev/null
+++ b/accord-core/src/main/java/org/apache/cassandra/utils/concurrent/UncheckedInterruptedException.java
@@ -0,0 +1,38 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.utils.concurrent;
+
+import org.apache.cassandra.utils.Shared;
+
+import static org.apache.cassandra.utils.Shared.Scope.SIMULATION;
+
+/**
+ * Unchecked {@link InterruptedException}, to be thrown in places where an interrupt is unexpected
+ */
+@Shared(scope = SIMULATION)
+public class UncheckedInterruptedException extends RuntimeException
+{
+ public UncheckedInterruptedException()
+ {
+ }
+ public UncheckedInterruptedException(InterruptedException cause)
+ {
+ super(cause);
+ }
+}
diff --git a/accord-core/src/main/java/org/apache/cassandra/utils/concurrent/WaitQueue.java b/accord-core/src/main/java/org/apache/cassandra/utils/concurrent/WaitQueue.java
new file mode 100644
index 0000000..d2a841d
--- /dev/null
+++ b/accord-core/src/main/java/org/apache/cassandra/utils/concurrent/WaitQueue.java
@@ -0,0 +1,437 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.cassandra.utils.concurrent;
+
+import java.util.Iterator;
+import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
+import java.util.concurrent.locks.LockSupport;
+import java.util.function.BooleanSupplier;
+import java.util.function.Consumer;
+
+import org.apache.cassandra.utils.Intercept;
+import org.apache.cassandra.utils.Shared;
+import org.apache.cassandra.utils.concurrent.Awaitable.AbstractAwaitable;
+
+import static org.apache.cassandra.utils.Clock.Global.nanoTime;
+import static org.apache.cassandra.utils.Shared.Recursive.INTERFACES;
+import static org.apache.cassandra.utils.Shared.Scope.SIMULATION;
+
+/**
+ * <p>A relatively easy to use utility for general purpose thread signalling.</p>
+ * <p>Usage on a thread awaiting a state change using a WaitQueue q is:</p>
+ * <pre>
+ * {@code
+ * while (!conditionMet())
+ * Signal s = q.register();
+ * if (!conditionMet()) // or, perhaps more correctly, !conditionChanged()
+ * s.await();
+ * else
+ * s.cancel();
+ * }
+ * </pre>
+ * A signalling thread, AFTER changing the state, then calls q.signal() to wake up one, or q.signalAll()
+ * to wake up all, waiting threads.
+ * <p>To understand intuitively how this class works, the idea is simply that a thread, once it considers itself
+ * incapable of making progress, registers to be awoken once that changes. Since this could have changed between
+ * checking and registering (in which case the thread that made this change would have been unable to signal it),
+ * it checks the condition again, sleeping only if it hasn't changed/still is not met.</p>
+ * <p>This thread synchronisation scheme has some advantages over Condition objects and Object.wait/notify in that no monitor
+ * acquisition is necessary and, in fact, besides the actual waiting on a signal, all operations are non-blocking.
+ * As a result consumers can never block producers, nor each other, or vice versa, from making progress.
+ * Threads that are signalled are also put into a RUNNABLE state almost simultaneously, so they can all immediately make
+ * progress without having to serially acquire the monitor/lock, reducing scheduler delay incurred.</p>
+ *
+ * <p>A few notes on utilisation:</p>
+ * <p>1. A thread will only exit await() when it has been signalled, but this does not guarantee the condition has not
+ * been altered since it was signalled, and depending on your design it is likely the outer condition will need to be
+ * checked in a loop, though this is not always the case.</p>
+ * <p>2. Each signal is single use, so must be re-registered after each await(). This is true even if it times out.</p>
+ * <p>3. If you choose not to wait on the signal (because the condition has been met before you waited on it)
+ * you must cancel() the signal if the signalling thread uses signal() to awake waiters; otherwise signals will be
+ * lost. If signalAll() is used but infrequent, and register() is frequent, cancel() should still be used to prevent the
+ * queue growing unboundedly. Similarly, if you provide a TimerContext, cancel should be used to ensure it is not erroneously
+ * counted towards wait time.</p>
+ * <p>4. Care must be taken when selecting conditionMet() to ensure we are waiting on the condition that actually
+ * indicates progress is possible. In some complex cases it may be tempting to wait on a condition that is only indicative
+ * of local progress, not progress on the task we are aiming to complete, and a race may leave us waiting for a condition
+ * to be met that we no longer need.
+ * <p>5. This scheme is not fair</p>
+ * <p>6. Only the thread that calls register() may call await()</p>
+ *
+ * TODO: this class should not be backed by CLQ (should use an intrusive linked-list with lower overhead)
+ */
+@Shared(scope = SIMULATION, inner = INTERFACES)
+public interface WaitQueue
+{
+ /**
+ * A Signal is a one-time-use mechanism for a thread to wait for notification that some condition
+ * state has transitioned that it may be interested in (and hence should check if it is).
+ * It is potentially transient, i.e. the state can change in the meantime, it only indicates
+ * that it should be checked, not necessarily anything about what the expected state should be.
+ *
+ * Signal implementations should never wake up spuriously, they are always woken up by a
+ * signal() or signalAll().
+ *
+ * This abstract definition of Signal does not need to be tied to a WaitQueue.
+ * Whilst RegisteredSignal is the main building block of Signals, this abstract
+ * definition allows us to compose Signals in useful ways. The Signal is 'owned' by the
+ * thread that registered itself with WaitQueue(s) to obtain the underlying RegisteredSignal(s);
+ * only the owning thread should use a Signal.
+ */
+ public static interface Signal extends Condition
+ {
+ /**
+ * @return true if cancelled; once cancelled, must be discarded by the owning thread.
+ */
+ public boolean isCancelled();
+
+ /**
+ * @return isSignalled() || isCancelled(). Once true, the state is fixed and the Signal should be discarded
+ * by the owning thread.
+ */
+ public boolean isSet();
+
+ /**
+ * atomically: cancels the Signal if !isSet(), or returns true if isSignalled()
+ *
+ * @return true if isSignalled()
+ */
+ public boolean checkAndClear();
+
+ /**
+ * Should only be called by the owning thread. Indicates the signal can be retired,
+ * and if signalled propagates the signal to another waiting thread
+ */
+ public abstract void cancel();
+ }
+
+ /**
+ * The calling thread MUST be the thread that uses the signal
+ */
+ public Signal register();
+
+ /**
+ * The calling thread MUST be the thread that uses the signal.
+ * If the Signal is waited on, context.stop() will be called when the wait times out, the Signal is signalled,
+ * or the waiting thread is interrupted.
+ */
+ public <V> Signal register(V supplyOnDone, Consumer<V> receiveOnDone);
+
+ /**
+ * Signal one waiting thread
+ */
+ public boolean signal();
+
+ /**
+ * Signal all waiting threads
+ */
+ public void signalAll();
+
+// /** getWaiting() > 0 */
+ public boolean hasWaiters();
+
+ /** Return how many threads are waiting */
+ public int getWaiting();
+
+ /**
+ * Factory method used to capture and redirect instantiations for simulation
+ */
+ @Intercept
+ public static WaitQueue newWaitQueue()
+ {
+ return new Standard();
+ }
+
+ class Standard implements WaitQueue
+ {
+ private static final int CANCELLED = -1;
+ private static final int SIGNALLED = 1;
+ private static final int NOT_SET = 0;
+
+ private static final AtomicIntegerFieldUpdater<RegisteredSignal> signalledUpdater = AtomicIntegerFieldUpdater.newUpdater(RegisteredSignal.class, "state");
+
+ // the waiting signals
+ private final ConcurrentLinkedQueue<RegisteredSignal> queue = new ConcurrentLinkedQueue<>();
+
+ protected Standard() {}
+
+ /**
+ * The calling thread MUST be the thread that uses the signal
+ * @return x
+ */
+ public Signal register()
+ {
+ RegisteredSignal signal = new RegisteredSignal();
+ queue.add(signal);
+ return signal;
+ }
+
+ /**
+ * The calling thread MUST be the thread that uses the signal.
+ * If the Signal is waited on, context.stop() will be called when the wait times out, the Signal is signalled,
+ * or the waiting thread is interrupted.
+ */
+ public <V> Signal register(V supplyOnDone, Consumer<V> receiveOnDone)
+ {
+ RegisteredSignal signal = new SignalWithListener<>(supplyOnDone, receiveOnDone);
+ queue.add(signal);
+ return signal;
+ }
+
+ /**
+ * Signal one waiting thread
+ */
+ public boolean signal()
+ {
+ while (true)
+ {
+ RegisteredSignal s = queue.poll();
+ if (s == null || s.doSignal() != null)
+ return s != null;
+ }
+ }
+
+ /**
+ * Signal all waiting threads
+ */
+ public void signalAll()
+ {
+ if (!hasWaiters())
+ return;
+
+ // to avoid a race where the condition is not met and the woken thread managed to wait on the queue before
+ // we finish signalling it all, we pick a random thread we have woken-up and hold onto it, so that if we encounter
+ // it again we know we're looping. We reselect a random thread periodically, progressively less often.
+ // the "correct" solution to this problem is to use a queue that permits snapshot iteration, but this solution is sufficient
+ // TODO: this is only necessary because we use CLQ - which is only for historical any-NIH reasons
+ int i = 0, s = 5;
+ Thread randomThread = null;
+ Iterator<RegisteredSignal> iter = queue.iterator();
+ while (iter.hasNext())
+ {
+ RegisteredSignal signal = iter.next();
+ Thread signalled = signal.doSignal();
+
+ if (signalled != null)
+ {
+ if (signalled == randomThread)
+ break;
+
+ if (++i == s)
+ {
+ randomThread = signalled;
+ s <<= 1;
+ }
+ }
+
+ iter.remove();
+ }
+ }
+
+ private void cleanUpCancelled()
+ {
+ // TODO: attempt to remove the cancelled from the beginning only (need atomic cas of head)
+ queue.removeIf(RegisteredSignal::isCancelled);
+ }
+
+ public boolean hasWaiters()
+ {
+ return !queue.isEmpty();
+ }
+
+ /**
+ * @return how many threads are waiting
+ */
+ public int getWaiting()
+ {
+ if (!hasWaiters())
+ return 0;
+ Iterator<RegisteredSignal> iter = queue.iterator();
+ int count = 0;
+ while (iter.hasNext())
+ {
+ Signal next = iter.next();
+ if (!next.isCancelled())
+ count++;
+ }
+ return count;
+ }
+
+ /**
+ * An abstract signal implementation
+ *
+ * TODO: use intrusive linked list
+ */
+ public static abstract class AbstractSignal extends AbstractAwaitable implements Signal
+ {
+ public Signal await() throws InterruptedException
+ {
+ while (!isSignalled())
+ {
+ checkInterrupted();
+ LockSupport.park();
+ }
+ checkAndClear();
+ return this;
+ }
+
+ public boolean awaitUntil(long nanoTimeDeadline) throws InterruptedException
+ {
+ long now;
+ while (nanoTimeDeadline > (now = nanoTime()) && !isSignalled())
+ {
+ checkInterrupted();
+ long delta = nanoTimeDeadline - now;
+ LockSupport.parkNanos(delta);
+ }
+ return checkAndClear();
+ }
+
+ private void checkInterrupted() throws InterruptedException
+ {
+ if (Thread.interrupted())
+ {
+ cancel();
+ throw new InterruptedException();
+ }
+ }
+ }
+
+ /**
+ * A signal registered with this WaitQueue
+ */
+ private class RegisteredSignal extends AbstractSignal
+ {
+ private volatile Thread thread = Thread.currentThread();
+ volatile int state;
+
+ public boolean isSignalled()
+ {
+ return state == SIGNALLED;
+ }
+
+ public boolean isCancelled()
+ {
+ return state == CANCELLED;
+ }
+
+ public boolean isSet()
+ {
+ return state != NOT_SET;
+ }
+
+ private Thread doSignal()
+ {
+ if (!isSet() && signalledUpdater.compareAndSet(this, NOT_SET, SIGNALLED))
+ {
+ Thread thread = this.thread;
+ LockSupport.unpark(thread);
+ this.thread = null;
+ return thread;
+ }
+ return null;
+ }
+
+ public void signal()
+ {
+ doSignal();
+ }
+
+ public boolean checkAndClear()
+ {
+ if (!isSet() && signalledUpdater.compareAndSet(this, NOT_SET, CANCELLED))
+ {
+ thread = null;
+ cleanUpCancelled();
+ return false;
+ }
+ // must now be signalled assuming correct API usage
+ return true;
+ }
+
+ /**
+ * Should only be called by the registered thread. Indicates the signal can be retired,
+ * and if signalled propagates the signal to another waiting thread
+ */
+ public void cancel()
+ {
+ if (isCancelled())
+ return;
+ if (!signalledUpdater.compareAndSet(this, NOT_SET, CANCELLED))
+ {
+ // must already be signalled - switch to cancelled and
+ state = CANCELLED;
+ // propagate the signal
+ Standard.this.signal();
+ }
+ thread = null;
+ cleanUpCancelled();
+ }
+ }
+
+ /**
+ * A RegisteredSignal that stores a TimerContext, and stops the timer when either cancelled or
+ * finished waiting. i.e. if the timer is started when the signal is registered it tracks the
+ * time in between registering and invalidating the signal.
+ */
+ private final class SignalWithListener<V> extends RegisteredSignal
+ {
+ private final V supplyOnDone;
+ private final Consumer<V> receiveOnDone;
+
+ private SignalWithListener(V supplyOnDone, Consumer<V> receiveOnDone)
+ {
+ this.receiveOnDone = receiveOnDone;
+ this.supplyOnDone = supplyOnDone;
+ }
+
+
+ @Override
+ public boolean checkAndClear()
+ {
+ receiveOnDone.accept(supplyOnDone);
+ return super.checkAndClear();
+ }
+
+ @Override
+ public void cancel()
+ {
+ if (!isCancelled())
+ {
+ receiveOnDone.accept(supplyOnDone);
+ super.cancel();
+ }
+ }
+ }
+ }
+
+ /**
+ * Loops waiting on the supplied condition and WaitQueue and will not return until the condition is true
+ */
+ public static void waitOnCondition(BooleanSupplier condition, WaitQueue queue) throws InterruptedException
+ {
+ while (!condition.getAsBoolean())
+ {
+ Signal s = queue.register();
+ if (!condition.getAsBoolean()) s.await();
+ else s.cancel();
+ }
+ }
+}
diff --git a/accord-core/src/test/java/accord/KeysTest.java b/accord-core/src/test/java/accord/KeysTest.java
index 61238f0..03f8bfd 100644
--- a/accord-core/src/test/java/accord/KeysTest.java
+++ b/accord-core/src/test/java/accord/KeysTest.java
@@ -32,4 +32,15 @@ public class KeysTest
keys(99, 100, 101, 199, 200, 201, 299, 300, 301)
.intersection(ranges(r(100, 200), r(200, 300))));
}
+
+ @Test
+ void mergeTest()
+ {
+ assertEquals(keys(0, 1, 2, 3, 4),
+ keys(0, 1, 2, 3, 4).merge(keys(0, 1, 2, 3, 4)));
+ assertEquals(keys(0, 1, 2, 3, 4),
+ keys(0, 1).merge(keys(2, 3, 4)));
+ assertEquals(keys(0, 1, 2, 3, 4),
+ keys(0, 2, 4).merge(keys(1, 3)));
+ }
}
diff --git a/accord-core/src/test/java/accord/burn/BurnTestConfigurationService.java b/accord-core/src/test/java/accord/burn/BurnTestConfigurationService.java
index 2a2872f..e7215f2 100644
--- a/accord-core/src/test/java/accord/burn/BurnTestConfigurationService.java
+++ b/accord-core/src/test/java/accord/burn/BurnTestConfigurationService.java
@@ -4,10 +4,11 @@ import accord.api.ConfigurationService;
import accord.api.MessageSink;
import accord.api.TestableConfigurationService;
import accord.local.Node;
-import accord.messages.Callback;
-import accord.messages.Reply;
-import accord.messages.Request;
+import accord.messages.*;
import accord.topology.Topology;
+import org.apache.cassandra.utils.concurrent.AsyncPromise;
+import org.apache.cassandra.utils.concurrent.Future;
+import org.apache.cassandra.utils.concurrent.ImmediateFuture;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -19,6 +20,7 @@ import java.util.function.Supplier;
public class BurnTestConfigurationService implements TestableConfigurationService
{
private static final Logger logger = LoggerFactory.getLogger(BurnTestConfigurationService.class);
+ private static final Future<Void> SUCCESS = ImmediateFuture.success(null);
private final Node.Id node;
private final MessageSink messageSink;
@@ -65,10 +67,16 @@ public class BurnTestConfigurationService implements TestableConfigurationServic
}
@Override
- public void process(Node on, Node.Id from, long messageId)
+ public void process(Node on, Node.Id from, ReplyContext replyContext)
{
Topology topology = on.configService().getTopologyForEpoch(epoch);
- on.reply(from, messageId, new FetchTopologyReply(topology));
+ on.reply(from, replyContext, new FetchTopologyReply(topology));
+ }
+
+ @Override
+ public MessageType type()
+ {
+ throw new UnsupportedOperationException();
}
@Override
@@ -87,6 +95,12 @@ public class BurnTestConfigurationService implements TestableConfigurationServic
this.topology = topology;
}
+ @Override
+ public MessageType type()
+ {
+ throw new UnsupportedOperationException();
+ }
+
@Override
public String toString()
{
@@ -95,7 +109,7 @@ public class BurnTestConfigurationService implements TestableConfigurationServic
}
}
- private class FetchTopology implements Callback<FetchTopologyReply>
+ private class FetchTopology extends AsyncPromise<Void> implements Callback<FetchTopologyReply>
{
private final FetchTopologyRequest request;
private final List<Node.Id> candidates;
@@ -109,16 +123,6 @@ public class BurnTestConfigurationService implements TestableConfigurationServic
sendNext();
}
- void onComplete(Runnable runnable)
- {
- onComplete.add(runnable);
- }
-
- synchronized void fireCallbacks()
- {
- onComplete.forEach(Runnable::run);
- }
-
synchronized void sendNext()
{
if (candidates.isEmpty())
@@ -150,17 +154,15 @@ public class BurnTestConfigurationService implements TestableConfigurationServic
private final Map<Long, FetchTopology> pendingEpochs = new HashMap<>();
@Override
- public synchronized void fetchTopologyForEpoch(long epoch, Runnable onComplete)
+ public synchronized Future<Void> fetchTopologyForEpoch(long epoch)
{
if (epoch < epochs.size())
{
- if (onComplete != null ) onComplete.run();
- return;
+ return SUCCESS;
}
FetchTopology fetch = pendingEpochs.computeIfAbsent(epoch, FetchTopology::new);
- if (onComplete != null)
- fetch.onComplete(onComplete);
+ return fetch;
}
@Override
@@ -179,7 +181,7 @@ public class BurnTestConfigurationService implements TestableConfigurationServic
if (topology.epoch() > epochs.size())
{
- fetchTopologyForEpoch(epochs.size() + 1, () -> reportTopology(topology));
+ fetchTopologyForEpoch(epochs.size() + 1).addListener(() -> reportTopology(topology));
return;
}
logger.trace("Epoch {} received by {}", topology.epoch(), node);
@@ -193,7 +195,7 @@ public class BurnTestConfigurationService implements TestableConfigurationServic
if (fetch == null)
return;
- fetch.fireCallbacks();
+ fetch.setSuccess(null);
}
}
diff --git a/accord-core/src/test/java/accord/burn/TopologyUpdate.java b/accord-core/src/test/java/accord/burn/TopologyUpdate.java
index eebdbf5..474c522 100644
--- a/accord-core/src/test/java/accord/burn/TopologyUpdate.java
+++ b/accord-core/src/test/java/accord/burn/TopologyUpdate.java
@@ -13,12 +13,13 @@ import accord.txn.*;
import accord.utils.MessageTask;
import com.google.common.base.Preconditions;
import com.google.common.collect.Sets;
+import org.apache.cassandra.utils.concurrent.AsyncPromise;
+import org.apache.cassandra.utils.concurrent.Future;
+import org.apache.cassandra.utils.concurrent.ImmediateFuture;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
-import java.util.concurrent.CompletableFuture;
-import java.util.concurrent.CompletionStage;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiConsumer;
@@ -30,7 +31,7 @@ public class TopologyUpdate
{
private static final Logger logger = LoggerFactory.getLogger(TopologyUpdate.class);
- private static class CountDownFuture<T> extends CompletableFuture<T>
+ private static class CountDownFuture<T> extends AsyncPromise<T>
{
private final AtomicInteger remaining;
private final T value;
@@ -49,7 +50,7 @@ public class TopologyUpdate
public void countDown()
{
if (remaining.decrementAndGet() == 0)
- complete(value);
+ setSuccess(value);
}
}
@@ -101,26 +102,28 @@ public class TopologyUpdate
}
}
- public static <T> Function<Throwable, T> dieOnException()
+ public static <T> BiConsumer<T, Throwable> dieOnException()
{
- return throwable -> {
- logger.error("", throwable);
- System.exit(1);
- return null;
+ return (result, throwable) -> {
+ if (throwable != null)
+ {
+ logger.error("", throwable);
+ System.exit(1);
+ }
};
}
- public static <T> CompletionStage<T> dieExceptionally(CompletionStage<T> stage)
+ public static <T> Future<T> dieExceptionally(Future<T> stage)
{
- return stage.exceptionally(dieOnException());
+ return stage.addCallback(dieOnException());
}
- private static <T> CompletionStage<Void> map(Collection<T> items, Function<T, CompletionStage<Void>> function)
+ private static <T> Future<Void> map(Collection<T> items, Function<T, Future<Void>> function)
{
CountDownFuture<Void> latch = new CountDownFuture<>(items.size());
for (T item : items)
{
- function.apply(item).thenRun(latch::countDown);
+ function.apply(item).addListener(latch::countDown);
}
return latch;
}
@@ -136,7 +139,7 @@ public class TopologyUpdate
});
}
- private static CompletionStage<Void> broadcast(List<Node.Id> cluster, Function<Node.Id, Node> lookup, String desc, BiConsumer<Node, Node.Id> process)
+ private static Future<Void> broadcast(List<Node.Id> cluster, Function<Node.Id, Node> lookup, String desc, BiConsumer<Node, Node.Id> process)
{
return map(cluster, node -> MessageTask.apply(lookup.apply(node), cluster, desc, process));
}
@@ -160,7 +163,7 @@ public class TopologyUpdate
return syncMessages.values().stream().map(cmd -> MessageTask.of(node, recipients.apply(cmd), "Sync:" + cmd.txnId + ':' + epoch + ':' + forEpoch, cmd::process));
}
- private static final boolean COMMITTED_ONLY = false;
+ private static final boolean COMMITTED_ONLY = true;
/**
* Syncs all replicated commands. Overkill, but useful for confirming issues in optimizedSync
@@ -228,16 +231,14 @@ public class TopologyUpdate
return messageStream;
}
- public static CompletionStage<Void> sync(Node node, long syncEpoch)
+ public static Future<Void> sync(Node node, long syncEpoch)
{
Stream<MessageTask> messageStream = optimizedSync(node, syncEpoch);
Iterator<MessageTask> iter = messageStream.iterator();
if (!iter.hasNext())
{
- CompletableFuture<Void> future = new CompletableFuture<>();
- future.complete(null);
- return future;
+ return ImmediateFuture.success(null);
}
MessageTask first = iter.next();
@@ -245,7 +246,7 @@ public class TopologyUpdate
while (iter.hasNext())
{
MessageTask next = iter.next();
- last.thenRun(next);
+ last.addListener(next);
last = next;
}
@@ -259,13 +260,14 @@ public class TopologyUpdate
// notify
dieExceptionally(notify(originator, cluster, update)
// sync operations
- .thenCompose(v -> map(cluster, node -> sync(lookup.apply(node), epoch - 1)))
+ .flatMap(v -> map(cluster, node -> sync(lookup.apply(node), epoch - 1)))
// inform sync complete
- .thenCompose(v -> broadcast(cluster, lookup, "SyncComplete:" + epoch, (node, from) -> node.onEpochSyncComplete(from, epoch))));
+ .flatMap(v -> broadcast(cluster, lookup, "SyncComplete:" + epoch, (node, from) -> node.onEpochSyncComplete(from, epoch))));
}
- public static CompletionStage<Void> syncEpoch(Node originator, long epoch, Collection<Node.Id> cluster)
+
+ public static Future<Void> syncEpoch(Node originator, long epoch, Collection<Node.Id> cluster)
{
return dieExceptionally(sync(originator, epoch)
- .thenCompose(v -> MessageTask.apply(originator, cluster, "SyncComplete:" + epoch, (node, from) -> node.onEpochSyncComplete(originator.id(), epoch))));
+ .flatMap(v -> MessageTask.apply(originator, cluster, "SyncComplete:" + epoch, (node, from) -> node.onEpochSyncComplete(originator.id(), epoch))));
}
}
diff --git a/accord-core/src/test/java/accord/coordinate/CoordinateTest.java b/accord-core/src/test/java/accord/coordinate/CoordinateTest.java
index a1e3d85..e306dae 100644
--- a/accord-core/src/test/java/accord/coordinate/CoordinateTest.java
+++ b/accord-core/src/test/java/accord/coordinate/CoordinateTest.java
@@ -26,7 +26,7 @@ public class CoordinateTest
TxnId txnId = new TxnId(1, 100, 0, node.id());
Txn txn = writeTxn(keys(10));
- Result result = Coordinate.execute(node, txnId, txn).toCompletableFuture().get();
+ Result result = Coordinate.execute(node, txnId, txn).get();
Assertions.assertEquals(MockStore.RESULT, result);
}
}
@@ -43,7 +43,7 @@ public class CoordinateTest
TxnId txnId = new TxnId(1, 100, 0, node.id());
Txn txn = writeTxn(keys(10));
- Result result = Coordinate.execute(node, txnId, txn).toCompletableFuture().get();
+ Result result = Coordinate.execute(node, txnId, txn).get();
Assertions.assertEquals(MockStore.RESULT, result);
}
}
@@ -52,7 +52,7 @@ public class CoordinateTest
{
TxnId txnId = new TxnId(1, clock, 0, node.id());
Txn txn = writeTxn(keys);
- Result result = Coordinate.execute(node, txnId, txn).toCompletableFuture().get();
+ Result result = Coordinate.execute(node, txnId, txn).get();
Assertions.assertEquals(MockStore.RESULT, result);
return txnId;
}
diff --git a/accord-core/src/test/java/accord/coordinate/RecoverTest.java b/accord-core/src/test/java/accord/coordinate/RecoverTest.java
index 1e260f3..68e7f02 100644
--- a/accord-core/src/test/java/accord/coordinate/RecoverTest.java
+++ b/accord-core/src/test/java/accord/coordinate/RecoverTest.java
@@ -13,8 +13,8 @@ import accord.txn.TxnId;
import org.junit.jupiter.api.Assertions;
import java.util.List;
-import java.util.concurrent.CompletionStage;
import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Future;
import static accord.NetworkFilter.*;
import static accord.Utils.id;
@@ -49,11 +49,11 @@ public class RecoverTest
Assertions.assertFalse(commandStore.hasCommand(txnId));
}
- private static void assertTimeout(CompletionStage<?> f)
+ private static void assertTimeout(Future<?> f)
{
try
{
- f.toCompletableFuture().get();
+ f.get();
Assertions.fail("expected timeout");
}
catch (ExecutionException e)
@@ -96,7 +96,7 @@ public class RecoverTest
//
cluster.networkFilter.clear();
cluster.networkFilter.isolate(ids(1, 4));
- Coordinate.recover(cluster.get(8), txnId2, txn2).toCompletableFuture().get();
+ Coordinate.recover(cluster.get(8), txnId2, txn2).get();
List<Node> nodes = cluster.nodes(ids(5, 9));
Assertions.assertTrue(txnId2.compareTo(txnId1) < 0);
diff --git a/accord-core/src/test/java/accord/coordinate/TopologyChangeTest.java b/accord-core/src/test/java/accord/coordinate/TopologyChangeTest.java
index a5c44f4..5a8e210 100644
--- a/accord-core/src/test/java/accord/coordinate/TopologyChangeTest.java
+++ b/accord-core/src/test/java/accord/coordinate/TopologyChangeTest.java
@@ -30,7 +30,7 @@ public class TopologyChangeTest
{
TxnId txnId = node.nextTxnId();
Txn txn = writeTxn(keys);
- node.coordinate(txnId, txn).toCompletableFuture().get();
+ node.coordinate(txnId, txn).get();
return txnId;
}
@@ -54,7 +54,7 @@ public class TopologyChangeTest
Node node1 = cluster.get(1);
TxnId txnId1 = node1.nextTxnId();
Txn txn1 = writeTxn(keys);
- node1.coordinate(txnId1, txn1).toCompletableFuture().get();
+ node1.coordinate(txnId1, txn1).get();
node1.local(keys).forEach(commands -> {
Command command = commands.command(txnId1);
Assertions.assertTrue(command.savedDeps().isEmpty());
@@ -65,7 +65,7 @@ public class TopologyChangeTest
Node node4 = cluster.get(4);
TxnId txnId2 = node4.nextTxnId();
Txn txn2 = writeTxn(keys);
- node4.coordinate(txnId2, txn2).toCompletableFuture().get();
+ node4.coordinate(txnId2, txn2).get();
// new nodes should have the previous epochs operation as a dependency
cluster.nodes(4, 5, 6).forEach(node -> {
diff --git a/accord-core/src/test/java/accord/impl/IntHashKey.java b/accord-core/src/test/java/accord/impl/IntHashKey.java
index acec998..796656b 100644
--- a/accord-core/src/test/java/accord/impl/IntHashKey.java
+++ b/accord-core/src/test/java/accord/impl/IntHashKey.java
@@ -12,7 +12,7 @@ import accord.txn.Keys;
public class IntHashKey implements Key<IntHashKey>
{
- private static class Range extends KeyRange.EndInclusive<IntHashKey>
+ public static class Range extends KeyRange.EndInclusive<IntHashKey>
{
public Range(IntHashKey start, IntHashKey end)
{
@@ -25,7 +25,6 @@ public class IntHashKey implements Key<IntHashKey>
return new Range(start, end);
}
- @Override
public KeyRanges split(int count)
{
int startHash = start().hash;
@@ -143,4 +142,10 @@ public class IntHashKey implements Key<IntHashKey>
crc32c.update(key >> 24);
return (int)crc32c.getValue();
}
+
+ @Override
+ public int keyHash()
+ {
+ return hash;
+ }
}
diff --git a/accord-core/src/test/java/accord/impl/IntKey.java b/accord-core/src/test/java/accord/impl/IntKey.java
index 6c8d2cd..6292658 100644
--- a/accord-core/src/test/java/accord/impl/IntKey.java
+++ b/accord-core/src/test/java/accord/impl/IntKey.java
@@ -24,33 +24,6 @@ public class IntKey implements Key<IntKey>
{
return new Range(start, end);
}
-
- @Override
- public KeyRanges split(int count)
- {
- return splitRange(this, count, Range::new);
- }
- }
-
- public static KeyRanges splitRange(KeyRange<IntKey> range, int count, BiFunction<IntKey, IntKey, KeyRange<IntKey>> ctor)
- {
- int start = range.start().key;
- int end = range.end().key;
- int currentSize = end - start;
- if (currentSize < count)
- return new KeyRanges(new KeyRange[]{range});
- int interval = currentSize / count;
-
- int nextStart = start;
- KeyRange[] ranges = new KeyRange[count];
- for (int i=0; i<count; i++)
- {
- int subStart = nextStart;
- int subEnd = i < count - 1 ? subStart + interval : end;
- ranges[i] = ctor.apply(key(subStart), key(subEnd));
- nextStart = subEnd;
- }
- return new KeyRanges(ranges);
}
public final int key;
@@ -136,4 +109,10 @@ public class IntKey implements Key<IntKey>
{
return Objects.hash(key);
}
+
+ @Override
+ public int keyHash()
+ {
+ return hashCode();
+ }
}
diff --git a/accord-core/src/test/java/accord/impl/basic/Cluster.java b/accord-core/src/test/java/accord/impl/basic/Cluster.java
index 02f93de..d9f5914 100644
--- a/accord-core/src/test/java/accord/impl/basic/Cluster.java
+++ b/accord-core/src/test/java/accord/impl/basic/Cluster.java
@@ -108,7 +108,7 @@ public class Cluster implements Scheduler
if (callback != null)
on.scheduler().now(() -> callback.onSuccess(deliver.src, reply));
}
- else on.receive((Request) deliver.message, deliver.src, deliver.requestId);
+ else on.receive((Request) deliver.message, deliver.src, deliver);
}
else
{
@@ -153,7 +153,7 @@ public class Cluster implements Scheduler
MessageSink messageSink = sinks.create(node, randomSupplier.get());
BurnTestConfigurationService configService = new BurnTestConfigurationService(node, messageSink, randomSupplier, topology, lookup::get);
lookup.put(node, new Node(node, messageSink, configService,
- nowSupplier.get(), ListStore::new, ListAgent.INSTANCE, sinks, CommandStore.Factory.SYNCHRONIZED));
+ nowSupplier.get(), () -> new ListStore(node), ListAgent.INSTANCE, sinks, CommandStore.Factory.SYNCHRONIZED));
}
List<Id> nodesList = new ArrayList<>(Arrays.asList(nodes));
diff --git a/accord-core/src/test/java/accord/impl/basic/NodeSink.java b/accord-core/src/test/java/accord/impl/basic/NodeSink.java
index f48877e..c1daccd 100644
--- a/accord-core/src/test/java/accord/impl/basic/NodeSink.java
+++ b/accord-core/src/test/java/accord/impl/basic/NodeSink.java
@@ -12,6 +12,7 @@ import accord.local.Node.Id;
import accord.api.MessageSink;
import accord.messages.Callback;
import accord.messages.Reply;
+import accord.messages.ReplyContext;
import accord.messages.Request;
import static accord.impl.basic.Packet.SENTINEL_MESSAGE_ID;
@@ -53,8 +54,8 @@ public class NodeSink implements MessageSink
}
@Override
- public void reply(Id replyToNode, long replyToMessage, Reply reply)
+ public void reply(Id replyToNode, ReplyContext replyContext, Reply reply)
{
- parent.add(self, replyToNode, replyToMessage, reply);
+ parent.add(self, replyToNode, Packet.getMessageId(replyContext), reply);
}
}
diff --git a/accord-core/src/test/java/accord/impl/basic/Packet.java b/accord-core/src/test/java/accord/impl/basic/Packet.java
index 3b56159..3929f85 100644
--- a/accord-core/src/test/java/accord/impl/basic/Packet.java
+++ b/accord-core/src/test/java/accord/impl/basic/Packet.java
@@ -1,11 +1,13 @@
package accord.impl.basic;
+import accord.impl.mock.Network;
import accord.local.Node.Id;
import accord.messages.Message;
import accord.messages.Reply;
+import accord.messages.ReplyContext;
import accord.messages.Request;
-public class Packet implements Pending
+public class Packet implements Pending, ReplyContext
{
static final int SENTINEL_MESSAGE_ID = Integer.MIN_VALUE;
@@ -42,4 +44,11 @@ public class Packet implements Pending
+ (replyId != SENTINEL_MESSAGE_ID ? "replyTo:" + replyId + ", " : "")
+ "body:" + message + "}";
}
+
+ public static long getMessageId(ReplyContext context)
+ {
+ if (context instanceof Network.MessageId)
+ return ((Network.MessageId) context).msgId;
+ return ((Packet) context).requestId;
+ }
}
diff --git a/accord-core/src/test/java/accord/impl/list/ListAgent.java b/accord-core/src/test/java/accord/impl/list/ListAgent.java
index dd90285..abf702f 100644
--- a/accord-core/src/test/java/accord/impl/list/ListAgent.java
+++ b/accord-core/src/test/java/accord/impl/list/ListAgent.java
@@ -1,5 +1,6 @@
package accord.impl.list;
+import accord.impl.mock.Network;
import accord.local.Node;
import accord.api.Agent;
import accord.api.Result;
@@ -16,7 +17,7 @@ public class ListAgent implements Agent
if (success != null)
{
ListResult result = (ListResult) success;
- node.reply(result.client, result.requestId, result);
+ node.reply(result.client, Network.replyCtxFor(result.requestId), result);
}
}
diff --git a/accord-core/src/test/java/accord/impl/list/ListRead.java b/accord-core/src/test/java/accord/impl/list/ListRead.java
index 57c5317..389c32e 100644
--- a/accord-core/src/test/java/accord/impl/list/ListRead.java
+++ b/accord-core/src/test/java/accord/impl/list/ListRead.java
@@ -1,13 +1,15 @@
package accord.impl.list;
import accord.api.*;
-import accord.topology.KeyRanges;
import accord.txn.Keys;
-
-import static java.lang.Math.max;
+import accord.txn.Timestamp;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class ListRead implements Read
{
+ private static final Logger logger = LoggerFactory.getLogger(ListRead.class);
+
public final Keys keys;
public ListRead(Keys keys)
@@ -16,20 +18,13 @@ public class ListRead implements Read
}
@Override
- public Data read(KeyRanges ranges, Store store)
+ public Data read(Key key, Timestamp executeAt, Store store)
{
ListStore s = (ListStore)store;
ListData result = new ListData();
- for (KeyRange range : ranges)
- {
- int lowIdx = range.lowKeyIndex(keys);
- if (lowIdx < -keys.size())
- return result;
- if (lowIdx < 0)
- continue;
- for (int i = lowIdx, limit = range.higherKeyIndex(keys) ; i < limit ; ++i)
- result.put(keys.get(i), s.get(keys.get(i)));
- }
+ int[] data = s.get(key);
+ logger.trace("READ on {} at {} key:{} -> {}", s.node, executeAt, key, data);
+ result.put(key, data);
return result;
}
diff --git a/accord-core/src/test/java/accord/impl/list/ListRequest.java b/accord-core/src/test/java/accord/impl/list/ListRequest.java
index d9cc845..9a4a823 100644
--- a/accord-core/src/test/java/accord/impl/list/ListRequest.java
+++ b/accord-core/src/test/java/accord/impl/list/ListRequest.java
@@ -2,6 +2,8 @@ package accord.impl.list;
import accord.local.Node;
import accord.local.Node.Id;
+import accord.messages.MessageType;
+import accord.messages.ReplyContext;
import accord.txn.Txn;
import accord.messages.Request;
@@ -14,16 +16,21 @@ public class ListRequest implements Request
this.txn = txn;
}
- public void process(Node node, Id client, long messageId)
+ public void process(Node node, Id client, ReplyContext replyContext)
{
// TODO (now): error handling
- node.coordinate(txn).handle((success, fail) -> {
+ node.coordinate(txn).addCallback((success, fail) -> {
if (success != null)
- node.reply(client, messageId, (ListResult) success);
- return null;
+ node.reply(client, replyContext, (ListResult) success);
});
}
+ @Override
+ public MessageType type()
+ {
+ throw new UnsupportedOperationException();
+ }
+
@Override
public String toString()
{
diff --git a/accord-core/src/test/java/accord/impl/list/ListResult.java b/accord-core/src/test/java/accord/impl/list/ListResult.java
index d950a15..6025ffe 100644
--- a/accord-core/src/test/java/accord/impl/list/ListResult.java
+++ b/accord-core/src/test/java/accord/impl/list/ListResult.java
@@ -6,6 +6,7 @@ import java.util.stream.IntStream;
import accord.local.Node.Id;
import accord.api.Result;
+import accord.messages.MessageType;
import accord.txn.Keys;
import accord.messages.Reply;
@@ -26,6 +27,12 @@ public class ListResult implements Result, Reply
this.update = update;
}
+ @Override
+ public MessageType type()
+ {
+ throw new UnsupportedOperationException();
+ }
+
@Override
public String toString()
{
diff --git a/accord-core/src/test/java/accord/impl/list/ListStore.java b/accord-core/src/test/java/accord/impl/list/ListStore.java
index ee6b05e..b619113 100644
--- a/accord-core/src/test/java/accord/impl/list/ListStore.java
+++ b/accord-core/src/test/java/accord/impl/list/ListStore.java
@@ -5,6 +5,7 @@ import java.util.concurrent.ConcurrentHashMap;
import accord.api.Key;
import accord.api.Store;
+import accord.local.Node;
import accord.utils.Timestamped;
public class ListStore implements Store
@@ -12,6 +13,14 @@ public class ListStore implements Store
static final int[] EMPTY = new int[0];
final Map<Key, Timestamped<int[]>> data = new ConcurrentHashMap<>();
+ // adding here to help trace burn test queries
+ public final Node.Id node;
+
+ public ListStore(Node.Id node)
+ {
+ this.node = node;
+ }
+
public int[] get(Key key)
{
Timestamped<int[]> v = data.get(key);
diff --git a/accord-core/src/test/java/accord/impl/list/ListWrite.java b/accord-core/src/test/java/accord/impl/list/ListWrite.java
index 0f9aeaf..29cc6ab 100644
--- a/accord-core/src/test/java/accord/impl/list/ListWrite.java
+++ b/accord-core/src/test/java/accord/impl/list/ListWrite.java
@@ -1,29 +1,26 @@
package accord.impl.list;
-import java.util.Map;
-import java.util.NavigableMap;
import java.util.TreeMap;
import accord.api.Key;
-import accord.api.KeyRange;
import accord.api.Store;
import accord.api.Write;
-import accord.topology.KeyRanges;
import accord.txn.Timestamp;
import accord.utils.Timestamped;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class ListWrite extends TreeMap<Key, int[]> implements Write
{
+ private static final Logger logger = LoggerFactory.getLogger(ListWrite.class);
@Override
- public void apply(KeyRanges ranges, Timestamp executeAt, Store store)
+ public void apply(Key key, Timestamp executeAt, Store store)
{
ListStore s = (ListStore) store;
- for (KeyRange range : ranges)
- {
- NavigableMap<Key, int[]> selection = subMap(range.start(), range.startInclusive(),
- range.end(), range.endInclusive());
- for (Map.Entry<Key, int[]> e : selection.entrySet())
- s.data.merge(e.getKey(), new Timestamped<>(executeAt, e.getValue()), Timestamped::merge);
- }
+ if (!containsKey(key))
+ return;
+ int[] data = get(key);
+ s.data.merge(key, new Timestamped<>(executeAt, data), Timestamped::merge);
+ logger.trace("WRITE on {} at {} key:{} -> {}", s.node, executeAt, key, data);
}
}
diff --git a/accord-core/src/test/java/accord/impl/mock/EpochSync.java b/accord-core/src/test/java/accord/impl/mock/EpochSync.java
index 4070da9..71914dd 100644
--- a/accord-core/src/test/java/accord/impl/mock/EpochSync.java
+++ b/accord-core/src/test/java/accord/impl/mock/EpochSync.java
@@ -2,18 +2,16 @@ package accord.impl.mock;
import accord.coordinate.tracking.QuorumTracker;
import accord.local.*;
-import accord.messages.Callback;
-import accord.messages.Reply;
-import accord.messages.Request;
+import accord.messages.*;
import accord.topology.Topologies;
import accord.topology.Topology;
import accord.txn.*;
import com.google.common.base.Preconditions;
+import org.apache.cassandra.utils.concurrent.AsyncPromise;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
-import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.function.Consumer;
@@ -52,13 +50,19 @@ public class EpochSync implements Runnable
}
@Override
- public void process(Node node, Node.Id from, long messageId)
+ public void process(Node node, Node.Id from, ReplyContext replyContext)
{
node.local().forEach(commandStore -> {
Command command = commandStore.command(txnId);
command.commit(txn, deps, executeAt);
});
- node.reply(from, messageId, SyncAck.INSTANCE);
+ node.reply(from, replyContext, SyncAck.INSTANCE);
+ }
+
+ @Override
+ public MessageType type()
+ {
+ throw new UnsupportedOperationException();
}
}
@@ -66,9 +70,15 @@ public class EpochSync implements Runnable
{
private static final SyncAck INSTANCE = new SyncAck();
private SyncAck() {}
+
+ @Override
+ public MessageType type()
+ {
+ throw new UnsupportedOperationException();
+ }
}
- private static class CommandSync extends CompletableFuture<Void> implements Callback<SyncAck>
+ private static class CommandSync extends AsyncPromise<Void> implements Callback<SyncAck>
{
private final QuorumTracker tracker;
@@ -84,7 +94,7 @@ public class EpochSync implements Runnable
{
tracker.recordSuccess(from);
if (tracker.hasReachedQuorum())
- complete(null);
+ setSuccess(null);
}
@Override
@@ -92,14 +102,14 @@ public class EpochSync implements Runnable
{
tracker.recordFailure(from);
if (tracker.hasFailed())
- completeExceptionally(throwable);
+ tryFailure(throwable);
}
public static void sync(Node node, SyncMessage message, Topology topology)
{
try
{
- new CommandSync(node, message, topology).toCompletableFuture().get();
+ new CommandSync(node, message, topology).get();
}
catch (InterruptedException | ExecutionException e)
{
@@ -118,10 +128,16 @@ public class EpochSync implements Runnable
}
@Override
- public void process(Node on, Node.Id from, long messageId)
+ public void process(Node on, Node.Id from, ReplyContext replyContext)
{
configService(on).reportSyncComplete(from, epoch);
}
+
+ @Override
+ public MessageType type()
+ {
+ throw new UnsupportedOperationException();
+ }
}
private class NodeSync implements Runnable
diff --git a/accord-core/src/test/java/accord/impl/mock/MockCluster.java b/accord-core/src/test/java/accord/impl/mock/MockCluster.java
index 139da72..8e00794 100644
--- a/accord-core/src/test/java/accord/impl/mock/MockCluster.java
+++ b/accord-core/src/test/java/accord/impl/mock/MockCluster.java
@@ -140,7 +140,7 @@ public class MockCluster implements Network, AutoCloseable, Iterable<Node>
}
logger.info("processing message[{}] from {} to {}: {}", messageId, from, to, request);
- node.receive(request, from, messageId);
+ node.receive(request, from, Network.replyCtxFor(messageId));
}
@Override
diff --git a/accord-core/src/test/java/accord/impl/mock/MockConfigurationService.java b/accord-core/src/test/java/accord/impl/mock/MockConfigurationService.java
index 4a322ab..74add97 100644
--- a/accord-core/src/test/java/accord/impl/mock/MockConfigurationService.java
+++ b/accord-core/src/test/java/accord/impl/mock/MockConfigurationService.java
@@ -5,17 +5,20 @@ import accord.api.TestableConfigurationService;
import accord.local.Node;
import accord.topology.Topology;
import accord.utils.EpochFunction;
-import com.google.common.collect.ImmutableSet;
+import org.apache.cassandra.utils.concurrent.AsyncPromise;
+import org.apache.cassandra.utils.concurrent.Future;
+import org.apache.cassandra.utils.concurrent.ImmediateFuture;
import org.junit.jupiter.api.Assertions;
import java.util.*;
public class MockConfigurationService implements TestableConfigurationService
{
+ private static final Future<Void> SUCCESS = ImmediateFuture.success(null);
private final MessageSink messageSink;
private final List<Topology> epochs = new ArrayList<>();
private final List<Listener> listeners = new ArrayList<>();
- private final Map<Long, Set<Runnable>> waiting = new HashMap<>();
+ private final Map<Long, AsyncPromise<Void>> pending = new HashMap<>();
private final EpochFunction<MockConfigurationService> fetchTopologyHandler;
public MockConfigurationService(MessageSink messageSink, EpochFunction<MockConfigurationService> fetchTopologyHandler)
@@ -50,19 +53,16 @@ public class MockConfigurationService implements TestableConfigurationService
}
@Override
- public synchronized void fetchTopologyForEpoch(long epoch, Runnable onComplete)
+ public synchronized Future<Void> fetchTopologyForEpoch(long epoch)
{
if (epoch < epochs.size())
{
- if (onComplete != null) onComplete.run();
- return;
+ return SUCCESS;
}
- Set<Runnable> runnables = waiting.computeIfAbsent(epoch, e -> new HashSet<>());
- if (onComplete != null)
- runnables.add(onComplete);
-
+ Future<Void> future = pending.computeIfAbsent(epoch, e -> new AsyncPromise<>());
fetchTopologyHandler.apply(epoch, this);
+ return future;
}
@Override
@@ -79,16 +79,10 @@ public class MockConfigurationService implements TestableConfigurationService
for (Listener listener : listeners)
listener.onTopologyUpdate(topology);
- Set<Runnable> runnables = waiting.remove(topology.epoch());
- if (runnables == null)
+ AsyncPromise<Void> promise = pending.remove(topology.epoch());
+ if (promise == null)
return;
-
- runnables.forEach(Runnable::run);
- }
-
- public synchronized Set<Long> pendingEpochs()
- {
- return ImmutableSet.copyOf(waiting.keySet());
+ promise.setSuccess(null);
}
public synchronized void reportSyncComplete(Node.Id node, long epoch)
diff --git a/accord-core/src/test/java/accord/impl/mock/MockStore.java b/accord-core/src/test/java/accord/impl/mock/MockStore.java
index 36b2271..7899a78 100644
--- a/accord-core/src/test/java/accord/impl/mock/MockStore.java
+++ b/accord-core/src/test/java/accord/impl/mock/MockStore.java
@@ -19,8 +19,8 @@ public class MockStore implements Store
};
public static final Result RESULT = new Result() {};
- public static final Read READ = (range, store) -> DATA;
+ public static final Read READ = (key, executeAt, store) -> DATA;
public static final Query QUERY = data -> RESULT;
- public static final Write WRITE = (range, executeAt, store) -> {};
+ public static final Write WRITE = (key, executeAt, store) -> {};
public static final Update UPDATE = data -> WRITE;
}
diff --git a/accord-core/src/test/java/accord/impl/mock/Network.java b/accord-core/src/test/java/accord/impl/mock/Network.java
index 5eda959..bb9fb64 100644
--- a/accord-core/src/test/java/accord/impl/mock/Network.java
+++ b/accord-core/src/test/java/accord/impl/mock/Network.java
@@ -3,10 +3,31 @@ package accord.impl.mock;
import accord.local.Node.Id;
import accord.messages.Callback;
import accord.messages.Reply;
+import accord.messages.ReplyContext;
import accord.messages.Request;
public interface Network
{
+ class MessageId implements ReplyContext
+ {
+ public final long msgId;
+
+ public MessageId(long msgId)
+ {
+ this.msgId = msgId;
+ }
+ }
+
+ static long getMessageId(ReplyContext ctx)
+ {
+ return ((MessageId) ctx).msgId;
+ }
+
+ static ReplyContext replyCtxFor(long messageId)
+ {
+ return new MessageId(messageId);
+ }
+
void send(Id from, Id to, Request request, Callback callback);
void reply(Id from, Id replyingToNode, long replyingToMessage, Reply reply);
diff --git a/accord-core/src/test/java/accord/impl/mock/RecordingMessageSink.java b/accord-core/src/test/java/accord/impl/mock/RecordingMessageSink.java
index 55cfa40..512c2b2 100644
--- a/accord-core/src/test/java/accord/impl/mock/RecordingMessageSink.java
+++ b/accord-core/src/test/java/accord/impl/mock/RecordingMessageSink.java
@@ -3,6 +3,7 @@ package accord.impl.mock;
import accord.local.Node;
import accord.messages.Callback;
import accord.messages.Reply;
+import accord.messages.ReplyContext;
import accord.messages.Request;
import org.junit.jupiter.api.Assertions;
@@ -49,10 +50,10 @@ public class RecordingMessageSink extends SimpleMessageSink
}
@Override
- public void reply(Node.Id replyingToNode, long replyingToMessage, Reply reply)
+ public void reply(Node.Id replyingToNode, ReplyContext replyContext, Reply reply)
{
responses.add(new Envelope<>(replyingToNode, reply, null));
- super.reply(replyingToNode, replyingToMessage, reply);
+ super.reply(replyingToNode, replyContext, reply);
}
public void assertHistorySizes(int requests, int responses)
diff --git a/accord-core/src/test/java/accord/impl/mock/SimpleMessageSink.java b/accord-core/src/test/java/accord/impl/mock/SimpleMessageSink.java
index 8ddbeca..8c16f8b 100644
--- a/accord-core/src/test/java/accord/impl/mock/SimpleMessageSink.java
+++ b/accord-core/src/test/java/accord/impl/mock/SimpleMessageSink.java
@@ -4,6 +4,7 @@ import accord.local.Node;
import accord.api.MessageSink;
import accord.messages.Callback;
import accord.messages.Reply;
+import accord.messages.ReplyContext;
import accord.messages.Request;
public class SimpleMessageSink implements MessageSink
@@ -30,8 +31,8 @@ public class SimpleMessageSink implements MessageSink
}
@Override
- public void reply(Node.Id replyingToNode, long replyingToMessage, Reply reply)
+ public void reply(Node.Id replyingToNode, ReplyContext replyContext, Reply reply)
{
- network.reply(node, replyingToNode, replyingToMessage, reply);
+ network.reply(node, replyingToNode, Network.getMessageId(replyContext), reply);
}
}
diff --git a/accord-core/src/test/java/accord/local/CommandTest.java b/accord-core/src/test/java/accord/local/CommandTest.java
index 5912791..7699d3d 100644
--- a/accord-core/src/test/java/accord/local/CommandTest.java
+++ b/accord-core/src/test/java/accord/local/CommandTest.java
@@ -32,7 +32,7 @@ public class CommandTest
private static class CommandStoreSupport
{
- final AtomicReference<CommandStore.Mapping> mapping = new AtomicReference<>(CommandStore.Mapping.EMPTY);
+ final AtomicReference<Topology> local = new AtomicReference<>(TOPOLOGY);
final MockStore data = new MockStore();
final AtomicReference<Timestamp> nextTimestamp = new AtomicReference<>(Timestamp.NONE);
final Function<Timestamp, Timestamp> uniqueNow = atleast -> {
@@ -42,22 +42,22 @@ public class CommandTest
};
}
- private static void setMappingEpoch(AtomicReference<CommandStore.Mapping> mapping, long epoch)
+ private static void setTopologyEpoch(AtomicReference<Topology> topology, long epoch)
{
- CommandStore.Mapping current = mapping.get();
- CommandStore.Mapping next = new CommandStore.Mapping(current.ranges, current.local.withEpoch(epoch));
- mapping.set(next);
+ topology.set(topology.get().withEpoch(epoch));
}
private static CommandStore createStore(CommandStoreSupport storeSupport)
{
return new CommandStore.Synchronized(0,
+ 0,
+ 1,
ID1,
storeSupport.uniqueNow,
new TestAgent(),
storeSupport.data,
- storeSupport.mapping.get(),
- i -> storeSupport.mapping.get());
+ storeSupport.local.get().ranges(),
+ storeSupport.local::get);
}
@Test
@@ -92,7 +92,7 @@ public class CommandTest
Assertions.assertEquals(Status.NotWitnessed, command.status());
Assertions.assertNull(command.executeAt());
- setMappingEpoch(support.mapping, 2);
+ setTopologyEpoch(support.local, 2);
Timestamp expectedTimestamp = new Timestamp(2, 110, 0, ID1);
support.nextTimestamp.set(expectedTimestamp);
commands.process((Consumer<? super CommandStore>) cstore -> command.witness(txn));
diff --git a/accord-core/src/test/java/accord/messages/PreAcceptTest.java b/accord-core/src/test/java/accord/messages/PreAcceptTest.java
index 1de92cd..87cc0c5 100644
--- a/accord-core/src/test/java/accord/messages/PreAcceptTest.java
+++ b/accord-core/src/test/java/accord/messages/PreAcceptTest.java
@@ -35,6 +35,8 @@ public class PreAcceptTest
private static final List<Id> IDS = List.of(ID1, ID2, ID3);
private static final Topology TOPOLOGY = TopologyFactory.toTopology(IDS, 3, IntKey.range(0, 100));
+ private static final ReplyContext REPLY_CONTEXT = Network.replyCtxFor(0);
+
private static Node createNode(Id nodeId, MessageSink messageSink, Clock clock)
{
MockStore store = new MockStore();
@@ -77,7 +79,7 @@ public class PreAcceptTest
Txn txn = writeTxn(Keys.of(key));
PreAccept preAccept = preAccept(txnId, txn);
clock.increment(10);
- preAccept.process(node, ID2, 0);
+ preAccept.process(node, ID2, REPLY_CONTEXT);
Command command = commandStore.commandsForKey(key).uncommitted.get(txnId);
Assertions.assertEquals(Status.PreAccepted, command.status());
@@ -108,7 +110,7 @@ public class PreAcceptTest
TxnId txnId = clock.idForNode(1, ID2);
Txn txn = writeTxn(Keys.of(key));
PreAccept preAccept = preAccept(txnId, txn);
- preAccept.process(node, ID2, 0);
+ preAccept.process(node, ID2, REPLY_CONTEXT);
}
finally
{
@@ -132,14 +134,14 @@ public class PreAcceptTest
IntKey key1 = IntKey.key(10);
PreAccept preAccept1 = preAccept(clock.idForNode(1, ID2), writeTxn(Keys.of(key1)));
- preAccept1.process(node, ID2, 0);
+ preAccept1.process(node, ID2, REPLY_CONTEXT);
messageSink.clearHistory();
IntKey key2 = IntKey.key(11);
TxnId txnId2 = new TxnId(1, 50, 0, ID3);
PreAccept preAccept2 = preAccept(txnId2, writeTxn(Keys.of(key1, key2)));
clock.increment(10);
- preAccept2.process(node, ID3, 0);
+ preAccept2.process(node, ID3, REPLY_CONTEXT);
messageSink.assertHistorySizes(0, 1);
Assertions.assertEquals(ID3, messageSink.responses.get(0).to);
@@ -169,7 +171,7 @@ public class PreAcceptTest
{
TxnId txnId = new TxnId(1, 110, 0, ID2);
PreAccept preAccept = preAccept(txnId, writeTxn(Keys.of(key)));
- preAccept.process(node, ID2, 0);
+ preAccept.process(node, ID2, REPLY_CONTEXT);
messageSink.assertHistorySizes(0, 1);
Assertions.assertEquals(ID2, messageSink.responses.get(0).to);
@@ -203,7 +205,7 @@ public class PreAcceptTest
PreAccept preAccept = preAccept(txnId, txn);
clock.increment(10);
- preAccept.process(node, ID2, 0);
+ preAccept.process(node, ID2, REPLY_CONTEXT);
Command command = commandStore.commandsForKey(key).uncommitted.get(txnId);
Assertions.assertEquals(Status.PreAccepted, command.status());
diff --git a/accord-core/src/test/java/accord/topology/TopologyRandomizer.java b/accord-core/src/test/java/accord/topology/TopologyRandomizer.java
index e241d86..c794c24 100644
--- a/accord-core/src/test/java/accord/topology/TopologyRandomizer.java
+++ b/accord-core/src/test/java/accord/topology/TopologyRandomizer.java
@@ -56,9 +56,9 @@ public class TopologyRandomizer
{
int idx = random.nextInt(shards.length - 1);
Shard left = shards[idx];
- KeyRange<IntHashKey> leftRange = left.range;
+ IntHashKey.Range leftRange = (IntHashKey.Range) left.range;
Shard right = shards[idx + 1];
- KeyRange<IntHashKey> rightRange = right.range;
+ IntHashKey.Range rightRange = (IntHashKey.Range) right.range;
IntHashKey minBound = (IntHashKey) leftRange.split(2).get(0).end();
IntHashKey maxBound = (IntHashKey) rightRange.split(2).get(0).start();
diff --git a/accord-core/src/test/java/accord/utils/KeyRangeTest.java b/accord-core/src/test/java/accord/utils/KeyRangeTest.java
index b14efa4..ff0fdc4 100644
--- a/accord-core/src/test/java/accord/utils/KeyRangeTest.java
+++ b/accord-core/src/test/java/accord/utils/KeyRangeTest.java
@@ -32,12 +32,6 @@ public class KeyRangeTest
{
return new EndInclusiveIntRange(start, end);
}
-
- @Override
- public KeyRanges split(int count)
- {
- return IntKey.splitRange(this, count, EndInclusiveIntRange::new);
- }
}
private static class StartInclusiveIntRange extends KeyRange.StartInclusive<IntKey>
@@ -52,12 +46,6 @@ public class KeyRangeTest
{
return new StartInclusiveIntRange(start, end);
}
-
- @Override
- public KeyRanges split(int count)
- {
- return IntKey.splitRange(this, count, StartInclusiveIntRange::new);
- }
}
static KeyRange<IntKey> rangeEndIncl(int start, int end)
diff --git a/accord-core/src/test/java/accord/utils/MessageTask.java b/accord-core/src/test/java/accord/utils/MessageTask.java
index 9a568fe..4db5452 100644
--- a/accord-core/src/test/java/accord/utils/MessageTask.java
+++ b/accord-core/src/test/java/accord/utils/MessageTask.java
@@ -1,24 +1,20 @@
package accord.utils;
import accord.local.Node;
-import accord.messages.Callback;
-import accord.messages.Reply;
-import accord.messages.Request;
+import accord.messages.*;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
+import org.apache.cassandra.utils.concurrent.AsyncPromise;
import java.util.*;
-import java.util.concurrent.CompletableFuture;
-import java.util.concurrent.TimeUnit;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
-import java.util.stream.Collectors;
/**
* Message task that will continue sending messages to a set of nodes until all
* nodes ack the message.
*/
-public class MessageTask extends CompletableFuture<Void> implements Runnable
+public class MessageTask extends AsyncPromise<Void> implements Runnable
{
public interface NodeProcess
{
@@ -26,6 +22,12 @@ public class MessageTask extends CompletableFuture<Void> implements Runnable
}
private static final Reply SUCCESS = new Reply() {
+ @Override
+ public MessageType type()
+ {
+ throw new UnsupportedOperationException();
+ }
+
@Override
public String toString()
{
@@ -34,6 +36,12 @@ public class MessageTask extends CompletableFuture<Void> implements Runnable
};
private static final Reply FAILURE = new Reply() {
+ @Override
+ public MessageType type()
+ {
+ throw new UnsupportedOperationException();
+ }
+
@Override
public String toString()
{
@@ -59,9 +67,15 @@ public class MessageTask extends CompletableFuture<Void> implements Runnable
}
@Override
- public void process(Node on, Node.Id from, long messageId)
+ public void process(Node on, Node.Id from, ReplyContext replyContext)
+ {
+ on.reply(from, replyContext, process.process(on, from) ? SUCCESS : FAILURE);
+ }
+
+ @Override
+ public MessageType type()
{
- on.reply(from, messageId, process.process(on, from) ? SUCCESS : FAILURE);
+ throw new UnsupportedOperationException();
}
@Override
@@ -94,7 +108,7 @@ public class MessageTask extends CompletableFuture<Void> implements Runnable
{
this.outstanding.remove(from);
if (outstanding.isEmpty())
- complete(null);
+ setSuccess(null);
}
}
diff --git a/accord-maelstrom/build.gradle b/accord-maelstrom/build.gradle
index b468830..33d5e72 100644
--- a/accord-maelstrom/build.gradle
+++ b/accord-maelstrom/build.gradle
@@ -18,6 +18,7 @@ dependencies {
implementation 'com.google.code.gson:gson:2.8.7'
implementation 'com.google.guava:guava:30.1.1-jre'
implementation 'ch.qos.logback:logback-classic:1.2.3'
+ implementation 'io.netty:netty-all:4.1.58.Final'
testCompile project(path: ':accord-core', configuration: 'testClasses')
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.7.0'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.7.0'
diff --git a/accord-maelstrom/src/main/java/accord/maelstrom/Cluster.java b/accord-maelstrom/src/main/java/accord/maelstrom/Cluster.java
index e054fe1..af4d294 100644
--- a/accord-maelstrom/src/main/java/accord/maelstrom/Cluster.java
+++ b/accord-maelstrom/src/main/java/accord/maelstrom/Cluster.java
@@ -20,6 +20,7 @@ import accord.local.Node.Id;
import accord.api.MessageSink;
import accord.messages.Callback;
import accord.messages.Reply;
+import accord.messages.ReplyContext;
import accord.messages.Request;
import accord.api.Scheduler;
import accord.topology.Topology;
@@ -77,8 +78,9 @@ public class Cluster implements Scheduler
}
@Override
- public void reply(Id replyToNode, long replyToMessage, Reply reply)
+ public void reply(Id replyToNode, ReplyContext replyContext, Reply reply)
{
+ long replyToMessage = ((Packet) replyContext).body.msg_id;
parent.add(self, replyToNode, replyToMessage, reply);
}
}
@@ -146,7 +148,7 @@ public class Cluster implements Scheduler
case txn:
err.println(clock++ + " RECV " + deliver);
err.flush();
- on.receive((MaelstromRequest)deliver.body, deliver.src, deliver.body.msg_id);
+ on.receive((MaelstromRequest)deliver.body, deliver.src, deliver);
break;
default:
// Drop the message if it goes across the partition
@@ -168,7 +170,7 @@ public class Cluster implements Scheduler
if (callback != null)
on.scheduler().now(() -> callback.onSuccess(deliver.src, reply));
}
- else on.receive((Request)((Wrapper)deliver.body).body, deliver.src, deliver.body.msg_id);
+ else on.receive((Request)((Wrapper)deliver.body).body, deliver.src, deliver);
}
}
else
diff --git a/accord-maelstrom/src/main/java/accord/maelstrom/Error.java b/accord-maelstrom/src/main/java/accord/maelstrom/Error.java
index 71a368b..e4dc308 100644
--- a/accord-maelstrom/src/main/java/accord/maelstrom/Error.java
+++ b/accord-maelstrom/src/main/java/accord/maelstrom/Error.java
@@ -3,6 +3,7 @@ package accord.maelstrom;
import java.io.IOException;
import accord.maelstrom.Packet.Type;
+import accord.messages.MessageType;
import com.google.gson.stream.JsonWriter;
import accord.messages.Reply;
@@ -27,4 +28,10 @@ public class Error extends Body implements Reply
out.name("text");
out.value(text);
}
+
+ @Override
+ public MessageType type()
+ {
+ throw new UnsupportedOperationException();
+ }
}
diff --git a/accord-maelstrom/src/main/java/accord/maelstrom/MaelstromAgent.java b/accord-maelstrom/src/main/java/accord/maelstrom/MaelstromAgent.java
index e25e617..dfe4851 100644
--- a/accord-maelstrom/src/main/java/accord/maelstrom/MaelstromAgent.java
+++ b/accord-maelstrom/src/main/java/accord/maelstrom/MaelstromAgent.java
@@ -16,7 +16,7 @@ public class MaelstromAgent implements Agent
if (success != null)
{
MaelstromResult result = (MaelstromResult) success;
- node.reply(result.client, result.requestId, new MaelstromReply(result.requestId, result));
+ node.reply(result.client, MaelstromReplyContext.contextFor(result.requestId), new MaelstromReply(result.requestId, result));
}
}
diff --git a/accord-maelstrom/src/main/java/accord/maelstrom/MaelstromKey.java b/accord-maelstrom/src/main/java/accord/maelstrom/MaelstromKey.java
index c557016..1f54292 100644
--- a/accord-maelstrom/src/main/java/accord/maelstrom/MaelstromKey.java
+++ b/accord-maelstrom/src/main/java/accord/maelstrom/MaelstromKey.java
@@ -5,6 +5,7 @@ import java.io.IOException;
import accord.api.Key;
import accord.api.KeyRange;
import accord.topology.KeyRanges;
+import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.common.primitives.Ints;
import com.google.gson.TypeAdapter;
@@ -25,30 +26,6 @@ public class MaelstromKey extends Datum<MaelstromKey> implements Key<MaelstromKe
{
return new Range(start, end);
}
-
- @Override
- public KeyRanges split(int count)
- {
- Preconditions.checkArgument(start().kind == Kind.HASH);
- Preconditions.checkArgument(end().kind == Kind.HASH);
- long startHash = ((Hash) start().value).hash;
- long endHash = end().value != null ? ((Hash) end().value).hash : Integer.MAX_VALUE;
- long currentSize = endHash - startHash;
- if (currentSize < count)
- return new KeyRanges(new KeyRange[]{this});
- long interval = currentSize / count;
-
- long subEnd = 0;
- KeyRange[] ranges = new KeyRange[count];
- for (int i=0; i<count; i++)
- {
- long subStart = i > 0 ? subEnd : startHash;
- subEnd = i < count - 1 ? subStart + interval : endHash;
- ranges[i] = new Range(new MaelstromKey(Kind.HASH, new Hash(Ints.checkedCast(subStart))),
- i < count - 1 ? new MaelstromKey(Kind.HASH, new Hash(Ints.checkedCast(subEnd))) : end());
- }
- return new KeyRanges(ranges);
- }
}
public MaelstromKey(Kind kind, Object value)
@@ -96,4 +73,10 @@ public class MaelstromKey extends Datum<MaelstromKey> implements Key<MaelstromKe
return MaelstromKey.read(in);
}
};
- }
+
+ @Override
+ public int keyHash()
+ {
+ return Objects.hashCode(kind, value);
+ }
+}
diff --git a/accord-maelstrom/src/main/java/accord/maelstrom/MaelstromRead.java b/accord-maelstrom/src/main/java/accord/maelstrom/MaelstromRead.java
index 142532e..6f96e70 100644
--- a/accord-maelstrom/src/main/java/accord/maelstrom/MaelstromRead.java
+++ b/accord-maelstrom/src/main/java/accord/maelstrom/MaelstromRead.java
@@ -1,10 +1,8 @@
package accord.maelstrom;
import accord.api.*;
-import accord.topology.KeyRanges;
import accord.txn.Keys;
-
-import static java.lang.Math.max;
+import accord.txn.Timestamp;
public class MaelstromRead implements Read
{
@@ -16,20 +14,11 @@ public class MaelstromRead implements Read
}
@Override
- public Data read(KeyRanges ranges, Store store)
+ public Data read(Key key, Timestamp executeAt, Store store)
{
MaelstromStore s = (MaelstromStore)store;
MaelstromData result = new MaelstromData();
- for (KeyRange range : ranges)
- {
- int lowIdx = range.lowKeyIndex(keys);
- if (lowIdx < -keys.size())
- return result;
- if (lowIdx < 0)
- continue;
- for (int i = lowIdx, limit = range.higherKeyIndex(keys) ; i < limit ; ++i)
- result.put(keys.get(i), s.get(keys.get(i)));
- }
+ result.put(key, s.get(key));
return result;
}
}
diff --git a/accord-maelstrom/src/main/java/accord/maelstrom/MaelstromReply.java b/accord-maelstrom/src/main/java/accord/maelstrom/MaelstromReply.java
index 593e6ff..2b8c87f 100644
--- a/accord-maelstrom/src/main/java/accord/maelstrom/MaelstromReply.java
+++ b/accord-maelstrom/src/main/java/accord/maelstrom/MaelstromReply.java
@@ -6,6 +6,7 @@ import java.util.TreeMap;
import accord.local.Node;
import accord.api.Key;
+import accord.messages.MessageType;
import accord.txn.Keys;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
@@ -23,6 +24,12 @@ public class MaelstromReply extends Body implements Reply
this.result = result;
}
+ @Override
+ public MessageType type()
+ {
+ throw new UnsupportedOperationException();
+ }
+
@Override
void writeBody(JsonWriter out) throws IOException
{
diff --git a/accord-maelstrom/src/main/java/accord/maelstrom/MaelstromReplyContext.java b/accord-maelstrom/src/main/java/accord/maelstrom/MaelstromReplyContext.java
new file mode 100644
index 0000000..5585138
--- /dev/null
+++ b/accord-maelstrom/src/main/java/accord/maelstrom/MaelstromReplyContext.java
@@ -0,0 +1,23 @@
+package accord.maelstrom;
+
+import accord.messages.ReplyContext;
+
+public class MaelstromReplyContext implements ReplyContext
+{
+ public final long messageId;
+
+ public MaelstromReplyContext(long messageId)
+ {
+ this.messageId = messageId;
+ }
+
+ public static ReplyContext contextFor(long messageId)
+ {
+ return new MaelstromReplyContext(messageId);
+ }
+
+ public static long messageIdFor(ReplyContext replyContext)
+ {
+ return ((MaelstromReplyContext) replyContext).messageId;
+ }
+}
diff --git a/accord-maelstrom/src/main/java/accord/maelstrom/MaelstromRequest.java b/accord-maelstrom/src/main/java/accord/maelstrom/MaelstromRequest.java
index 1d1275e..6d84c7c 100644
--- a/accord-maelstrom/src/main/java/accord/maelstrom/MaelstromRequest.java
+++ b/accord-maelstrom/src/main/java/accord/maelstrom/MaelstromRequest.java
@@ -5,6 +5,8 @@ import java.util.NavigableSet;
import java.util.TreeSet;
import accord.api.Key;
+import accord.messages.MessageType;
+import accord.messages.ReplyContext;
import accord.txn.Keys;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
@@ -25,16 +27,21 @@ public class MaelstromRequest extends Body implements Request
this.txn = txn;
}
- public void process(Node node, Id client, long messageId)
+ public void process(Node node, Id client, ReplyContext replyContext)
{
// TODO (now): error handling
- node.coordinate(txn).handle((success, fail) -> {
- if (success != null) node.reply(client, messageId, new MaelstromReply(messageId, (MaelstromResult) success));
+ node.coordinate(txn).addCallback((success, fail) -> {
+ if (success != null) node.reply(client, replyContext, new MaelstromReply(MaelstromReplyContext.messageIdFor(replyContext), (MaelstromResult) success));
// else node.reply(client, messageId, new Error(messageId, 13, fail.getMessage()));
- return null;
});
}
+ @Override
+ public MessageType type()
+ {
+ throw new UnsupportedOperationException();
+ }
+
@Override
void writeBody(JsonWriter out) throws IOException
{
diff --git a/accord-maelstrom/src/main/java/accord/maelstrom/MaelstromWrite.java b/accord-maelstrom/src/main/java/accord/maelstrom/MaelstromWrite.java
index b2216aa..8316712 100644
--- a/accord-maelstrom/src/main/java/accord/maelstrom/MaelstromWrite.java
+++ b/accord-maelstrom/src/main/java/accord/maelstrom/MaelstromWrite.java
@@ -1,29 +1,20 @@
package accord.maelstrom;
-import java.util.Map;
-import java.util.NavigableMap;
-import java.util.TreeMap;
-
import accord.api.Key;
-import accord.api.KeyRange;
import accord.api.Store;
import accord.api.Write;
-import accord.topology.KeyRanges;
import accord.txn.Timestamp;
import accord.utils.Timestamped;
+import java.util.TreeMap;
+
public class MaelstromWrite extends TreeMap<Key, Value> implements Write
{
@Override
- public void apply(KeyRanges ranges, Timestamp executeAt, Store store)
+ public void apply(Key key, Timestamp executeAt, Store store)
{
MaelstromStore s = (MaelstromStore) store;
- for (KeyRange range : ranges)
- {
- NavigableMap<Key, Value> selection = subMap(range.start(), range.startInclusive(),
- range.end(), range.endInclusive());
- for (Map.Entry<Key, Value> e : selection.entrySet())
- s.data.merge(e.getKey(), new Timestamped<>(executeAt, e.getValue()), Timestamped::merge);
- }
+ if (containsKey(key))
+ s.data.merge(key, new Timestamped<>(executeAt, get(key)), Timestamped::merge);
}
}
diff --git a/accord-maelstrom/src/main/java/accord/maelstrom/Main.java b/accord-maelstrom/src/main/java/accord/maelstrom/Main.java
index 67671ee..30c5930 100644
--- a/accord-maelstrom/src/main/java/accord/maelstrom/Main.java
+++ b/accord-maelstrom/src/main/java/accord/maelstrom/Main.java
@@ -18,6 +18,7 @@ import accord.local.CommandStore;
import accord.local.Node;
import accord.local.Node.Id;
import accord.api.Scheduler;
+import accord.messages.ReplyContext;
import accord.topology.Topology;
import accord.utils.ThreadPoolScheduler;
import accord.maelstrom.Packet.Type;
@@ -98,9 +99,9 @@ public class Main
}
@Override
- public void reply(Id replyToNode, long replyToMessage, Reply reply)
+ public void reply(Id replyToNode, ReplyContext replyContext, Reply reply)
{
- send(new Packet(self, replyToNode, replyToMessage, reply));
+ send(new Packet(self, replyToNode, MaelstromReplyContext.messageIdFor(replyContext), reply));
}
}
@@ -163,7 +164,7 @@ public class Main
switch (next.body.type)
{
case txn:
- on.receive((MaelstromRequest)next.body, next.src, next.body.msg_id);
+ on.receive((MaelstromRequest)next.body, next.src, MaelstromReplyContext.contextFor(next.body.msg_id));
break;
default:
if (next.body.in_reply_to > Body.SENTINEL_MSG_ID)
@@ -174,7 +175,7 @@ public class Main
if (callback != null)
scheduler.now(() -> callback.callback.onSuccess(next.src, reply));
}
- else on.receive((Request)((Wrapper)next.body).body, next.src, next.body.msg_id);
+ else on.receive((Request)((Wrapper)next.body).body, next.src, MaelstromReplyContext.contextFor(next.body.msg_id));
}
}
}
diff --git a/accord-maelstrom/src/main/java/accord/maelstrom/Packet.java b/accord-maelstrom/src/main/java/accord/maelstrom/Packet.java
index bdbe9a9..4e4eaaf 100644
--- a/accord-maelstrom/src/main/java/accord/maelstrom/Packet.java
+++ b/accord-maelstrom/src/main/java/accord/maelstrom/Packet.java
@@ -7,18 +7,14 @@ import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
+import accord.messages.*;
import com.google.gson.JsonObject;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
-import accord.messages.Apply;
-import accord.messages.BeginRecovery;
-import accord.messages.ReadData;
-import accord.messages.Reply;
-import accord.messages.Request;
import accord.local.Node.Id;
-public class Packet
+public class Packet implements ReplyContext
{
public enum Type
{
diff --git a/accord-maelstrom/src/main/java/accord/maelstrom/SimpleConfigService.java b/accord-maelstrom/src/main/java/accord/maelstrom/SimpleConfigService.java
index adf4dc0..b6ec202 100644
--- a/accord-maelstrom/src/main/java/accord/maelstrom/SimpleConfigService.java
+++ b/accord-maelstrom/src/main/java/accord/maelstrom/SimpleConfigService.java
@@ -2,9 +2,12 @@ package accord.maelstrom;
import accord.api.ConfigurationService;
import accord.topology.Topology;
+import org.apache.cassandra.utils.concurrent.Future;
+import org.apache.cassandra.utils.concurrent.ImmediateFuture;
public class SimpleConfigService implements ConfigurationService
{
+ private static final Future<Void> SUCCESS = ImmediateFuture.success(null);
private final Topology topology;
public SimpleConfigService(Topology topology)
@@ -32,9 +35,9 @@ public class SimpleConfigService implements ConfigurationService
}
@Override
- public void fetchTopologyForEpoch(long epoch, Runnable onComplete)
+ public Future<Void> fetchTopologyForEpoch(long epoch)
{
-
+ return SUCCESS;
}
@Override
diff --git a/build.gradle b/build.gradle
index 7947c7a..54b9419 100644
--- a/build.gradle
+++ b/build.gradle
@@ -13,6 +13,7 @@ dependencies {
implementation 'com.google.code.gson:gson:2.8.7'
implementation 'com.google.guava:guava:30.1.1-jre'
implementation 'ch.qos.logback:logback-classic:1.2.3'
+ implementation 'io.netty:netty-all:4.1.58.Final'
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.7.0'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.7.0'
}
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For additional commands, e-mail: commits-help@cassandra.apache.org