You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cassandra.apache.org by "mansikhara (via GitHub)" <gi...@apache.org> on 2026/08/28 22:04:24 UTC
[PR] CASSANALYTICS-194: Parse / replication factor fo… [cassandra-analytics]
mansikhara opened a new pull request, #238:
URL: https://github.com/apache/cassandra-analytics/pull/238
…r witness-enabled keyspaces
Cassandra accepts a replication factor of the form <replicas>/<transient>, which witness replicas under mutation tracking reuse, so a witness-enabled keyspace declares 'datacenter1': '3/1' meaning three replicas of which one is a witness.
CqlUtils.extractReplicationFactor() passed each datacenter value to Integer.parseInt, so a bulk read against any such keyspace failed during job setup with an uncaught NumberFormatException.
Transient counts are now tracked per datacenter alongside the existing totals and exposed through getFullReplicationFactor(), getTransientReplicationFactor(), getFullReplicas(dc), getTransientReplicas(dc) and hasTransientReplicas(). getTotalReplicationFactor() keeps its existing meaning of all replicas including witnesses, so behaviour for untracked keyspaces is unchanged. Parsing applies the same constraints Cassandra enforces in locator.ReplicationFactor.validate. A new parseStrict factory reports an unparseable or empty replication map at parse time rather than dropping the datacenter and failing later with a misleading "DC not found in replication factor"; the lenient constructor is retained unchanged for CDC callers. The Kryo serializer and CassandraRing's hand-rolled JDK readObject/writeObject are updated so the new field survives serialization to Spark executors.
Prerequisite for CASSANALYTICS-164.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For additional commands, e-mail: commits-help@cassandra.apache.org
Re: [PR] CASSANALYTICS-194: Parse / replication factor fo… [cassandra-analytics]
Posted by "sarankk (via GitHub)" <gi...@apache.org>.
sarankk commented on code in PR #238:
URL: https://github.com/apache/cassandra-analytics/pull/238#discussion_r4107771952
##########
cassandra-six-zero-types/src/main/java/org/apache/cassandra/bridge/SchemaUpdater.java:
##########
@@ -72,6 +72,27 @@ public static void openKeyspaceInstances()
ClusterMetadata.current().schema.initializeKeyspaceInstances(DistributedSchema.empty(), false);
}
+ /**
+ * Creates the keyspace instance for one keyspace, leaving every other keyspace's instance untouched.
+ *
+ * <p>Prefer this to {@link #openKeyspaceInstances()} whenever the caller knows which keyspace is missing its
+ * instance. That method diffs against {@link DistributedSchema#empty()}, so every keyspace in the process looks
+ * newly created and all of them are rebuilt. Rebuilding a keyspace that already has an instance constructs its
+ * {@code KeyspaceMetrics} again, and each metric it re-registers throws {@code IllegalArgumentException} out of
+ * Dropwizard's {@code MetricRegistry.register}. Filling in those stack traces dominates the cost, and the cost
+ * grows with the number of keyspaces the process has seen, so a long-lived JVM that builds schemas repeatedly -
+ * a Spark executor, or a single test class - degrades quadratically.
+ *
+ * <p>Diffing against the current keyspaces minus this one leaves exactly one keyspace in
+ * {@code Keyspaces.diff().created}, so one instance is built and no metric is registered twice.
Review Comment:
Because a bulk job currently deals with only 1 keyspace, this issue need not show up in prod, could we update the comment to make it clear? Also shall we remove `openKeyspaceInstances()` if possible
```suggestion
* Creates the keyspace instance for one keyspace, leaving every other keyspace's instance untouched.
*
* <p>Prefer this to {@link #openKeyspaceInstances()} whenever the caller knows which keyspace is missing its
* instance. That method diffs against {@link DistributedSchema#empty()} causing every keyspace to be rebuilt again,
* which in turn rebuilds {@code KeyspaceMetrics} and registers each metric, throwing
* {@code IllegalArgumentException}. A bulk job builds schema only once per task, stack trace waste from
* exceptions thrown grows in integration tests which may open many distinct keyspaces.
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For additional commands, e-mail: commits-help@cassandra.apache.org
Re: [PR] CASSANALYTICS-194: Parse / replication factor fo… [cassandra-analytics]
Posted by "mansikhara (via GitHub)" <gi...@apache.org>.
mansikhara commented on code in PR #238:
URL: https://github.com/apache/cassandra-analytics/pull/238#discussion_r4020091351
##########
cassandra-analytics-common/src/main/java/org/apache/cassandra/spark/data/ReplicationFactor.java:
##########
@@ -108,11 +114,44 @@ public static ReplicationFactor simpleStrategy(int rf)
private final ReplicationStrategy replicationStrategy;
@NotNull
private final Map<String, Integer> options;
+ /**
+ * Per-datacenter count of transient (witness) replicas, parsed from the {@code <replicas>/<transient>} form.
+ * A datacenter absent from this map has no transient replicas. Always empty for untracked keyspaces using the
+ * plain {@code <replicas>} form, which keeps behaviour identical for those keyspaces.
+ */
+ @NotNull
+ private final Map<String, Integer> transientOptions;
+ /**
+ * Lenient parse: a replication value that cannot be parsed is logged and its datacenter omitted. Retained for
+ * callers that tolerate a partial replication factor.
+ *
+ * @param options the raw replication map, including the {@code class} entry
+ */
public ReplicationFactor(@NotNull Map<String, String> options)
+ {
+ this(options, false);
+ }
+
+ /**
+ * Strict parse: a replication value that cannot be parsed raises {@link IllegalArgumentException} naming the
+ * offending datacenter, rather than silently omitting it. Prefer this when a partial replication factor would
+ * produce a misleading failure later.
+ *
+ * @param options the raw replication map, including the {@code class} entry
+ * @return the parsed replication factor
+ * @throws IllegalArgumentException when any replication value cannot be parsed
+ */
+ public static ReplicationFactor parseStrict(@NotNull Map<String, String> options)
+ {
+ return new ReplicationFactor(options, true);
+ }
+
+ private ReplicationFactor(@NotNull Map<String, String> options, boolean strict)
{
this.replicationStrategy = ReplicationFactor.ReplicationStrategy.getEnum(options.get("class"));
this.options = new LinkedHashMap<>(options.size());
Review Comment:
Done!
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For additional commands, e-mail: commits-help@cassandra.apache.org
Re: [PR] CASSANALYTICS-194: Parse / replication factor fo… [cassandra-analytics]
Posted by "sarankk (via GitHub)" <gi...@apache.org>.
sarankk commented on code in PR #238:
URL: https://github.com/apache/cassandra-analytics/pull/238#discussion_r4031372985
##########
cassandra-analytics-common/src/main/java/org/apache/cassandra/spark/data/ReplicationFactor.java:
##########
@@ -106,62 +110,204 @@ public static ReplicationFactor simpleStrategy(int rf)
@NotNull
private final ReplicationStrategy replicationStrategy;
+ /**
+ * Per-datacenter replica counts. Holding the total and the transient count together, rather than in two
+ * parallel maps, means the two cannot drift apart.
+ */
@NotNull
- private final Map<String, Integer> options;
+ private final Map<String, ReplicaCounts> replication;
+ /**
+ * Parses a raw replication map. A value that cannot be parsed, or that Cassandra itself would reject, raises
+ * {@link IllegalArgumentException} naming the offending datacenter: a partial replication factor is not usable
+ * and reporting it here avoids a misleading failure later, such as "DC not found in replication factor".
+ *
+ * @param options the raw replication map, including the {@code class} entry
+ * @throws IllegalArgumentException when any replication value cannot be parsed
+ */
public ReplicationFactor(@NotNull Map<String, String> options)
{
this.replicationStrategy = ReplicationFactor.ReplicationStrategy.getEnum(options.get("class"));
- this.options = new LinkedHashMap<>(options.size());
+ Map<String, ReplicaCounts> parsed = new LinkedHashMap<>(options.size());
for (Map.Entry<String, String> entry : options.entrySet())
{
if ("class".equals(entry.getKey()))
{
continue;
}
-
try
{
- this.options.put(entry.getKey(), Integer.parseInt(entry.getValue()));
+ parsed.put(entry.getKey(), ReplicaCounts.parse(entry.getValue()));
}
- catch (NumberFormatException exception)
+ catch (IllegalArgumentException exception)
{
- LOGGER.warn("Could not parse replication option: {} = {}", entry.getKey(), entry.getValue());
+ throw new IllegalArgumentException(String.format("Could not parse replication option: %s = %s",
+ entry.getKey(), entry.getValue()), exception);
}
}
+ validateNotEmpty(this.replicationStrategy, parsed, options);
+ this.replication = Collections.unmodifiableMap(parsed);
}
public ReplicationFactor(@NotNull ReplicationStrategy replicationStrategy, @NotNull Map<String, Integer> options)
{
- this.replicationStrategy = replicationStrategy;
- this.options = new LinkedHashMap<>(options.size());
-
- if (!replicationStrategy.equals(ReplicationStrategy.LocalStrategy) && options.isEmpty())
- {
- throw new RuntimeException(String.format("Could not find replication info in schema map: %s.", options));
- }
+ this(replicationStrategy, options, Collections.emptyMap());
+ }
+ public ReplicationFactor(@NotNull ReplicationStrategy replicationStrategy,
+ @NotNull Map<String, Integer> options,
+ @NotNull Map<String, Integer> transientOptions)
+ {
+ this.replicationStrategy = replicationStrategy;
+ Map<String, ReplicaCounts> merged = new LinkedHashMap<>(options.size());
for (Map.Entry<String, Integer> entry : options.entrySet())
{
if ("class".equals(entry.getKey()))
{
continue;
}
- this.options.put(entry.getKey(), entry.getValue());
+ int transientReplicas = transientOptions.getOrDefault(entry.getKey(), 0);
+ merged.put(entry.getKey(), ReplicaCounts.of(entry.getKey(), entry.getValue(), transientReplicas));
+ }
+ for (String datacenter : transientOptions.keySet())
+ {
+ if (!"class".equals(datacenter) && !merged.containsKey(datacenter)
+ && transientOptions.get(datacenter) != null && transientOptions.get(datacenter) != 0)
+ {
+ throw new IllegalArgumentException(String.format(
+ "Transient replicas specified for %s but it has no replication factor", datacenter));
+ }
+ }
+ validateNotEmpty(replicationStrategy, merged, options);
+ this.replication = Collections.unmodifiableMap(merged);
+ }
+
+ /**
+ * Canonical constructor. {@code validate} exists only for {@link #readResolve()}, which must not reject an
+ * instance that an earlier version was willing to create.
+ */
+ private ReplicationFactor(@NotNull ReplicationStrategy replicationStrategy,
+ @NotNull Map<String, ReplicaCounts> replication,
+ boolean validate)
+ {
+ this.replicationStrategy = replicationStrategy;
+ if (validate)
Review Comment:
Can we delete this flag, it is always false
##########
cassandra-analytics-common/src/main/java/org/apache/cassandra/spark/data/partitioner/CassandraRing.java:
##########
@@ -295,6 +322,13 @@ private void writeObject(ObjectOutputStream out) throws IOException, ClassNotFou
out.writeUTF(option.getKey());
out.writeByte(option.getValue());
}
+ Map<String, Integer> transientOptions = this.replicationFactor.getTransientOptions();
Review Comment:
Why are we writing options and transient options separately? could we write `ReplicationFactor` itself since it is serializable?
##########
cassandra-analytics-common/src/main/java/org/apache/cassandra/spark/data/ReplicationFactor.java:
##########
@@ -106,62 +110,204 @@ public static ReplicationFactor simpleStrategy(int rf)
@NotNull
private final ReplicationStrategy replicationStrategy;
+ /**
+ * Per-datacenter replica counts. Holding the total and the transient count together, rather than in two
+ * parallel maps, means the two cannot drift apart.
+ */
@NotNull
- private final Map<String, Integer> options;
+ private final Map<String, ReplicaCounts> replication;
+ /**
+ * Parses a raw replication map. A value that cannot be parsed, or that Cassandra itself would reject, raises
+ * {@link IllegalArgumentException} naming the offending datacenter: a partial replication factor is not usable
+ * and reporting it here avoids a misleading failure later, such as "DC not found in replication factor".
+ *
+ * @param options the raw replication map, including the {@code class} entry
+ * @throws IllegalArgumentException when any replication value cannot be parsed
+ */
public ReplicationFactor(@NotNull Map<String, String> options)
{
this.replicationStrategy = ReplicationFactor.ReplicationStrategy.getEnum(options.get("class"));
- this.options = new LinkedHashMap<>(options.size());
+ Map<String, ReplicaCounts> parsed = new LinkedHashMap<>(options.size());
for (Map.Entry<String, String> entry : options.entrySet())
{
if ("class".equals(entry.getKey()))
{
continue;
}
-
try
{
- this.options.put(entry.getKey(), Integer.parseInt(entry.getValue()));
+ parsed.put(entry.getKey(), ReplicaCounts.parse(entry.getValue()));
}
- catch (NumberFormatException exception)
+ catch (IllegalArgumentException exception)
{
- LOGGER.warn("Could not parse replication option: {} = {}", entry.getKey(), entry.getValue());
+ throw new IllegalArgumentException(String.format("Could not parse replication option: %s = %s",
+ entry.getKey(), entry.getValue()), exception);
}
}
+ validateNotEmpty(this.replicationStrategy, parsed, options);
+ this.replication = Collections.unmodifiableMap(parsed);
}
public ReplicationFactor(@NotNull ReplicationStrategy replicationStrategy, @NotNull Map<String, Integer> options)
{
- this.replicationStrategy = replicationStrategy;
- this.options = new LinkedHashMap<>(options.size());
-
- if (!replicationStrategy.equals(ReplicationStrategy.LocalStrategy) && options.isEmpty())
- {
- throw new RuntimeException(String.format("Could not find replication info in schema map: %s.", options));
- }
+ this(replicationStrategy, options, Collections.emptyMap());
+ }
+ public ReplicationFactor(@NotNull ReplicationStrategy replicationStrategy,
+ @NotNull Map<String, Integer> options,
+ @NotNull Map<String, Integer> transientOptions)
+ {
+ this.replicationStrategy = replicationStrategy;
+ Map<String, ReplicaCounts> merged = new LinkedHashMap<>(options.size());
for (Map.Entry<String, Integer> entry : options.entrySet())
Review Comment:
Nit: We seem to repeat these bits among constructors, existing code seems to have 3 constructors, with transient options we seem to have 4, could we restructure these?
##########
cassandra-analytics-core/src/test/java/org/apache/cassandra/spark/utils/CqlUtilsTest.java:
##########
@@ -142,6 +142,83 @@ public void testExtractReplicationFactor(CassandraBridge bridge)
assertThat(systemSchemaRf.getOptions()).isEqualTo(ImmutableMap.of());
}
+ @Test
+ public void testExtractReplicationFactorWithWitnessReplicas()
+ {
+ // The <replicas>/<transient> form, as Cassandra's WitnessAlwaysReadsFullReplicaTest creates it on the
+ // cep-45-mutation-tracking branch. replication_type is deliberately omitted: Sidecar builds its schema
+ // response from the driver's exportAsString(), which does not emit that property, and it is irrelevant to
+ // replication factor parsing in any case. extractReplicationType is covered separately.
Review Comment:
Nit: remove comment, `<replicas>/<transient>` existed prior to cep-45 branch and rest is not necessary
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For additional commands, e-mail: commits-help@cassandra.apache.org
Re: [PR] CASSANALYTICS-194: Parse / replication factor fo… [cassandra-analytics]
Posted by "mansikhara (via GitHub)" <gi...@apache.org>.
mansikhara commented on code in PR #238:
URL: https://github.com/apache/cassandra-analytics/pull/238#discussion_r4086240120
##########
cassandra-analytics-common/src/main/java/org/apache/cassandra/spark/data/ReplicationFactor.java:
##########
@@ -203,25 +534,29 @@ public static class Serializer extends com.esotericsoftware.kryo.Serializer<Repl
public void write(Kryo kryo, Output out, ReplicationFactor replicationFactor)
{
out.writeByte(replicationFactor.replicationStrategy.value);
- out.writeByte(replicationFactor.options.size());
- for (Map.Entry<String, Integer> entry : replicationFactor.options.entrySet())
+ out.writeByte(replicationFactor.replication.size());
+ for (Map.Entry<String, ReplicaCounts> entry : replicationFactor.replication.entrySet())
{
out.writeString(entry.getKey());
- out.writeByte(entry.getValue());
+ out.writeByte(entry.getValue().allReplicas());
+ out.writeByte(entry.getValue().transientReplicas());
Review Comment:
Done, thanks!
But, practically the exposure is narrow: driver and executors always load the same jar, so old and new bytes can't meet inside a job, and the RF isn't persisted between jobs. But it's one byte and it makes the next format change safe, so I've added it here!
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For additional commands, e-mail: commits-help@cassandra.apache.org
Re: [PR] CASSANALYTICS-194: Parse / replication factor fo… [cassandra-analytics]
Posted by "sarankk (via GitHub)" <gi...@apache.org>.
sarankk merged PR #238:
URL: https://github.com/apache/cassandra-analytics/pull/238
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For additional commands, e-mail: commits-help@cassandra.apache.org
Re: [PR] CASSANALYTICS-194: Parse / replication factor fo… [cassandra-analytics]
Posted by "mansikhara (via GitHub)" <gi...@apache.org>.
mansikhara commented on code in PR #238:
URL: https://github.com/apache/cassandra-analytics/pull/238#discussion_r4020075785
##########
cassandra-analytics-common/src/main/java/org/apache/cassandra/spark/data/ReplicationFactor.java:
##########
@@ -108,11 +114,44 @@ public static ReplicationFactor simpleStrategy(int rf)
private final ReplicationStrategy replicationStrategy;
@NotNull
private final Map<String, Integer> options;
+ /**
+ * Per-datacenter count of transient (witness) replicas, parsed from the {@code <replicas>/<transient>} form.
+ * A datacenter absent from this map has no transient replicas. Always empty for untracked keyspaces using the
+ * plain {@code <replicas>} form, which keeps behaviour identical for those keyspaces.
+ */
+ @NotNull
+ private final Map<String, Integer> transientOptions;
+ /**
+ * Lenient parse: a replication value that cannot be parsed is logged and its datacenter omitted. Retained for
Review Comment:
None, as it turns out. I checked the callers and there are only two, ReplicationFactorSupplier and CdcOptions, and both build hardcoded maps that cannot fail to parse. So I have removed the lenient path entirely and made strict the only behaviour! Thanks for the find
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For additional commands, e-mail: commits-help@cassandra.apache.org
Re: [PR] CASSANALYTICS-194: Parse / replication factor fo… [cassandra-analytics]
Posted by "jyothsnakonisa (via GitHub)" <gi...@apache.org>.
jyothsnakonisa commented on code in PR #238:
URL: https://github.com/apache/cassandra-analytics/pull/238#discussion_r4077978962
##########
cassandra-analytics-common/src/main/java/org/apache/cassandra/spark/data/ReplicationFactor.java:
##########
@@ -188,13 +359,173 @@ public boolean equals(Object other)
ReplicationFactor that = (ReplicationFactor) other;
return this.replicationStrategy == that.replicationStrategy
- && java.util.Objects.equals(this.options, that.options);
+ && Objects.equals(this.replication, that.replication);
}
@Override
public int hashCode()
{
- return Objects.hash(replicationStrategy, options);
+ return Objects.hash(replicationStrategy, replication);
+ }
+
+ /**
+ * {@link #serialVersionUID} is pinned, so an instance serialized before the per-datacenter counts were combined
+ * deserializes with a {@code null} {@code replication}. Only reachable under driver/executor version skew, which
+ * is not a supported configuration, so this reports the mismatch rather than silently losing the counts.
+ *
+ * @return this instance
+ * @throws InvalidObjectException when deserialized from an incompatible older form
+ */
+ private Object readResolve() throws InvalidObjectException
+ {
+ if (replication == null)
+ {
+ throw new InvalidObjectException(
+ "ReplicationFactor was serialized by an incompatible version: per-datacenter replica counts are absent. "
+ + "Driver and executors must run the same version.");
+ }
+ // Rebuild through the canonical constructor so the derived fields, which are transient, are populated
+ return new ReplicationFactor(replicationStrategy, replication, replication);
+ }
+
+ /**
+ * Replica counts for a single datacenter. Cassandra accepts either {@code <replicas>} or
+ * {@code <replicas>/<transient>}; transient replication predates mutation tracking, and witness replicas
+ * (CEP-46) reuse the same form. See {@code org.apache.cassandra.locator.ReplicationFactor} in Cassandra.
+ */
+ public static final class ReplicaCounts implements Serializable
+ {
+ private static final long serialVersionUID = 2026091500000000001L;
+ private static final String TRANSIENT_SEPARATOR = "/";
+
+ private final int allReplicas;
+ private final int transientReplicas;
+
+ private ReplicaCounts(int allReplicas, int transientReplicas)
+ {
+ this.allReplicas = allReplicas;
+ this.transientReplicas = transientReplicas;
+ }
+
+ /**
+ * @param datacenter datacenter name, used only in error messages, may be {@code null}
+ * @param allReplicas total replicas
+ * @param transientReplicas transient (witness) replicas
+ * @return validated counts
+ * @throws IllegalArgumentException when the counts are inconsistent
+ */
+ public static ReplicaCounts of(String datacenter, int allReplicas, int transientReplicas)
+ {
+ validate(datacenter, allReplicas, transientReplicas);
+ return new ReplicaCounts(allReplicas, transientReplicas);
+ }
+
+ /**
+ * @return total replicas, including transient (witness) replicas
+ */
+ public int allReplicas()
+ {
+ return allReplicas;
+ }
+
+ /**
+ * @return replicas holding the full data set
+ */
+ public int fullReplicas()
+ {
+ return allReplicas - transientReplicas;
+ }
+
+ /**
+ * @return transient (witness) replicas, {@code 0} when none are configured
+ */
+ public int transientReplicas()
+ {
+ return transientReplicas;
+ }
+
+ /**
+ * @param value the raw replication value, e.g. {@code "3"} or {@code "3/1"}
+ * @return the parsed replica counts
+ * @throws NumberFormatException when either component is not an integer
+ * @throws IllegalArgumentException when the value is malformed or the counts are inconsistent
+ */
+ static ReplicaCounts parse(@NotNull String value)
+ {
+ String trimmed = value.trim();
+ int separator = trimmed.indexOf(TRANSIENT_SEPARATOR);
+ if (separator < 0)
+ {
+ return of(null, Integer.parseInt(trimmed), 0);
+ }
+
+ if (trimmed.indexOf(TRANSIENT_SEPARATOR, separator + 1) >= 0)
+ {
+ throw new IllegalArgumentException(String.format(
+ "Replication factor format is <replicas> or <replicas>/<transient>, found '%s'", value));
+ }
+
+ return of(null,
+ Integer.parseInt(trimmed.substring(0, separator).trim()),
+ Integer.parseInt(trimmed.substring(separator + 1).trim()));
+ }
+
+ /**
+ * Mirrors the constraints Cassandra enforces in {@code ReplicationFactor.validate}: transient replicas must
+ * be non-negative and strictly fewer than the total, so at least one full replica always exists.
+ *
+ * @param datacenter datacenter name for the error message, may be {@code null}
+ * @param allReplicas total replicas
+ * @param transientReplicas transient (witness) replicas
+ */
+ static void validate(String datacenter, int allReplicas, int transientReplicas)
Review Comment:
ReplicaCounts class doesn't need `datacenter` at all and the datacenter argument fit here in this method. I see that you are passing this for logging can u try moving logging out of this class
##########
cassandra-analytics-common/src/main/java/org/apache/cassandra/spark/data/ReplicationFactor.java:
##########
@@ -188,13 +359,173 @@ public boolean equals(Object other)
ReplicationFactor that = (ReplicationFactor) other;
return this.replicationStrategy == that.replicationStrategy
- && java.util.Objects.equals(this.options, that.options);
+ && Objects.equals(this.replication, that.replication);
}
@Override
public int hashCode()
{
- return Objects.hash(replicationStrategy, options);
+ return Objects.hash(replicationStrategy, replication);
+ }
+
+ /**
+ * {@link #serialVersionUID} is pinned, so an instance serialized before the per-datacenter counts were combined
+ * deserializes with a {@code null} {@code replication}. Only reachable under driver/executor version skew, which
+ * is not a supported configuration, so this reports the mismatch rather than silently losing the counts.
+ *
+ * @return this instance
+ * @throws InvalidObjectException when deserialized from an incompatible older form
+ */
+ private Object readResolve() throws InvalidObjectException
+ {
+ if (replication == null)
+ {
+ throw new InvalidObjectException(
+ "ReplicationFactor was serialized by an incompatible version: per-datacenter replica counts are absent. "
+ + "Driver and executors must run the same version.");
+ }
+ // Rebuild through the canonical constructor so the derived fields, which are transient, are populated
+ return new ReplicationFactor(replicationStrategy, replication, replication);
+ }
+
+ /**
+ * Replica counts for a single datacenter. Cassandra accepts either {@code <replicas>} or
+ * {@code <replicas>/<transient>}; transient replication predates mutation tracking, and witness replicas
+ * (CEP-46) reuse the same form. See {@code org.apache.cassandra.locator.ReplicationFactor} in Cassandra.
+ */
+ public static final class ReplicaCounts implements Serializable
+ {
+ private static final long serialVersionUID = 2026091500000000001L;
+ private static final String TRANSIENT_SEPARATOR = "/";
+
+ private final int allReplicas;
+ private final int transientReplicas;
+
+ private ReplicaCounts(int allReplicas, int transientReplicas)
+ {
+ this.allReplicas = allReplicas;
+ this.transientReplicas = transientReplicas;
+ }
+
+ /**
+ * @param datacenter datacenter name, used only in error messages, may be {@code null}
+ * @param allReplicas total replicas
+ * @param transientReplicas transient (witness) replicas
+ * @return validated counts
+ * @throws IllegalArgumentException when the counts are inconsistent
+ */
+ public static ReplicaCounts of(String datacenter, int allReplicas, int transientReplicas)
Review Comment:
ReplicaCounts class doesn't need datacenter at all and the datacenter argument fit here in this method. I see that you are passing this for logging can u try moving logging out of this class
##########
cassandra-analytics-common/src/main/java/org/apache/cassandra/spark/data/ReplicationFactor.java:
##########
@@ -203,25 +534,29 @@ public static class Serializer extends com.esotericsoftware.kryo.Serializer<Repl
public void write(Kryo kryo, Output out, ReplicationFactor replicationFactor)
{
out.writeByte(replicationFactor.replicationStrategy.value);
- out.writeByte(replicationFactor.options.size());
- for (Map.Entry<String, Integer> entry : replicationFactor.options.entrySet())
+ out.writeByte(replicationFactor.replication.size());
+ for (Map.Entry<String, ReplicaCounts> entry : replicationFactor.replication.entrySet())
{
out.writeString(entry.getKey());
- out.writeByte(entry.getValue());
+ out.writeByte(entry.getValue().allReplicas());
+ out.writeByte(entry.getValue().transientReplicas());
Review Comment:
This adds a new field to the Kryo wire format (1 byte/DC → 2 bytes/DC) with no version marker, so an old-format ReplicationFactor read by this new code would crash or silently produce wrong RF values.
CassandraRing solves this exact problem for its own serialization with a version byte, and this is actually the primary path Spark uses (its JDK fallback is just a fallback), so it seems worth the same protection here.
##########
cassandra-analytics-common/src/test/java/org/apache/cassandra/spark/data/ReplicationFactorTests.java:
##########
@@ -111,4 +118,357 @@ public void testEquality()
assertThat(replicationFactor1).isEqualTo(replicationFactor2);
assertThat(replicationFactor1.hashCode()).isEqualTo(replicationFactor2.hashCode());
}
+
+ // Transient / witness replicas: the <replicas>/<transient> form, reused by witness replicas under
+ // mutation tracking (CEP-45/CEP-46)
+
+ @Test
+ public void testNoTransientReplicasByDefault()
+ {
+ ReplicationFactor replicationFactor = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "3"));
+ assertThat(replicationFactor.hasTransientReplicas()).isFalse();
+ assertThat(replicationFactor.getTransientOptions()).isEmpty();
+ assertThat(replicationFactor.getTotalReplicationFactor()).isEqualTo(3);
+ assertThat(replicationFactor.getFullReplicationFactor()).isEqualTo(3);
+ assertThat(replicationFactor.getTransientReplicationFactor()).isEqualTo(0);
+ assertThat(replicationFactor.getFullReplicas("datacenter1")).isEqualTo(3);
+ assertThat(replicationFactor.getTransientReplicas("datacenter1")).isEqualTo(0);
+ }
+
+ @Test
+ public void testTransientReplicasSingleDatacenter()
+ {
+ ReplicationFactor replicationFactor = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "3/1"));
+ assertThat(replicationFactor.hasTransientReplicas()).isTrue();
+ // total keeps its original meaning: all replicas, witnesses included
+ assertThat(replicationFactor.getOptions().get("datacenter1")).isEqualTo(Integer.valueOf(3));
+ assertThat(replicationFactor.getTotalReplicationFactor()).isEqualTo(3);
+ assertThat(replicationFactor.getFullReplicationFactor()).isEqualTo(2);
+ assertThat(replicationFactor.getTransientReplicationFactor()).isEqualTo(1);
+ assertThat(replicationFactor.getFullReplicas("datacenter1")).isEqualTo(2);
+ assertThat(replicationFactor.getTransientReplicas("datacenter1")).isEqualTo(1);
+ }
+
+ @Test
+ public void testTransientReplicasMultipleDatacenters()
+ {
+ ReplicationFactor replicationFactor = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "3/1",
+ "datacenter2", "3/1"));
+ assertThat(replicationFactor.getTotalReplicationFactor()).isEqualTo(6);
+ assertThat(replicationFactor.getFullReplicationFactor()).isEqualTo(4);
+ assertThat(replicationFactor.getTransientReplicationFactor()).isEqualTo(2);
+ }
+
+ @Test
+ public void testMixedTransientAndFullDatacenters()
+ {
+ ReplicationFactor replicationFactor = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "3/1",
+ "datacenter2", "3"));
+ assertThat(replicationFactor.getTotalReplicationFactor()).isEqualTo(6);
+ assertThat(replicationFactor.getFullReplicationFactor()).isEqualTo(5);
+ assertThat(replicationFactor.getTransientReplicas("datacenter1")).isEqualTo(1);
+ assertThat(replicationFactor.getTransientReplicas("datacenter2")).isEqualTo(0);
+ assertThat(replicationFactor.getFullReplicas("datacenter2")).isEqualTo(3);
+ // datacenter2 has no transient replicas, so it must be absent rather than mapped to zero
+ assertThat(replicationFactor.getTransientOptions()).containsOnlyKeys("datacenter1");
+ }
+
+ @Test
+ public void testTransientReplicasSimpleStrategy()
+ {
+ ReplicationFactor replicationFactor = new ReplicationFactor(ImmutableMap.of(
+ "class", "SimpleStrategy",
+ "replication_factor", "3/1"));
+ assertThat(replicationFactor.getReplicationStrategy())
+ .isEqualTo(ReplicationFactor.ReplicationStrategy.SimpleStrategy);
+ assertThat(replicationFactor.getTotalReplicationFactor()).isEqualTo(3);
+ assertThat(replicationFactor.getFullReplicationFactor()).isEqualTo(2);
+ }
+
+ @Test
+ public void testTransientReplicasWithWhitespace()
+ {
+ ReplicationFactor replicationFactor = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", " 3 / 1 "));
+ assertThat(replicationFactor.getTotalReplicationFactor()).isEqualTo(3);
+ assertThat(replicationFactor.getFullReplicationFactor()).isEqualTo(2);
+ }
+
+ @Test
+ public void testTransientEqualToTotalIsRejected()
+ {
+ // Cassandra requires at least one full replica, so 3/3 is invalid and must not be accepted silently
+ assertThatThrownBy(() -> new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "3/3")))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("datacenter1");
+ }
+
+ @Test
+ public void testMalformedReplicationValuesAreRejected()
+ {
+ for (String malformed : new String[]{"3/", "/1", "3/1/1", "3/x", "x/1", "3/-1", ""})
+ {
+ assertThatThrownBy(() -> new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", malformed)))
+ .as("malformed replication value '%s' should be rejected", malformed)
+ .isInstanceOf(IllegalArgumentException.class);
+ }
+ }
+
+ @Test
+ public void testGetFullReplicasUnknownDatacenter()
+ {
+ ReplicationFactor replicationFactor = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "3/1"));
+ assertThatThrownBy(() -> replicationFactor.getFullReplicas("nosuchdc"))
+ .isInstanceOf(IllegalArgumentException.class);
+ }
+
+ @Test
+ public void testTransientOptionsForUnknownDatacenterRejected()
+ {
+ assertThatThrownBy(() -> new ReplicationFactor(
+ ReplicationFactor.ReplicationStrategy.NetworkTopologyStrategy,
+ ImmutableMap.of("datacenter1", 3),
+ ImmutableMap.of("datacenter2", 1)))
+ .isInstanceOf(IllegalArgumentException.class);
+ }
+
+ @Test
+ public void testEqualityConsidersTransientReplicas()
+ {
+ ReplicationFactor full = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "3"));
+ ReplicationFactor withTransient = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "3/1"));
+ assertThat(full).isNotEqualTo(withTransient);
+ assertThat(full.hashCode()).isNotEqualTo(withTransient.hashCode());
+ }
+
+ @Test
+ public void testNegativeReplicationFactorIsRejected()
+ {
+ assertThatThrownBy(() -> new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "-3")))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("datacenter1");
+ }
+
+ @Test
+ public void testZeroReplicationFactorIsAllowed()
+ {
+ // RF 0 is legitimate for NetworkTopologyStrategy: the keyspace is simply not replicated to that datacenter
+ ReplicationFactor replicationFactor = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "3",
+ "datacenter2", "0"));
+ assertThat(replicationFactor.getOptions().get("datacenter2")).isEqualTo(Integer.valueOf(0));
+ assertThat(replicationFactor.getTotalReplicationFactor()).isEqualTo(3);
+ }
+
+ @Test
+ public void testKryoSerializationRoundTripWithTransientReplicas() throws Exception
+ {
+ ReplicationFactor original = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "3/1",
+ "datacenter2", "3"));
+
+ Kryo kryo = new Kryo();
+ kryo.register(ReplicationFactor.class, new ReplicationFactor.Serializer());
+
+ ByteArrayOutputStream bytes = new ByteArrayOutputStream();
+ try (Output out = new Output(bytes))
+ {
+ kryo.writeObject(out, original);
+ }
+ ReplicationFactor deserialized;
+ try (Input in = new Input(new ByteArrayInputStream(bytes.toByteArray())))
+ {
+ deserialized = kryo.readObject(in, ReplicationFactor.class);
+ }
+
+ assertThat(deserialized).isEqualTo(original);
+ assertThat(deserialized.getTotalReplicationFactor()).isEqualTo(6);
+ assertThat(deserialized.getFullReplicationFactor()).isEqualTo(5);
+ assertThat(deserialized.getTransientReplicas("datacenter1")).isEqualTo(1);
+ assertThat(deserialized.getTransientReplicas("datacenter2")).isEqualTo(0);
+ }
+
+ @Test
+ public void testJdkSerializationRoundTripWithTransientReplicas() throws Exception
Review Comment:
Same here, this test Is identical to testPrecomputedValuesSurviveJdkSerialization, WDYT of merging them
##########
cassandra-analytics-common/src/test/java/org/apache/cassandra/spark/data/ReplicationFactorTests.java:
##########
@@ -111,4 +118,357 @@ public void testEquality()
assertThat(replicationFactor1).isEqualTo(replicationFactor2);
assertThat(replicationFactor1.hashCode()).isEqualTo(replicationFactor2.hashCode());
}
+
+ // Transient / witness replicas: the <replicas>/<transient> form, reused by witness replicas under
+ // mutation tracking (CEP-45/CEP-46)
+
+ @Test
+ public void testNoTransientReplicasByDefault()
+ {
+ ReplicationFactor replicationFactor = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "3"));
+ assertThat(replicationFactor.hasTransientReplicas()).isFalse();
+ assertThat(replicationFactor.getTransientOptions()).isEmpty();
+ assertThat(replicationFactor.getTotalReplicationFactor()).isEqualTo(3);
+ assertThat(replicationFactor.getFullReplicationFactor()).isEqualTo(3);
+ assertThat(replicationFactor.getTransientReplicationFactor()).isEqualTo(0);
+ assertThat(replicationFactor.getFullReplicas("datacenter1")).isEqualTo(3);
+ assertThat(replicationFactor.getTransientReplicas("datacenter1")).isEqualTo(0);
+ }
+
+ @Test
+ public void testTransientReplicasSingleDatacenter()
+ {
+ ReplicationFactor replicationFactor = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "3/1"));
+ assertThat(replicationFactor.hasTransientReplicas()).isTrue();
+ // total keeps its original meaning: all replicas, witnesses included
+ assertThat(replicationFactor.getOptions().get("datacenter1")).isEqualTo(Integer.valueOf(3));
+ assertThat(replicationFactor.getTotalReplicationFactor()).isEqualTo(3);
+ assertThat(replicationFactor.getFullReplicationFactor()).isEqualTo(2);
+ assertThat(replicationFactor.getTransientReplicationFactor()).isEqualTo(1);
+ assertThat(replicationFactor.getFullReplicas("datacenter1")).isEqualTo(2);
+ assertThat(replicationFactor.getTransientReplicas("datacenter1")).isEqualTo(1);
+ }
+
+ @Test
+ public void testTransientReplicasMultipleDatacenters()
+ {
+ ReplicationFactor replicationFactor = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "3/1",
+ "datacenter2", "3/1"));
+ assertThat(replicationFactor.getTotalReplicationFactor()).isEqualTo(6);
+ assertThat(replicationFactor.getFullReplicationFactor()).isEqualTo(4);
+ assertThat(replicationFactor.getTransientReplicationFactor()).isEqualTo(2);
+ }
+
+ @Test
+ public void testMixedTransientAndFullDatacenters()
+ {
+ ReplicationFactor replicationFactor = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "3/1",
+ "datacenter2", "3"));
+ assertThat(replicationFactor.getTotalReplicationFactor()).isEqualTo(6);
+ assertThat(replicationFactor.getFullReplicationFactor()).isEqualTo(5);
+ assertThat(replicationFactor.getTransientReplicas("datacenter1")).isEqualTo(1);
+ assertThat(replicationFactor.getTransientReplicas("datacenter2")).isEqualTo(0);
+ assertThat(replicationFactor.getFullReplicas("datacenter2")).isEqualTo(3);
+ // datacenter2 has no transient replicas, so it must be absent rather than mapped to zero
+ assertThat(replicationFactor.getTransientOptions()).containsOnlyKeys("datacenter1");
+ }
+
+ @Test
+ public void testTransientReplicasSimpleStrategy()
+ {
+ ReplicationFactor replicationFactor = new ReplicationFactor(ImmutableMap.of(
+ "class", "SimpleStrategy",
+ "replication_factor", "3/1"));
+ assertThat(replicationFactor.getReplicationStrategy())
+ .isEqualTo(ReplicationFactor.ReplicationStrategy.SimpleStrategy);
+ assertThat(replicationFactor.getTotalReplicationFactor()).isEqualTo(3);
+ assertThat(replicationFactor.getFullReplicationFactor()).isEqualTo(2);
+ }
+
+ @Test
+ public void testTransientReplicasWithWhitespace()
+ {
+ ReplicationFactor replicationFactor = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", " 3 / 1 "));
+ assertThat(replicationFactor.getTotalReplicationFactor()).isEqualTo(3);
+ assertThat(replicationFactor.getFullReplicationFactor()).isEqualTo(2);
+ }
+
+ @Test
+ public void testTransientEqualToTotalIsRejected()
+ {
+ // Cassandra requires at least one full replica, so 3/3 is invalid and must not be accepted silently
+ assertThatThrownBy(() -> new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "3/3")))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("datacenter1");
+ }
+
+ @Test
+ public void testMalformedReplicationValuesAreRejected()
+ {
+ for (String malformed : new String[]{"3/", "/1", "3/1/1", "3/x", "x/1", "3/-1", ""})
+ {
+ assertThatThrownBy(() -> new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", malformed)))
+ .as("malformed replication value '%s' should be rejected", malformed)
+ .isInstanceOf(IllegalArgumentException.class);
+ }
+ }
+
+ @Test
+ public void testGetFullReplicasUnknownDatacenter()
+ {
+ ReplicationFactor replicationFactor = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "3/1"));
+ assertThatThrownBy(() -> replicationFactor.getFullReplicas("nosuchdc"))
+ .isInstanceOf(IllegalArgumentException.class);
+ }
+
+ @Test
+ public void testTransientOptionsForUnknownDatacenterRejected()
+ {
+ assertThatThrownBy(() -> new ReplicationFactor(
+ ReplicationFactor.ReplicationStrategy.NetworkTopologyStrategy,
+ ImmutableMap.of("datacenter1", 3),
+ ImmutableMap.of("datacenter2", 1)))
+ .isInstanceOf(IllegalArgumentException.class);
+ }
+
+ @Test
+ public void testEqualityConsidersTransientReplicas()
+ {
+ ReplicationFactor full = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "3"));
+ ReplicationFactor withTransient = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "3/1"));
+ assertThat(full).isNotEqualTo(withTransient);
+ assertThat(full.hashCode()).isNotEqualTo(withTransient.hashCode());
+ }
+
+ @Test
+ public void testNegativeReplicationFactorIsRejected()
+ {
+ assertThatThrownBy(() -> new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "-3")))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("datacenter1");
+ }
+
+ @Test
+ public void testZeroReplicationFactorIsAllowed()
+ {
+ // RF 0 is legitimate for NetworkTopologyStrategy: the keyspace is simply not replicated to that datacenter
+ ReplicationFactor replicationFactor = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "3",
+ "datacenter2", "0"));
+ assertThat(replicationFactor.getOptions().get("datacenter2")).isEqualTo(Integer.valueOf(0));
+ assertThat(replicationFactor.getTotalReplicationFactor()).isEqualTo(3);
+ }
+
+ @Test
+ public void testKryoSerializationRoundTripWithTransientReplicas() throws Exception
Review Comment:
This test is almost identical to testPrecomputedValuesSurviveKryoSerialization, WDYT of merging them?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For additional commands, e-mail: commits-help@cassandra.apache.org
Re: [PR] CASSANALYTICS-194: Parse / replication factor fo… [cassandra-analytics]
Posted by "mansikhara (via GitHub)" <gi...@apache.org>.
mansikhara commented on code in PR #238:
URL: https://github.com/apache/cassandra-analytics/pull/238#discussion_r4020099123
##########
cassandra-analytics-common/src/test/java/org/apache/cassandra/spark/data/ReplicationFactorTests.java:
##########
@@ -111,4 +118,296 @@ public void testEquality()
assertThat(replicationFactor1).isEqualTo(replicationFactor2);
assertThat(replicationFactor1.hashCode()).isEqualTo(replicationFactor2.hashCode());
}
+
+ // Transient / witness replicas: the <replicas>/<transient> form, reused by witness replicas under
+ // mutation tracking (CEP-45/CEP-46)
+
+ @Test
+ public void testNoTransientReplicasByDefault()
+ {
+ ReplicationFactor replicationFactor = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "3"));
+ assertThat(replicationFactor.hasTransientReplicas()).isFalse();
+ assertThat(replicationFactor.getTransientOptions()).isEmpty();
+ assertThat(replicationFactor.getTotalReplicationFactor()).isEqualTo(3);
+ assertThat(replicationFactor.getFullReplicationFactor()).isEqualTo(3);
+ assertThat(replicationFactor.getTransientReplicationFactor()).isEqualTo(0);
+ assertThat(replicationFactor.getFullReplicas("datacenter1")).isEqualTo(3);
+ assertThat(replicationFactor.getTransientReplicas("datacenter1")).isEqualTo(0);
+ }
+
+ @Test
+ public void testTransientReplicasSingleDatacenter()
+ {
+ ReplicationFactor replicationFactor = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "3/1"));
+ assertThat(replicationFactor.hasTransientReplicas()).isTrue();
+ // total keeps its original meaning: all replicas, witnesses included
+ assertThat(replicationFactor.getOptions().get("datacenter1")).isEqualTo(Integer.valueOf(3));
+ assertThat(replicationFactor.getTotalReplicationFactor()).isEqualTo(3);
+ assertThat(replicationFactor.getFullReplicationFactor()).isEqualTo(2);
+ assertThat(replicationFactor.getTransientReplicationFactor()).isEqualTo(1);
+ assertThat(replicationFactor.getFullReplicas("datacenter1")).isEqualTo(2);
+ assertThat(replicationFactor.getTransientReplicas("datacenter1")).isEqualTo(1);
+ }
+
+ @Test
+ public void testTransientReplicasMultipleDatacenters()
+ {
+ ReplicationFactor replicationFactor = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "3/1",
+ "datacenter2", "3/1"));
+ assertThat(replicationFactor.getTotalReplicationFactor()).isEqualTo(6);
+ assertThat(replicationFactor.getFullReplicationFactor()).isEqualTo(4);
+ assertThat(replicationFactor.getTransientReplicationFactor()).isEqualTo(2);
+ }
+
+ @Test
+ public void testMixedTransientAndFullDatacenters()
+ {
+ ReplicationFactor replicationFactor = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "3/1",
+ "datacenter2", "3"));
+ assertThat(replicationFactor.getTotalReplicationFactor()).isEqualTo(6);
+ assertThat(replicationFactor.getFullReplicationFactor()).isEqualTo(5);
+ assertThat(replicationFactor.getTransientReplicas("datacenter1")).isEqualTo(1);
+ assertThat(replicationFactor.getTransientReplicas("datacenter2")).isEqualTo(0);
+ assertThat(replicationFactor.getFullReplicas("datacenter2")).isEqualTo(3);
+ // datacenter2 has no transient replicas, so it must be absent rather than mapped to zero
+ assertThat(replicationFactor.getTransientOptions()).containsOnlyKeys("datacenter1");
+ }
+
+ @Test
+ public void testTransientReplicasSimpleStrategy()
+ {
+ ReplicationFactor replicationFactor = new ReplicationFactor(ImmutableMap.of(
+ "class", "SimpleStrategy",
+ "replication_factor", "3/1"));
+ assertThat(replicationFactor.getReplicationStrategy())
+ .isEqualTo(ReplicationFactor.ReplicationStrategy.SimpleStrategy);
+ assertThat(replicationFactor.getTotalReplicationFactor()).isEqualTo(3);
+ assertThat(replicationFactor.getFullReplicationFactor()).isEqualTo(2);
+ }
+
+ @Test
+ public void testTransientReplicasWithWhitespace()
+ {
+ ReplicationFactor replicationFactor = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", " 3 / 1 "));
+ assertThat(replicationFactor.getTotalReplicationFactor()).isEqualTo(3);
+ assertThat(replicationFactor.getFullReplicationFactor()).isEqualTo(2);
+ }
+
+ @Test
+ public void testTransientEqualToTotalIsRejected()
+ {
+ // Cassandra requires at least one full replica, so 3/3 is invalid
+ ReplicationFactor replicationFactor = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "3/3"));
+ assertThat(replicationFactor.getOptions()).doesNotContainKey("datacenter1");
+ }
+
+ @Test
+ public void testMalformedTransientValuesAreSkipped()
+ {
+ for (String malformed : new String[]{ "3/", "/1", "3/1/1", "3/x", "x/1", "3/-1", "" })
+ {
+ ReplicationFactor replicationFactor = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", malformed));
+ assertThat(replicationFactor.getOptions())
+ .as("malformed value '%s' should not produce a replication factor entry", malformed)
+ .doesNotContainKey("datacenter1");
+ }
+ }
+
+ @Test
+ public void testGetFullReplicasUnknownDatacenter()
+ {
+ ReplicationFactor replicationFactor = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "3/1"));
+ assertThatThrownBy(() -> replicationFactor.getFullReplicas("nosuchdc"))
+ .isInstanceOf(IllegalArgumentException.class);
+ }
+
+ @Test
+ public void testTransientOptionsForUnknownDatacenterRejected()
+ {
+ assertThatThrownBy(() -> new ReplicationFactor(
+ ReplicationFactor.ReplicationStrategy.NetworkTopologyStrategy,
+ ImmutableMap.of("datacenter1", 3),
+ ImmutableMap.of("datacenter2", 1)))
+ .isInstanceOf(IllegalArgumentException.class);
+ }
+
+ @Test
+ public void testEqualityConsidersTransientReplicas()
+ {
+ ReplicationFactor full = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "3"));
+ ReplicationFactor withTransient = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "3/1"));
+ assertThat(full).isNotEqualTo(withTransient);
+ assertThat(full.hashCode()).isNotEqualTo(withTransient.hashCode());
+ }
+
+ @Test
+ public void testNegativeReplicationFactorIsRejected()
+ {
+ ReplicationFactor replicationFactor = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "-3"));
+ assertThat(replicationFactor.getOptions()).doesNotContainKey("datacenter1");
Review Comment:
Done, thanks!
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For additional commands, e-mail: commits-help@cassandra.apache.org
Re: [PR] CASSANALYTICS-194: Parse / replication factor fo… [cassandra-analytics]
Posted by "mansikhara (via GitHub)" <gi...@apache.org>.
mansikhara commented on code in PR #238:
URL: https://github.com/apache/cassandra-analytics/pull/238#discussion_r4020079134
##########
cassandra-analytics-common/src/main/java/org/apache/cassandra/spark/data/ReplicationFactor.java:
##########
@@ -108,11 +114,44 @@ public static ReplicationFactor simpleStrategy(int rf)
private final ReplicationStrategy replicationStrategy;
@NotNull
private final Map<String, Integer> options;
+ /**
+ * Per-datacenter count of transient (witness) replicas, parsed from the {@code <replicas>/<transient>} form.
+ * A datacenter absent from this map has no transient replicas. Always empty for untracked keyspaces using the
+ * plain {@code <replicas>} form, which keeps behaviour identical for those keyspaces.
+ */
+ @NotNull
+ private final Map<String, Integer> transientOptions;
Review Comment:
Agreed and done, thanks!
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For additional commands, e-mail: commits-help@cassandra.apache.org
Re: [PR] CASSANALYTICS-194: Parse / replication factor fo… [cassandra-analytics]
Posted by "sarankk (via GitHub)" <gi...@apache.org>.
sarankk commented on code in PR #238:
URL: https://github.com/apache/cassandra-analytics/pull/238#discussion_r4107616006
##########
cassandra-six-zero-types/src/main/java/org/apache/cassandra/bridge/SchemaUpdater.java:
##########
@@ -72,6 +72,27 @@ public static void openKeyspaceInstances()
ClusterMetadata.current().schema.initializeKeyspaceInstances(DistributedSchema.empty(), false);
Review Comment:
Should we avoid initializing all keyspaces altogether? the only other place where this seems to be used is CDC code path. There too we have the keyspace information `removeTables(SchemaProvider schema, KeyspaceMetadata keyspaceMetadata)`
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For additional commands, e-mail: commits-help@cassandra.apache.org
Re: [PR] CASSANALYTICS-194: Parse / replication factor fo… [cassandra-analytics]
Posted by "mansikhara (via GitHub)" <gi...@apache.org>.
mansikhara commented on code in PR #238:
URL: https://github.com/apache/cassandra-analytics/pull/238#discussion_r4020105208
##########
cassandra-analytics-core/src/test/java/org/apache/cassandra/spark/utils/CqlUtilsTest.java:
##########
@@ -142,6 +142,84 @@ public void testExtractReplicationFactor(CassandraBridge bridge)
assertThat(systemSchemaRf.getOptions()).isEqualTo(ImmutableMap.of());
}
+ @Test
+ public void testExtractReplicationFactorWithWitnessReplicas()
+ {
+ // Witness-enabled keyspace as created by Cassandra's WitnessAlwaysReadsFullReplicaTest on the
+ // cep-45-mutation-tracking branch: the <replicas>/<transient> form plus replication_type = 'tracked'
+ String schema = "CREATE KEYSPACE witnessks WITH REPLICATION = {'class': 'NetworkTopologyStrategy', "
+ + "'datacenter1': '3/1', 'datacenter2': '3/1'} AND replication_type = 'tracked' "
Review Comment:
You are right, I confirmed it. Removed it from these fixtures since it is irrelevant to replication factor parsing anyway.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For additional commands, e-mail: commits-help@cassandra.apache.org
Re: [PR] CASSANALYTICS-194: Parse / replication factor fo… [cassandra-analytics]
Posted by "mansikhara (via GitHub)" <gi...@apache.org>.
mansikhara commented on code in PR #238:
URL: https://github.com/apache/cassandra-analytics/pull/238#discussion_r4032254935
##########
cassandra-analytics-core/src/test/java/org/apache/cassandra/spark/utils/CqlUtilsTest.java:
##########
@@ -142,6 +142,83 @@ public void testExtractReplicationFactor(CassandraBridge bridge)
assertThat(systemSchemaRf.getOptions()).isEqualTo(ImmutableMap.of());
}
+ @Test
+ public void testExtractReplicationFactorWithWitnessReplicas()
+ {
+ // The <replicas>/<transient> form, as Cassandra's WitnessAlwaysReadsFullReplicaTest creates it on the
+ // cep-45-mutation-tracking branch. replication_type is deliberately omitted: Sidecar builds its schema
+ // response from the driver's exportAsString(), which does not emit that property, and it is irrelevant to
+ // replication factor parsing in any case. extractReplicationType is covered separately.
Review Comment:
Done!
##########
cassandra-analytics-common/src/main/java/org/apache/cassandra/spark/data/ReplicationFactor.java:
##########
@@ -106,62 +110,204 @@ public static ReplicationFactor simpleStrategy(int rf)
@NotNull
private final ReplicationStrategy replicationStrategy;
+ /**
+ * Per-datacenter replica counts. Holding the total and the transient count together, rather than in two
+ * parallel maps, means the two cannot drift apart.
+ */
@NotNull
- private final Map<String, Integer> options;
+ private final Map<String, ReplicaCounts> replication;
+ /**
+ * Parses a raw replication map. A value that cannot be parsed, or that Cassandra itself would reject, raises
+ * {@link IllegalArgumentException} naming the offending datacenter: a partial replication factor is not usable
+ * and reporting it here avoids a misleading failure later, such as "DC not found in replication factor".
+ *
+ * @param options the raw replication map, including the {@code class} entry
+ * @throws IllegalArgumentException when any replication value cannot be parsed
+ */
public ReplicationFactor(@NotNull Map<String, String> options)
{
this.replicationStrategy = ReplicationFactor.ReplicationStrategy.getEnum(options.get("class"));
- this.options = new LinkedHashMap<>(options.size());
+ Map<String, ReplicaCounts> parsed = new LinkedHashMap<>(options.size());
for (Map.Entry<String, String> entry : options.entrySet())
{
if ("class".equals(entry.getKey()))
{
continue;
}
-
try
{
- this.options.put(entry.getKey(), Integer.parseInt(entry.getValue()));
+ parsed.put(entry.getKey(), ReplicaCounts.parse(entry.getValue()));
}
- catch (NumberFormatException exception)
+ catch (IllegalArgumentException exception)
{
- LOGGER.warn("Could not parse replication option: {} = {}", entry.getKey(), entry.getValue());
+ throw new IllegalArgumentException(String.format("Could not parse replication option: %s = %s",
+ entry.getKey(), entry.getValue()), exception);
}
}
+ validateNotEmpty(this.replicationStrategy, parsed, options);
+ this.replication = Collections.unmodifiableMap(parsed);
}
public ReplicationFactor(@NotNull ReplicationStrategy replicationStrategy, @NotNull Map<String, Integer> options)
{
- this.replicationStrategy = replicationStrategy;
- this.options = new LinkedHashMap<>(options.size());
-
- if (!replicationStrategy.equals(ReplicationStrategy.LocalStrategy) && options.isEmpty())
- {
- throw new RuntimeException(String.format("Could not find replication info in schema map: %s.", options));
- }
+ this(replicationStrategy, options, Collections.emptyMap());
+ }
+ public ReplicationFactor(@NotNull ReplicationStrategy replicationStrategy,
+ @NotNull Map<String, Integer> options,
+ @NotNull Map<String, Integer> transientOptions)
+ {
+ this.replicationStrategy = replicationStrategy;
+ Map<String, ReplicaCounts> merged = new LinkedHashMap<>(options.size());
for (Map.Entry<String, Integer> entry : options.entrySet())
{
if ("class".equals(entry.getKey()))
{
continue;
}
- this.options.put(entry.getKey(), entry.getValue());
+ int transientReplicas = transientOptions.getOrDefault(entry.getKey(), 0);
+ merged.put(entry.getKey(), ReplicaCounts.of(entry.getKey(), entry.getValue(), transientReplicas));
+ }
+ for (String datacenter : transientOptions.keySet())
+ {
+ if (!"class".equals(datacenter) && !merged.containsKey(datacenter)
+ && transientOptions.get(datacenter) != null && transientOptions.get(datacenter) != 0)
+ {
+ throw new IllegalArgumentException(String.format(
+ "Transient replicas specified for %s but it has no replication factor", datacenter));
+ }
+ }
+ validateNotEmpty(replicationStrategy, merged, options);
+ this.replication = Collections.unmodifiableMap(merged);
+ }
+
+ /**
+ * Canonical constructor. {@code validate} exists only for {@link #readResolve()}, which must not reject an
+ * instance that an earlier version was willing to create.
+ */
+ private ReplicationFactor(@NotNull ReplicationStrategy replicationStrategy,
+ @NotNull Map<String, ReplicaCounts> replication,
+ boolean validate)
+ {
+ this.replicationStrategy = replicationStrategy;
+ if (validate)
Review Comment:
Done!
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For additional commands, e-mail: commits-help@cassandra.apache.org
Re: [PR] CASSANALYTICS-194: Parse / replication factor fo… [cassandra-analytics]
Posted by "sarankk (via GitHub)" <gi...@apache.org>.
sarankk commented on code in PR #238:
URL: https://github.com/apache/cassandra-analytics/pull/238#discussion_r4107623057
##########
cassandra-six-zero-types/src/main/java/org/apache/cassandra/bridge/SchemaUpdater.java:
##########
@@ -72,6 +72,27 @@ public static void openKeyspaceInstances()
ClusterMetadata.current().schema.initializeKeyspaceInstances(DistributedSchema.empty(), false);
}
+ /**
+ * Creates the keyspace instance for one keyspace, leaving every other keyspace's instance untouched.
+ *
+ * <p>Prefer this to {@link #openKeyspaceInstances()} whenever the caller knows which keyspace is missing its
+ * instance. That method diffs against {@link DistributedSchema#empty()}, so every keyspace in the process looks
+ * newly created and all of them are rebuilt. Rebuilding a keyspace that already has an instance constructs its
Review Comment:
Nice find! since the code path exists in trunk, can you fix it in trunk first with a separate JIRA? also curious why trunk CI is not timing out with the issue
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For additional commands, e-mail: commits-help@cassandra.apache.org
Re: [PR] CASSANALYTICS-194: Parse / replication factor fo… [cassandra-analytics]
Posted by "mansikhara (via GitHub)" <gi...@apache.org>.
mansikhara commented on code in PR #238:
URL: https://github.com/apache/cassandra-analytics/pull/238#discussion_r4020096789
##########
cassandra-analytics-common/src/test/java/org/apache/cassandra/spark/data/ReplicationFactorTests.java:
##########
@@ -111,4 +118,296 @@ public void testEquality()
assertThat(replicationFactor1).isEqualTo(replicationFactor2);
assertThat(replicationFactor1.hashCode()).isEqualTo(replicationFactor2.hashCode());
}
+
+ // Transient / witness replicas: the <replicas>/<transient> form, reused by witness replicas under
+ // mutation tracking (CEP-45/CEP-46)
+
+ @Test
+ public void testNoTransientReplicasByDefault()
+ {
+ ReplicationFactor replicationFactor = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "3"));
+ assertThat(replicationFactor.hasTransientReplicas()).isFalse();
+ assertThat(replicationFactor.getTransientOptions()).isEmpty();
+ assertThat(replicationFactor.getTotalReplicationFactor()).isEqualTo(3);
+ assertThat(replicationFactor.getFullReplicationFactor()).isEqualTo(3);
+ assertThat(replicationFactor.getTransientReplicationFactor()).isEqualTo(0);
+ assertThat(replicationFactor.getFullReplicas("datacenter1")).isEqualTo(3);
+ assertThat(replicationFactor.getTransientReplicas("datacenter1")).isEqualTo(0);
+ }
+
+ @Test
+ public void testTransientReplicasSingleDatacenter()
+ {
+ ReplicationFactor replicationFactor = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "3/1"));
+ assertThat(replicationFactor.hasTransientReplicas()).isTrue();
+ // total keeps its original meaning: all replicas, witnesses included
+ assertThat(replicationFactor.getOptions().get("datacenter1")).isEqualTo(Integer.valueOf(3));
+ assertThat(replicationFactor.getTotalReplicationFactor()).isEqualTo(3);
+ assertThat(replicationFactor.getFullReplicationFactor()).isEqualTo(2);
+ assertThat(replicationFactor.getTransientReplicationFactor()).isEqualTo(1);
+ assertThat(replicationFactor.getFullReplicas("datacenter1")).isEqualTo(2);
+ assertThat(replicationFactor.getTransientReplicas("datacenter1")).isEqualTo(1);
+ }
+
+ @Test
+ public void testTransientReplicasMultipleDatacenters()
+ {
+ ReplicationFactor replicationFactor = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "3/1",
+ "datacenter2", "3/1"));
+ assertThat(replicationFactor.getTotalReplicationFactor()).isEqualTo(6);
+ assertThat(replicationFactor.getFullReplicationFactor()).isEqualTo(4);
+ assertThat(replicationFactor.getTransientReplicationFactor()).isEqualTo(2);
+ }
+
+ @Test
+ public void testMixedTransientAndFullDatacenters()
+ {
+ ReplicationFactor replicationFactor = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "3/1",
+ "datacenter2", "3"));
+ assertThat(replicationFactor.getTotalReplicationFactor()).isEqualTo(6);
+ assertThat(replicationFactor.getFullReplicationFactor()).isEqualTo(5);
+ assertThat(replicationFactor.getTransientReplicas("datacenter1")).isEqualTo(1);
+ assertThat(replicationFactor.getTransientReplicas("datacenter2")).isEqualTo(0);
+ assertThat(replicationFactor.getFullReplicas("datacenter2")).isEqualTo(3);
+ // datacenter2 has no transient replicas, so it must be absent rather than mapped to zero
+ assertThat(replicationFactor.getTransientOptions()).containsOnlyKeys("datacenter1");
+ }
+
+ @Test
+ public void testTransientReplicasSimpleStrategy()
+ {
+ ReplicationFactor replicationFactor = new ReplicationFactor(ImmutableMap.of(
+ "class", "SimpleStrategy",
+ "replication_factor", "3/1"));
+ assertThat(replicationFactor.getReplicationStrategy())
+ .isEqualTo(ReplicationFactor.ReplicationStrategy.SimpleStrategy);
+ assertThat(replicationFactor.getTotalReplicationFactor()).isEqualTo(3);
+ assertThat(replicationFactor.getFullReplicationFactor()).isEqualTo(2);
+ }
+
+ @Test
+ public void testTransientReplicasWithWhitespace()
+ {
+ ReplicationFactor replicationFactor = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", " 3 / 1 "));
+ assertThat(replicationFactor.getTotalReplicationFactor()).isEqualTo(3);
+ assertThat(replicationFactor.getFullReplicationFactor()).isEqualTo(2);
+ }
+
+ @Test
+ public void testTransientEqualToTotalIsRejected()
+ {
+ // Cassandra requires at least one full replica, so 3/3 is invalid
+ ReplicationFactor replicationFactor = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "3/3"));
+ assertThat(replicationFactor.getOptions()).doesNotContainKey("datacenter1");
Review Comment:
Great suggestions! Done.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For additional commands, e-mail: commits-help@cassandra.apache.org
Re: [PR] CASSANALYTICS-194: Parse / replication factor fo… [cassandra-analytics]
Posted by "mansikhara (via GitHub)" <gi...@apache.org>.
mansikhara commented on code in PR #238:
URL: https://github.com/apache/cassandra-analytics/pull/238#discussion_r4041083188
##########
cassandra-analytics-common/src/main/java/org/apache/cassandra/spark/data/ReplicationFactor.java:
##########
@@ -106,62 +110,209 @@ public static ReplicationFactor simpleStrategy(int rf)
@NotNull
private final ReplicationStrategy replicationStrategy;
+ /**
+ * Per-datacenter replica counts. Holding the total and the transient count together, rather than in two
+ * parallel maps, means the two cannot drift apart.
+ */
@NotNull
- private final Map<String, Integer> options;
+ private final Map<String, ReplicaCounts> replication;
+ /**
+ * Parses a raw replication map. A value that cannot be parsed, or that Cassandra itself would reject, raises
+ * {@link IllegalArgumentException} naming the offending datacenter: a partial replication factor is not usable
+ * and reporting it here avoids a misleading failure later, such as "DC not found in replication factor".
+ *
+ * @param options the raw replication map, including the {@code class} entry
+ * @throws IllegalArgumentException when any replication value cannot be parsed
+ */
public ReplicationFactor(@NotNull Map<String, String> options)
{
- this.replicationStrategy = ReplicationFactor.ReplicationStrategy.getEnum(options.get("class"));
- this.options = new LinkedHashMap<>(options.size());
- for (Map.Entry<String, String> entry : options.entrySet())
+ this(ReplicationStrategy.getEnum(options.get("class")), parse(options), options);
+ }
+
+ public ReplicationFactor(@NotNull ReplicationStrategy replicationStrategy, @NotNull Map<String, Integer> options)
+ {
+ this(replicationStrategy, options, Collections.emptyMap());
+ }
+
+ public ReplicationFactor(@NotNull ReplicationStrategy replicationStrategy,
+ @NotNull Map<String, Integer> options,
+ @NotNull Map<String, Integer> transientOptions)
+ {
+ this(replicationStrategy, merge(options, transientOptions), options);
+ }
+
+ /**
+ * Canonical constructor. Every other constructor resolves its input to per-datacenter counts and delegates here.
+ *
+ * @param replicationStrategy the replication strategy
+ * @param replication per-datacenter replica counts, already validated individually
+ * @param raw the caller's original input, used only in the error message
+ */
+ private ReplicationFactor(@NotNull ReplicationStrategy replicationStrategy,
+ @NotNull Map<String, ReplicaCounts> replication,
+ @NotNull Object raw)
+ {
+ // A strategy other than LocalStrategy with no datacenter entries is not usable
+ if (replicationStrategy != ReplicationStrategy.LocalStrategy && replication.isEmpty())
{
- if ("class".equals(entry.getKey()))
+ throw new IllegalArgumentException("Could not find replication info in schema map: " + raw);
+ }
+ this.replicationStrategy = replicationStrategy;
+ this.replication = Collections.unmodifiableMap(new LinkedHashMap<>(replication));
+ }
+
+ /**
+ * Resolves raw string values, e.g. {@code "3"} or {@code "3/1"}, to per-datacenter counts.
+ */
+ private static Map<String, ReplicaCounts> parse(@NotNull Map<String, String> options)
+ {
+ Map<String, ReplicaCounts> parsed = new LinkedHashMap<>(options.size());
+ options.forEach((datacenter, value) -> {
+ if ("class".equals(datacenter))
{
- continue;
+ return;
}
-
try
{
- this.options.put(entry.getKey(), Integer.parseInt(entry.getValue()));
+ parsed.put(datacenter, ReplicaCounts.parse(value));
}
- catch (NumberFormatException exception)
+ catch (IllegalArgumentException exception)
{
- LOGGER.warn("Could not parse replication option: {} = {}", entry.getKey(), entry.getValue());
+ throw new IllegalArgumentException(String.format("Could not parse replication option: %s = %s",
+ datacenter, value), exception);
}
- }
+ });
+ return parsed;
}
- public ReplicationFactor(@NotNull ReplicationStrategy replicationStrategy, @NotNull Map<String, Integer> options)
+ /**
+ * Resolves separate total and transient maps to per-datacenter counts, rejecting a transient entry for a
+ * datacenter that has no replication factor.
+ */
+ private static Map<String, ReplicaCounts> merge(@NotNull Map<String, Integer> options,
+ @NotNull Map<String, Integer> transientOptions)
{
- this.replicationStrategy = replicationStrategy;
- this.options = new LinkedHashMap<>(options.size());
+ Map<String, ReplicaCounts> merged = new LinkedHashMap<>(options.size());
+ options.forEach((datacenter, allReplicas) -> {
+ if (!"class".equals(datacenter))
+ {
+ merged.put(datacenter,
+ ReplicaCounts.of(datacenter, allReplicas, transientOptions.getOrDefault(datacenter, 0)));
+ }
+ });
+ transientOptions.forEach((datacenter, transientReplicas) -> {
+ if (!"class".equals(datacenter) && transientReplicas != null && transientReplicas != 0
+ && !merged.containsKey(datacenter))
+ {
+ throw new IllegalArgumentException(String.format(
+ "Transient replicas specified for %s but it has no replication factor", datacenter));
+ }
+ });
+ return merged;
+ }
- if (!replicationStrategy.equals(ReplicationStrategy.LocalStrategy) && options.isEmpty())
- {
- throw new RuntimeException(String.format("Could not find replication info in schema map: %s.", options));
- }
+ /**
+ * @return the total number of replicas across all datacenters, including transient (witness) replicas.
+ * Semantics are unchanged from before transient replica support was added.
+ */
+ public Integer getTotalReplicationFactor()
+ {
+ return replication.values().stream().mapToInt(ReplicaCounts::allReplicas).sum();
+ }
- for (Map.Entry<String, Integer> entry : options.entrySet())
+ /**
+ * @return the number of replicas across all datacenters that hold the full data set, i.e. the total
+ * replication factor minus transient (witness) replicas
+ */
+ public Integer getFullReplicationFactor()
+ {
+ return replication.values().stream().mapToInt(ReplicaCounts::fullReplicas).sum();
+ }
+
+ /**
+ * @return the number of transient (witness) replicas across all datacenters, {@code 0} when none are configured
+ */
+ public Integer getTransientReplicationFactor()
+ {
+ return replication.values().stream().mapToInt(ReplicaCounts::transientReplicas).sum();
+ }
+
+ /**
+ * @return {@code true} if any datacenter is configured with transient (witness) replicas
+ */
+ public boolean hasTransientReplicas()
+ {
+ return replication.values().stream().anyMatch(counts -> counts.transientReplicas() > 0);
+ }
+
+ /**
+ * @param datacenter the datacenter to look up
+ * @return the number of transient (witness) replicas in {@code datacenter}, {@code 0} when none are configured
+ */
+ public int getTransientReplicas(@NotNull String datacenter)
+ {
+ ReplicaCounts counts = replication.get(datacenter);
+ return counts == null ? 0 : counts.transientReplicas();
+ }
+
+ /**
+ * @param datacenter the datacenter to look up
+ * @return the number of replicas in {@code datacenter} holding the full data set
+ * @throws IllegalArgumentException when {@code datacenter} has no replication factor
+ */
+ public int getFullReplicas(@NotNull String datacenter)
+ {
+ return counts(datacenter).fullReplicas();
+ }
+
+ private ReplicaCounts counts(@NotNull String datacenter)
+ {
+ ReplicaCounts counts = replication.get(datacenter);
+ if (counts == null)
{
- if ("class".equals(entry.getKey()))
- {
- continue;
- }
- this.options.put(entry.getKey(), entry.getValue());
+ throw new IllegalArgumentException(String.format("Datacenter %s not found in replication factor %s",
Review Comment:
No reason, was an oversight, thanks for catching it :)
##########
cassandra-analytics-common/src/main/java/org/apache/cassandra/spark/data/ReplicationFactor.java:
##########
@@ -106,62 +110,209 @@ public static ReplicationFactor simpleStrategy(int rf)
@NotNull
private final ReplicationStrategy replicationStrategy;
+ /**
+ * Per-datacenter replica counts. Holding the total and the transient count together, rather than in two
+ * parallel maps, means the two cannot drift apart.
+ */
@NotNull
- private final Map<String, Integer> options;
+ private final Map<String, ReplicaCounts> replication;
+ /**
+ * Parses a raw replication map. A value that cannot be parsed, or that Cassandra itself would reject, raises
+ * {@link IllegalArgumentException} naming the offending datacenter: a partial replication factor is not usable
+ * and reporting it here avoids a misleading failure later, such as "DC not found in replication factor".
+ *
+ * @param options the raw replication map, including the {@code class} entry
+ * @throws IllegalArgumentException when any replication value cannot be parsed
+ */
public ReplicationFactor(@NotNull Map<String, String> options)
{
- this.replicationStrategy = ReplicationFactor.ReplicationStrategy.getEnum(options.get("class"));
- this.options = new LinkedHashMap<>(options.size());
- for (Map.Entry<String, String> entry : options.entrySet())
+ this(ReplicationStrategy.getEnum(options.get("class")), parse(options), options);
+ }
+
+ public ReplicationFactor(@NotNull ReplicationStrategy replicationStrategy, @NotNull Map<String, Integer> options)
+ {
+ this(replicationStrategy, options, Collections.emptyMap());
+ }
+
+ public ReplicationFactor(@NotNull ReplicationStrategy replicationStrategy,
+ @NotNull Map<String, Integer> options,
+ @NotNull Map<String, Integer> transientOptions)
+ {
+ this(replicationStrategy, merge(options, transientOptions), options);
+ }
+
+ /**
+ * Canonical constructor. Every other constructor resolves its input to per-datacenter counts and delegates here.
+ *
+ * @param replicationStrategy the replication strategy
+ * @param replication per-datacenter replica counts, already validated individually
+ * @param raw the caller's original input, used only in the error message
+ */
+ private ReplicationFactor(@NotNull ReplicationStrategy replicationStrategy,
+ @NotNull Map<String, ReplicaCounts> replication,
+ @NotNull Object raw)
+ {
+ // A strategy other than LocalStrategy with no datacenter entries is not usable
+ if (replicationStrategy != ReplicationStrategy.LocalStrategy && replication.isEmpty())
{
- if ("class".equals(entry.getKey()))
+ throw new IllegalArgumentException("Could not find replication info in schema map: " + raw);
+ }
+ this.replicationStrategy = replicationStrategy;
+ this.replication = Collections.unmodifiableMap(new LinkedHashMap<>(replication));
+ }
+
+ /**
+ * Resolves raw string values, e.g. {@code "3"} or {@code "3/1"}, to per-datacenter counts.
+ */
+ private static Map<String, ReplicaCounts> parse(@NotNull Map<String, String> options)
+ {
+ Map<String, ReplicaCounts> parsed = new LinkedHashMap<>(options.size());
+ options.forEach((datacenter, value) -> {
+ if ("class".equals(datacenter))
{
- continue;
+ return;
}
-
try
{
- this.options.put(entry.getKey(), Integer.parseInt(entry.getValue()));
+ parsed.put(datacenter, ReplicaCounts.parse(value));
}
- catch (NumberFormatException exception)
+ catch (IllegalArgumentException exception)
{
- LOGGER.warn("Could not parse replication option: {} = {}", entry.getKey(), entry.getValue());
+ throw new IllegalArgumentException(String.format("Could not parse replication option: %s = %s",
+ datacenter, value), exception);
}
- }
+ });
+ return parsed;
}
- public ReplicationFactor(@NotNull ReplicationStrategy replicationStrategy, @NotNull Map<String, Integer> options)
+ /**
+ * Resolves separate total and transient maps to per-datacenter counts, rejecting a transient entry for a
+ * datacenter that has no replication factor.
+ */
+ private static Map<String, ReplicaCounts> merge(@NotNull Map<String, Integer> options,
+ @NotNull Map<String, Integer> transientOptions)
{
- this.replicationStrategy = replicationStrategy;
- this.options = new LinkedHashMap<>(options.size());
+ Map<String, ReplicaCounts> merged = new LinkedHashMap<>(options.size());
+ options.forEach((datacenter, allReplicas) -> {
+ if (!"class".equals(datacenter))
+ {
+ merged.put(datacenter,
+ ReplicaCounts.of(datacenter, allReplicas, transientOptions.getOrDefault(datacenter, 0)));
+ }
+ });
+ transientOptions.forEach((datacenter, transientReplicas) -> {
+ if (!"class".equals(datacenter) && transientReplicas != null && transientReplicas != 0
+ && !merged.containsKey(datacenter))
+ {
+ throw new IllegalArgumentException(String.format(
+ "Transient replicas specified for %s but it has no replication factor", datacenter));
+ }
+ });
+ return merged;
+ }
- if (!replicationStrategy.equals(ReplicationStrategy.LocalStrategy) && options.isEmpty())
- {
- throw new RuntimeException(String.format("Could not find replication info in schema map: %s.", options));
- }
+ /**
+ * @return the total number of replicas across all datacenters, including transient (witness) replicas.
+ * Semantics are unchanged from before transient replica support was added.
+ */
+ public Integer getTotalReplicationFactor()
+ {
+ return replication.values().stream().mapToInt(ReplicaCounts::allReplicas).sum();
+ }
- for (Map.Entry<String, Integer> entry : options.entrySet())
+ /**
+ * @return the number of replicas across all datacenters that hold the full data set, i.e. the total
+ * replication factor minus transient (witness) replicas
+ */
+ public Integer getFullReplicationFactor()
+ {
+ return replication.values().stream().mapToInt(ReplicaCounts::fullReplicas).sum();
+ }
+
+ /**
+ * @return the number of transient (witness) replicas across all datacenters, {@code 0} when none are configured
+ */
+ public Integer getTransientReplicationFactor()
+ {
+ return replication.values().stream().mapToInt(ReplicaCounts::transientReplicas).sum();
+ }
+
+ /**
+ * @return {@code true} if any datacenter is configured with transient (witness) replicas
+ */
+ public boolean hasTransientReplicas()
+ {
+ return replication.values().stream().anyMatch(counts -> counts.transientReplicas() > 0);
+ }
+
+ /**
+ * @param datacenter the datacenter to look up
+ * @return the number of transient (witness) replicas in {@code datacenter}, {@code 0} when none are configured
+ */
+ public int getTransientReplicas(@NotNull String datacenter)
+ {
+ ReplicaCounts counts = replication.get(datacenter);
+ return counts == null ? 0 : counts.transientReplicas();
+ }
+
+ /**
+ * @param datacenter the datacenter to look up
+ * @return the number of replicas in {@code datacenter} holding the full data set
+ * @throws IllegalArgumentException when {@code datacenter} has no replication factor
+ */
+ public int getFullReplicas(@NotNull String datacenter)
+ {
+ return counts(datacenter).fullReplicas();
+ }
+
+ private ReplicaCounts counts(@NotNull String datacenter)
+ {
+ ReplicaCounts counts = replication.get(datacenter);
+ if (counts == null)
{
- if ("class".equals(entry.getKey()))
- {
- continue;
- }
- this.options.put(entry.getKey(), entry.getValue());
+ throw new IllegalArgumentException(String.format("Datacenter %s not found in replication factor %s",
+ datacenter, replication.keySet()));
}
+ return counts;
}
- public Integer getTotalReplicationFactor()
+ /**
+ * @return per-datacenter replica counts, unmodifiable
+ */
+ @NotNull
+ public Map<String, ReplicaCounts> getReplication()
{
- return options.values().stream()
- .mapToInt(Integer::intValue)
- .sum();
+ return replication;
}
+ /**
+ * @return per-datacenter total replica counts, including transient (witness) replicas. Unmodifiable, and derived
+ * from {@link #getReplication()}.
+ */
@NotNull
public Map<String, Integer> getOptions()
{
- return options;
+ Map<String, Integer> options = new LinkedHashMap<>(replication.size());
Review Comment:
Done!
##########
cassandra-analytics-common/src/main/java/org/apache/cassandra/spark/data/ReplicationFactor.java:
##########
@@ -106,62 +110,209 @@ public static ReplicationFactor simpleStrategy(int rf)
@NotNull
private final ReplicationStrategy replicationStrategy;
+ /**
+ * Per-datacenter replica counts. Holding the total and the transient count together, rather than in two
+ * parallel maps, means the two cannot drift apart.
+ */
@NotNull
- private final Map<String, Integer> options;
+ private final Map<String, ReplicaCounts> replication;
+ /**
+ * Parses a raw replication map. A value that cannot be parsed, or that Cassandra itself would reject, raises
+ * {@link IllegalArgumentException} naming the offending datacenter: a partial replication factor is not usable
+ * and reporting it here avoids a misleading failure later, such as "DC not found in replication factor".
+ *
+ * @param options the raw replication map, including the {@code class} entry
+ * @throws IllegalArgumentException when any replication value cannot be parsed
+ */
public ReplicationFactor(@NotNull Map<String, String> options)
{
- this.replicationStrategy = ReplicationFactor.ReplicationStrategy.getEnum(options.get("class"));
- this.options = new LinkedHashMap<>(options.size());
- for (Map.Entry<String, String> entry : options.entrySet())
+ this(ReplicationStrategy.getEnum(options.get("class")), parse(options), options);
+ }
+
+ public ReplicationFactor(@NotNull ReplicationStrategy replicationStrategy, @NotNull Map<String, Integer> options)
+ {
+ this(replicationStrategy, options, Collections.emptyMap());
+ }
+
+ public ReplicationFactor(@NotNull ReplicationStrategy replicationStrategy,
+ @NotNull Map<String, Integer> options,
+ @NotNull Map<String, Integer> transientOptions)
+ {
+ this(replicationStrategy, merge(options, transientOptions), options);
+ }
+
+ /**
+ * Canonical constructor. Every other constructor resolves its input to per-datacenter counts and delegates here.
+ *
+ * @param replicationStrategy the replication strategy
+ * @param replication per-datacenter replica counts, already validated individually
+ * @param raw the caller's original input, used only in the error message
+ */
+ private ReplicationFactor(@NotNull ReplicationStrategy replicationStrategy,
+ @NotNull Map<String, ReplicaCounts> replication,
+ @NotNull Object raw)
+ {
+ // A strategy other than LocalStrategy with no datacenter entries is not usable
+ if (replicationStrategy != ReplicationStrategy.LocalStrategy && replication.isEmpty())
{
- if ("class".equals(entry.getKey()))
+ throw new IllegalArgumentException("Could not find replication info in schema map: " + raw);
+ }
+ this.replicationStrategy = replicationStrategy;
+ this.replication = Collections.unmodifiableMap(new LinkedHashMap<>(replication));
+ }
+
+ /**
+ * Resolves raw string values, e.g. {@code "3"} or {@code "3/1"}, to per-datacenter counts.
+ */
+ private static Map<String, ReplicaCounts> parse(@NotNull Map<String, String> options)
+ {
+ Map<String, ReplicaCounts> parsed = new LinkedHashMap<>(options.size());
+ options.forEach((datacenter, value) -> {
+ if ("class".equals(datacenter))
{
- continue;
+ return;
}
-
try
{
- this.options.put(entry.getKey(), Integer.parseInt(entry.getValue()));
+ parsed.put(datacenter, ReplicaCounts.parse(value));
}
- catch (NumberFormatException exception)
+ catch (IllegalArgumentException exception)
{
- LOGGER.warn("Could not parse replication option: {} = {}", entry.getKey(), entry.getValue());
+ throw new IllegalArgumentException(String.format("Could not parse replication option: %s = %s",
+ datacenter, value), exception);
}
- }
+ });
+ return parsed;
}
- public ReplicationFactor(@NotNull ReplicationStrategy replicationStrategy, @NotNull Map<String, Integer> options)
+ /**
+ * Resolves separate total and transient maps to per-datacenter counts, rejecting a transient entry for a
+ * datacenter that has no replication factor.
+ */
+ private static Map<String, ReplicaCounts> merge(@NotNull Map<String, Integer> options,
+ @NotNull Map<String, Integer> transientOptions)
{
- this.replicationStrategy = replicationStrategy;
- this.options = new LinkedHashMap<>(options.size());
+ Map<String, ReplicaCounts> merged = new LinkedHashMap<>(options.size());
+ options.forEach((datacenter, allReplicas) -> {
+ if (!"class".equals(datacenter))
+ {
+ merged.put(datacenter,
+ ReplicaCounts.of(datacenter, allReplicas, transientOptions.getOrDefault(datacenter, 0)));
+ }
+ });
+ transientOptions.forEach((datacenter, transientReplicas) -> {
+ if (!"class".equals(datacenter) && transientReplicas != null && transientReplicas != 0
+ && !merged.containsKey(datacenter))
+ {
+ throw new IllegalArgumentException(String.format(
+ "Transient replicas specified for %s but it has no replication factor", datacenter));
+ }
+ });
+ return merged;
+ }
- if (!replicationStrategy.equals(ReplicationStrategy.LocalStrategy) && options.isEmpty())
- {
- throw new RuntimeException(String.format("Could not find replication info in schema map: %s.", options));
- }
+ /**
+ * @return the total number of replicas across all datacenters, including transient (witness) replicas.
+ * Semantics are unchanged from before transient replica support was added.
+ */
+ public Integer getTotalReplicationFactor()
+ {
+ return replication.values().stream().mapToInt(ReplicaCounts::allReplicas).sum();
+ }
- for (Map.Entry<String, Integer> entry : options.entrySet())
+ /**
+ * @return the number of replicas across all datacenters that hold the full data set, i.e. the total
+ * replication factor minus transient (witness) replicas
+ */
+ public Integer getFullReplicationFactor()
+ {
+ return replication.values().stream().mapToInt(ReplicaCounts::fullReplicas).sum();
+ }
+
+ /**
+ * @return the number of transient (witness) replicas across all datacenters, {@code 0} when none are configured
+ */
+ public Integer getTransientReplicationFactor()
+ {
+ return replication.values().stream().mapToInt(ReplicaCounts::transientReplicas).sum();
+ }
+
+ /**
+ * @return {@code true} if any datacenter is configured with transient (witness) replicas
+ */
+ public boolean hasTransientReplicas()
+ {
+ return replication.values().stream().anyMatch(counts -> counts.transientReplicas() > 0);
+ }
+
+ /**
+ * @param datacenter the datacenter to look up
+ * @return the number of transient (witness) replicas in {@code datacenter}, {@code 0} when none are configured
+ */
+ public int getTransientReplicas(@NotNull String datacenter)
+ {
+ ReplicaCounts counts = replication.get(datacenter);
+ return counts == null ? 0 : counts.transientReplicas();
+ }
+
+ /**
+ * @param datacenter the datacenter to look up
+ * @return the number of replicas in {@code datacenter} holding the full data set
+ * @throws IllegalArgumentException when {@code datacenter} has no replication factor
+ */
+ public int getFullReplicas(@NotNull String datacenter)
+ {
+ return counts(datacenter).fullReplicas();
+ }
+
+ private ReplicaCounts counts(@NotNull String datacenter)
+ {
+ ReplicaCounts counts = replication.get(datacenter);
+ if (counts == null)
{
- if ("class".equals(entry.getKey()))
- {
- continue;
- }
- this.options.put(entry.getKey(), entry.getValue());
+ throw new IllegalArgumentException(String.format("Datacenter %s not found in replication factor %s",
+ datacenter, replication.keySet()));
}
+ return counts;
}
- public Integer getTotalReplicationFactor()
+ /**
+ * @return per-datacenter replica counts, unmodifiable
+ */
+ @NotNull
+ public Map<String, ReplicaCounts> getReplication()
{
- return options.values().stream()
- .mapToInt(Integer::intValue)
- .sum();
+ return replication;
}
+ /**
+ * @return per-datacenter total replica counts, including transient (witness) replicas. Unmodifiable, and derived
+ * from {@link #getReplication()}.
+ */
@NotNull
public Map<String, Integer> getOptions()
{
- return options;
+ Map<String, Integer> options = new LinkedHashMap<>(replication.size());
+ replication.forEach((datacenter, counts) -> options.put(datacenter, counts.allReplicas()));
+ return Collections.unmodifiableMap(options);
+ }
+
+ /**
+ * @return per-datacenter transient (witness) replica counts, unmodifiable. Datacenters without transient
+ * replicas are absent.
+ */
+ @NotNull
+ public Map<String, Integer> getTransientOptions()
+ {
+ Map<String, Integer> transientOptions = new LinkedHashMap<>();
Review Comment:
Done!
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For additional commands, e-mail: commits-help@cassandra.apache.org
Re: [PR] CASSANALYTICS-194: Parse / replication factor fo… [cassandra-analytics]
Posted by "mansikhara (via GitHub)" <gi...@apache.org>.
mansikhara commented on code in PR #238:
URL: https://github.com/apache/cassandra-analytics/pull/238#discussion_r4086134291
##########
cassandra-analytics-common/src/main/java/org/apache/cassandra/spark/data/ReplicationFactor.java:
##########
@@ -188,13 +359,173 @@ public boolean equals(Object other)
ReplicationFactor that = (ReplicationFactor) other;
return this.replicationStrategy == that.replicationStrategy
- && java.util.Objects.equals(this.options, that.options);
+ && Objects.equals(this.replication, that.replication);
}
@Override
public int hashCode()
{
- return Objects.hash(replicationStrategy, options);
+ return Objects.hash(replicationStrategy, replication);
+ }
+
+ /**
+ * {@link #serialVersionUID} is pinned, so an instance serialized before the per-datacenter counts were combined
+ * deserializes with a {@code null} {@code replication}. Only reachable under driver/executor version skew, which
+ * is not a supported configuration, so this reports the mismatch rather than silently losing the counts.
+ *
+ * @return this instance
+ * @throws InvalidObjectException when deserialized from an incompatible older form
+ */
+ private Object readResolve() throws InvalidObjectException
+ {
+ if (replication == null)
+ {
+ throw new InvalidObjectException(
+ "ReplicationFactor was serialized by an incompatible version: per-datacenter replica counts are absent. "
+ + "Driver and executors must run the same version.");
+ }
+ // Rebuild through the canonical constructor so the derived fields, which are transient, are populated
+ return new ReplicationFactor(replicationStrategy, replication, replication);
+ }
+
+ /**
+ * Replica counts for a single datacenter. Cassandra accepts either {@code <replicas>} or
+ * {@code <replicas>/<transient>}; transient replication predates mutation tracking, and witness replicas
+ * (CEP-46) reuse the same form. See {@code org.apache.cassandra.locator.ReplicationFactor} in Cassandra.
+ */
+ public static final class ReplicaCounts implements Serializable
+ {
+ private static final long serialVersionUID = 2026091500000000001L;
+ private static final String TRANSIENT_SEPARATOR = "/";
+
+ private final int allReplicas;
+ private final int transientReplicas;
+
+ private ReplicaCounts(int allReplicas, int transientReplicas)
+ {
+ this.allReplicas = allReplicas;
+ this.transientReplicas = transientReplicas;
+ }
+
+ /**
+ * @param datacenter datacenter name, used only in error messages, may be {@code null}
+ * @param allReplicas total replicas
+ * @param transientReplicas transient (witness) replicas
+ * @return validated counts
+ * @throws IllegalArgumentException when the counts are inconsistent
+ */
+ public static ReplicaCounts of(String datacenter, int allReplicas, int transientReplicas)
+ {
+ validate(datacenter, allReplicas, transientReplicas);
+ return new ReplicaCounts(allReplicas, transientReplicas);
+ }
+
+ /**
+ * @return total replicas, including transient (witness) replicas
+ */
+ public int allReplicas()
+ {
+ return allReplicas;
+ }
+
+ /**
+ * @return replicas holding the full data set
+ */
+ public int fullReplicas()
+ {
+ return allReplicas - transientReplicas;
+ }
+
+ /**
+ * @return transient (witness) replicas, {@code 0} when none are configured
+ */
+ public int transientReplicas()
+ {
+ return transientReplicas;
+ }
+
+ /**
+ * @param value the raw replication value, e.g. {@code "3"} or {@code "3/1"}
+ * @return the parsed replica counts
+ * @throws NumberFormatException when either component is not an integer
+ * @throws IllegalArgumentException when the value is malformed or the counts are inconsistent
+ */
+ static ReplicaCounts parse(@NotNull String value)
+ {
+ String trimmed = value.trim();
+ int separator = trimmed.indexOf(TRANSIENT_SEPARATOR);
+ if (separator < 0)
+ {
+ return of(null, Integer.parseInt(trimmed), 0);
+ }
+
+ if (trimmed.indexOf(TRANSIENT_SEPARATOR, separator + 1) >= 0)
+ {
+ throw new IllegalArgumentException(String.format(
+ "Replication factor format is <replicas> or <replicas>/<transient>, found '%s'", value));
+ }
+
+ return of(null,
+ Integer.parseInt(trimmed.substring(0, separator).trim()),
+ Integer.parseInt(trimmed.substring(separator + 1).trim()));
+ }
+
+ /**
+ * Mirrors the constraints Cassandra enforces in {@code ReplicationFactor.validate}: transient replicas must
+ * be non-negative and strictly fewer than the total, so at least one full replica always exists.
+ *
+ * @param datacenter datacenter name for the error message, may be {@code null}
+ * @param allReplicas total replicas
+ * @param transientReplicas transient (witness) replicas
+ */
+ static void validate(String datacenter, int allReplicas, int transientReplicas)
Review Comment:
Agreed, done!
##########
cassandra-analytics-common/src/main/java/org/apache/cassandra/spark/data/ReplicationFactor.java:
##########
@@ -188,13 +359,173 @@ public boolean equals(Object other)
ReplicationFactor that = (ReplicationFactor) other;
return this.replicationStrategy == that.replicationStrategy
- && java.util.Objects.equals(this.options, that.options);
+ && Objects.equals(this.replication, that.replication);
}
@Override
public int hashCode()
{
- return Objects.hash(replicationStrategy, options);
+ return Objects.hash(replicationStrategy, replication);
+ }
+
+ /**
+ * {@link #serialVersionUID} is pinned, so an instance serialized before the per-datacenter counts were combined
+ * deserializes with a {@code null} {@code replication}. Only reachable under driver/executor version skew, which
+ * is not a supported configuration, so this reports the mismatch rather than silently losing the counts.
+ *
+ * @return this instance
+ * @throws InvalidObjectException when deserialized from an incompatible older form
+ */
+ private Object readResolve() throws InvalidObjectException
+ {
+ if (replication == null)
+ {
+ throw new InvalidObjectException(
+ "ReplicationFactor was serialized by an incompatible version: per-datacenter replica counts are absent. "
+ + "Driver and executors must run the same version.");
+ }
+ // Rebuild through the canonical constructor so the derived fields, which are transient, are populated
+ return new ReplicationFactor(replicationStrategy, replication, replication);
+ }
+
+ /**
+ * Replica counts for a single datacenter. Cassandra accepts either {@code <replicas>} or
+ * {@code <replicas>/<transient>}; transient replication predates mutation tracking, and witness replicas
+ * (CEP-46) reuse the same form. See {@code org.apache.cassandra.locator.ReplicationFactor} in Cassandra.
+ */
+ public static final class ReplicaCounts implements Serializable
+ {
+ private static final long serialVersionUID = 2026091500000000001L;
+ private static final String TRANSIENT_SEPARATOR = "/";
+
+ private final int allReplicas;
+ private final int transientReplicas;
+
+ private ReplicaCounts(int allReplicas, int transientReplicas)
+ {
+ this.allReplicas = allReplicas;
+ this.transientReplicas = transientReplicas;
+ }
+
+ /**
+ * @param datacenter datacenter name, used only in error messages, may be {@code null}
+ * @param allReplicas total replicas
+ * @param transientReplicas transient (witness) replicas
+ * @return validated counts
+ * @throws IllegalArgumentException when the counts are inconsistent
+ */
+ public static ReplicaCounts of(String datacenter, int allReplicas, int transientReplicas)
Review Comment:
Done!
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For additional commands, e-mail: commits-help@cassandra.apache.org
Re: [PR] CASSANALYTICS-194: Parse / replication factor fo… [cassandra-analytics]
Posted by "mansikhara (via GitHub)" <gi...@apache.org>.
mansikhara commented on code in PR #238:
URL: https://github.com/apache/cassandra-analytics/pull/238#discussion_r4032262526
##########
cassandra-analytics-common/src/main/java/org/apache/cassandra/spark/data/partitioner/CassandraRing.java:
##########
@@ -295,6 +322,13 @@ private void writeObject(ObjectOutputStream out) throws IOException, ClassNotFou
out.writeUTF(option.getKey());
out.writeByte(option.getValue());
}
+ Map<String, Integer> transientOptions = this.replicationFactor.getTransientOptions();
Review Comment:
Done, thanks!
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For additional commands, e-mail: commits-help@cassandra.apache.org
Re: [PR] CASSANALYTICS-194: Parse / replication factor fo… [cassandra-analytics]
Posted by "mansikhara (via GitHub)" <gi...@apache.org>.
mansikhara commented on code in PR #238:
URL: https://github.com/apache/cassandra-analytics/pull/238#discussion_r4086142246
##########
cassandra-analytics-common/src/test/java/org/apache/cassandra/spark/data/ReplicationFactorTests.java:
##########
@@ -111,4 +118,357 @@ public void testEquality()
assertThat(replicationFactor1).isEqualTo(replicationFactor2);
assertThat(replicationFactor1.hashCode()).isEqualTo(replicationFactor2.hashCode());
}
+
+ // Transient / witness replicas: the <replicas>/<transient> form, reused by witness replicas under
+ // mutation tracking (CEP-45/CEP-46)
+
+ @Test
+ public void testNoTransientReplicasByDefault()
+ {
+ ReplicationFactor replicationFactor = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "3"));
+ assertThat(replicationFactor.hasTransientReplicas()).isFalse();
+ assertThat(replicationFactor.getTransientOptions()).isEmpty();
+ assertThat(replicationFactor.getTotalReplicationFactor()).isEqualTo(3);
+ assertThat(replicationFactor.getFullReplicationFactor()).isEqualTo(3);
+ assertThat(replicationFactor.getTransientReplicationFactor()).isEqualTo(0);
+ assertThat(replicationFactor.getFullReplicas("datacenter1")).isEqualTo(3);
+ assertThat(replicationFactor.getTransientReplicas("datacenter1")).isEqualTo(0);
+ }
+
+ @Test
+ public void testTransientReplicasSingleDatacenter()
+ {
+ ReplicationFactor replicationFactor = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "3/1"));
+ assertThat(replicationFactor.hasTransientReplicas()).isTrue();
+ // total keeps its original meaning: all replicas, witnesses included
+ assertThat(replicationFactor.getOptions().get("datacenter1")).isEqualTo(Integer.valueOf(3));
+ assertThat(replicationFactor.getTotalReplicationFactor()).isEqualTo(3);
+ assertThat(replicationFactor.getFullReplicationFactor()).isEqualTo(2);
+ assertThat(replicationFactor.getTransientReplicationFactor()).isEqualTo(1);
+ assertThat(replicationFactor.getFullReplicas("datacenter1")).isEqualTo(2);
+ assertThat(replicationFactor.getTransientReplicas("datacenter1")).isEqualTo(1);
+ }
+
+ @Test
+ public void testTransientReplicasMultipleDatacenters()
+ {
+ ReplicationFactor replicationFactor = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "3/1",
+ "datacenter2", "3/1"));
+ assertThat(replicationFactor.getTotalReplicationFactor()).isEqualTo(6);
+ assertThat(replicationFactor.getFullReplicationFactor()).isEqualTo(4);
+ assertThat(replicationFactor.getTransientReplicationFactor()).isEqualTo(2);
+ }
+
+ @Test
+ public void testMixedTransientAndFullDatacenters()
+ {
+ ReplicationFactor replicationFactor = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "3/1",
+ "datacenter2", "3"));
+ assertThat(replicationFactor.getTotalReplicationFactor()).isEqualTo(6);
+ assertThat(replicationFactor.getFullReplicationFactor()).isEqualTo(5);
+ assertThat(replicationFactor.getTransientReplicas("datacenter1")).isEqualTo(1);
+ assertThat(replicationFactor.getTransientReplicas("datacenter2")).isEqualTo(0);
+ assertThat(replicationFactor.getFullReplicas("datacenter2")).isEqualTo(3);
+ // datacenter2 has no transient replicas, so it must be absent rather than mapped to zero
+ assertThat(replicationFactor.getTransientOptions()).containsOnlyKeys("datacenter1");
+ }
+
+ @Test
+ public void testTransientReplicasSimpleStrategy()
+ {
+ ReplicationFactor replicationFactor = new ReplicationFactor(ImmutableMap.of(
+ "class", "SimpleStrategy",
+ "replication_factor", "3/1"));
+ assertThat(replicationFactor.getReplicationStrategy())
+ .isEqualTo(ReplicationFactor.ReplicationStrategy.SimpleStrategy);
+ assertThat(replicationFactor.getTotalReplicationFactor()).isEqualTo(3);
+ assertThat(replicationFactor.getFullReplicationFactor()).isEqualTo(2);
+ }
+
+ @Test
+ public void testTransientReplicasWithWhitespace()
+ {
+ ReplicationFactor replicationFactor = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", " 3 / 1 "));
+ assertThat(replicationFactor.getTotalReplicationFactor()).isEqualTo(3);
+ assertThat(replicationFactor.getFullReplicationFactor()).isEqualTo(2);
+ }
+
+ @Test
+ public void testTransientEqualToTotalIsRejected()
+ {
+ // Cassandra requires at least one full replica, so 3/3 is invalid and must not be accepted silently
+ assertThatThrownBy(() -> new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "3/3")))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("datacenter1");
+ }
+
+ @Test
+ public void testMalformedReplicationValuesAreRejected()
+ {
+ for (String malformed : new String[]{"3/", "/1", "3/1/1", "3/x", "x/1", "3/-1", ""})
+ {
+ assertThatThrownBy(() -> new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", malformed)))
+ .as("malformed replication value '%s' should be rejected", malformed)
+ .isInstanceOf(IllegalArgumentException.class);
+ }
+ }
+
+ @Test
+ public void testGetFullReplicasUnknownDatacenter()
+ {
+ ReplicationFactor replicationFactor = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "3/1"));
+ assertThatThrownBy(() -> replicationFactor.getFullReplicas("nosuchdc"))
+ .isInstanceOf(IllegalArgumentException.class);
+ }
+
+ @Test
+ public void testTransientOptionsForUnknownDatacenterRejected()
+ {
+ assertThatThrownBy(() -> new ReplicationFactor(
+ ReplicationFactor.ReplicationStrategy.NetworkTopologyStrategy,
+ ImmutableMap.of("datacenter1", 3),
+ ImmutableMap.of("datacenter2", 1)))
+ .isInstanceOf(IllegalArgumentException.class);
+ }
+
+ @Test
+ public void testEqualityConsidersTransientReplicas()
+ {
+ ReplicationFactor full = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "3"));
+ ReplicationFactor withTransient = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "3/1"));
+ assertThat(full).isNotEqualTo(withTransient);
+ assertThat(full.hashCode()).isNotEqualTo(withTransient.hashCode());
+ }
+
+ @Test
+ public void testNegativeReplicationFactorIsRejected()
+ {
+ assertThatThrownBy(() -> new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "-3")))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("datacenter1");
+ }
+
+ @Test
+ public void testZeroReplicationFactorIsAllowed()
+ {
+ // RF 0 is legitimate for NetworkTopologyStrategy: the keyspace is simply not replicated to that datacenter
+ ReplicationFactor replicationFactor = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "3",
+ "datacenter2", "0"));
+ assertThat(replicationFactor.getOptions().get("datacenter2")).isEqualTo(Integer.valueOf(0));
+ assertThat(replicationFactor.getTotalReplicationFactor()).isEqualTo(3);
+ }
+
+ @Test
+ public void testKryoSerializationRoundTripWithTransientReplicas() throws Exception
Review Comment:
Merged, thanks!
##########
cassandra-analytics-common/src/test/java/org/apache/cassandra/spark/data/ReplicationFactorTests.java:
##########
@@ -111,4 +118,357 @@ public void testEquality()
assertThat(replicationFactor1).isEqualTo(replicationFactor2);
assertThat(replicationFactor1.hashCode()).isEqualTo(replicationFactor2.hashCode());
}
+
+ // Transient / witness replicas: the <replicas>/<transient> form, reused by witness replicas under
+ // mutation tracking (CEP-45/CEP-46)
+
+ @Test
+ public void testNoTransientReplicasByDefault()
+ {
+ ReplicationFactor replicationFactor = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "3"));
+ assertThat(replicationFactor.hasTransientReplicas()).isFalse();
+ assertThat(replicationFactor.getTransientOptions()).isEmpty();
+ assertThat(replicationFactor.getTotalReplicationFactor()).isEqualTo(3);
+ assertThat(replicationFactor.getFullReplicationFactor()).isEqualTo(3);
+ assertThat(replicationFactor.getTransientReplicationFactor()).isEqualTo(0);
+ assertThat(replicationFactor.getFullReplicas("datacenter1")).isEqualTo(3);
+ assertThat(replicationFactor.getTransientReplicas("datacenter1")).isEqualTo(0);
+ }
+
+ @Test
+ public void testTransientReplicasSingleDatacenter()
+ {
+ ReplicationFactor replicationFactor = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "3/1"));
+ assertThat(replicationFactor.hasTransientReplicas()).isTrue();
+ // total keeps its original meaning: all replicas, witnesses included
+ assertThat(replicationFactor.getOptions().get("datacenter1")).isEqualTo(Integer.valueOf(3));
+ assertThat(replicationFactor.getTotalReplicationFactor()).isEqualTo(3);
+ assertThat(replicationFactor.getFullReplicationFactor()).isEqualTo(2);
+ assertThat(replicationFactor.getTransientReplicationFactor()).isEqualTo(1);
+ assertThat(replicationFactor.getFullReplicas("datacenter1")).isEqualTo(2);
+ assertThat(replicationFactor.getTransientReplicas("datacenter1")).isEqualTo(1);
+ }
+
+ @Test
+ public void testTransientReplicasMultipleDatacenters()
+ {
+ ReplicationFactor replicationFactor = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "3/1",
+ "datacenter2", "3/1"));
+ assertThat(replicationFactor.getTotalReplicationFactor()).isEqualTo(6);
+ assertThat(replicationFactor.getFullReplicationFactor()).isEqualTo(4);
+ assertThat(replicationFactor.getTransientReplicationFactor()).isEqualTo(2);
+ }
+
+ @Test
+ public void testMixedTransientAndFullDatacenters()
+ {
+ ReplicationFactor replicationFactor = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "3/1",
+ "datacenter2", "3"));
+ assertThat(replicationFactor.getTotalReplicationFactor()).isEqualTo(6);
+ assertThat(replicationFactor.getFullReplicationFactor()).isEqualTo(5);
+ assertThat(replicationFactor.getTransientReplicas("datacenter1")).isEqualTo(1);
+ assertThat(replicationFactor.getTransientReplicas("datacenter2")).isEqualTo(0);
+ assertThat(replicationFactor.getFullReplicas("datacenter2")).isEqualTo(3);
+ // datacenter2 has no transient replicas, so it must be absent rather than mapped to zero
+ assertThat(replicationFactor.getTransientOptions()).containsOnlyKeys("datacenter1");
+ }
+
+ @Test
+ public void testTransientReplicasSimpleStrategy()
+ {
+ ReplicationFactor replicationFactor = new ReplicationFactor(ImmutableMap.of(
+ "class", "SimpleStrategy",
+ "replication_factor", "3/1"));
+ assertThat(replicationFactor.getReplicationStrategy())
+ .isEqualTo(ReplicationFactor.ReplicationStrategy.SimpleStrategy);
+ assertThat(replicationFactor.getTotalReplicationFactor()).isEqualTo(3);
+ assertThat(replicationFactor.getFullReplicationFactor()).isEqualTo(2);
+ }
+
+ @Test
+ public void testTransientReplicasWithWhitespace()
+ {
+ ReplicationFactor replicationFactor = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", " 3 / 1 "));
+ assertThat(replicationFactor.getTotalReplicationFactor()).isEqualTo(3);
+ assertThat(replicationFactor.getFullReplicationFactor()).isEqualTo(2);
+ }
+
+ @Test
+ public void testTransientEqualToTotalIsRejected()
+ {
+ // Cassandra requires at least one full replica, so 3/3 is invalid and must not be accepted silently
+ assertThatThrownBy(() -> new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "3/3")))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("datacenter1");
+ }
+
+ @Test
+ public void testMalformedReplicationValuesAreRejected()
+ {
+ for (String malformed : new String[]{"3/", "/1", "3/1/1", "3/x", "x/1", "3/-1", ""})
+ {
+ assertThatThrownBy(() -> new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", malformed)))
+ .as("malformed replication value '%s' should be rejected", malformed)
+ .isInstanceOf(IllegalArgumentException.class);
+ }
+ }
+
+ @Test
+ public void testGetFullReplicasUnknownDatacenter()
+ {
+ ReplicationFactor replicationFactor = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "3/1"));
+ assertThatThrownBy(() -> replicationFactor.getFullReplicas("nosuchdc"))
+ .isInstanceOf(IllegalArgumentException.class);
+ }
+
+ @Test
+ public void testTransientOptionsForUnknownDatacenterRejected()
+ {
+ assertThatThrownBy(() -> new ReplicationFactor(
+ ReplicationFactor.ReplicationStrategy.NetworkTopologyStrategy,
+ ImmutableMap.of("datacenter1", 3),
+ ImmutableMap.of("datacenter2", 1)))
+ .isInstanceOf(IllegalArgumentException.class);
+ }
+
+ @Test
+ public void testEqualityConsidersTransientReplicas()
+ {
+ ReplicationFactor full = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "3"));
+ ReplicationFactor withTransient = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "3/1"));
+ assertThat(full).isNotEqualTo(withTransient);
+ assertThat(full.hashCode()).isNotEqualTo(withTransient.hashCode());
+ }
+
+ @Test
+ public void testNegativeReplicationFactorIsRejected()
+ {
+ assertThatThrownBy(() -> new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "-3")))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("datacenter1");
+ }
+
+ @Test
+ public void testZeroReplicationFactorIsAllowed()
+ {
+ // RF 0 is legitimate for NetworkTopologyStrategy: the keyspace is simply not replicated to that datacenter
+ ReplicationFactor replicationFactor = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "3",
+ "datacenter2", "0"));
+ assertThat(replicationFactor.getOptions().get("datacenter2")).isEqualTo(Integer.valueOf(0));
+ assertThat(replicationFactor.getTotalReplicationFactor()).isEqualTo(3);
+ }
+
+ @Test
+ public void testKryoSerializationRoundTripWithTransientReplicas() throws Exception
+ {
+ ReplicationFactor original = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "3/1",
+ "datacenter2", "3"));
+
+ Kryo kryo = new Kryo();
+ kryo.register(ReplicationFactor.class, new ReplicationFactor.Serializer());
+
+ ByteArrayOutputStream bytes = new ByteArrayOutputStream();
+ try (Output out = new Output(bytes))
+ {
+ kryo.writeObject(out, original);
+ }
+ ReplicationFactor deserialized;
+ try (Input in = new Input(new ByteArrayInputStream(bytes.toByteArray())))
+ {
+ deserialized = kryo.readObject(in, ReplicationFactor.class);
+ }
+
+ assertThat(deserialized).isEqualTo(original);
+ assertThat(deserialized.getTotalReplicationFactor()).isEqualTo(6);
+ assertThat(deserialized.getFullReplicationFactor()).isEqualTo(5);
+ assertThat(deserialized.getTransientReplicas("datacenter1")).isEqualTo(1);
+ assertThat(deserialized.getTransientReplicas("datacenter2")).isEqualTo(0);
+ }
+
+ @Test
+ public void testJdkSerializationRoundTripWithTransientReplicas() throws Exception
Review Comment:
Merged, thanks!
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For additional commands, e-mail: commits-help@cassandra.apache.org
Re: [PR] CASSANALYTICS-194: Parse / replication factor fo… [cassandra-analytics]
Posted by "sarankk (via GitHub)" <gi...@apache.org>.
sarankk commented on code in PR #238:
URL: https://github.com/apache/cassandra-analytics/pull/238#discussion_r4018411791
##########
cassandra-analytics-core/src/test/java/org/apache/cassandra/spark/utils/CqlUtilsTest.java:
##########
@@ -142,6 +142,84 @@ public void testExtractReplicationFactor(CassandraBridge bridge)
assertThat(systemSchemaRf.getOptions()).isEqualTo(ImmutableMap.of());
}
+ @Test
+ public void testExtractReplicationFactorWithWitnessReplicas()
+ {
+ // Witness-enabled keyspace as created by Cassandra's WitnessAlwaysReadsFullReplicaTest on the
+ // cep-45-mutation-tracking branch: the <replicas>/<transient> form plus replication_type = 'tracked'
+ String schema = "CREATE KEYSPACE witnessks WITH REPLICATION = {'class': 'NetworkTopologyStrategy', "
+ + "'datacenter1': '3/1', 'datacenter2': '3/1'} AND replication_type = 'tracked' "
Review Comment:
`replication_type = 'tracked'` this field is not yet supported in Sidecar schema response, shall we remove this from example?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For additional commands, e-mail: commits-help@cassandra.apache.org
Re: [PR] CASSANALYTICS-194: Parse / replication factor fo… [cassandra-analytics]
Posted by "mansikhara (via GitHub)" <gi...@apache.org>.
mansikhara commented on code in PR #238:
URL: https://github.com/apache/cassandra-analytics/pull/238#discussion_r4020068877
##########
cassandra-analytics-common/src/main/java/org/apache/cassandra/spark/data/ReplicationFactor.java:
##########
@@ -50,6 +51,11 @@
* "replication_factor" : 1
* }
* }
+ * <p>
+ * Replica counts may also use the {@code <replicas>/<transient>} form, e.g. {@code "DC1" : "3/1"}, meaning three
+ * replicas of which one is transient. Witness replicas under mutation tracking (CEP-45/CEP-46) reuse this form, so
Review Comment:
Good catch, you are right that transient replication came first. Applied your suggestion, thanks!
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For additional commands, e-mail: commits-help@cassandra.apache.org
Re: [PR] CASSANALYTICS-194: Parse / replication factor fo… [cassandra-analytics]
Posted by "sarankk (via GitHub)" <gi...@apache.org>.
sarankk commented on code in PR #238:
URL: https://github.com/apache/cassandra-analytics/pull/238#discussion_r4017680293
##########
cassandra-analytics-common/src/main/java/org/apache/cassandra/spark/data/ReplicationFactor.java:
##########
@@ -50,6 +51,11 @@
* "replication_factor" : 1
* }
* }
+ * <p>
+ * Replica counts may also use the {@code <replicas>/<transient>} form, e.g. {@code "DC1" : "3/1"}, meaning three
+ * replicas of which one is transient. Witness replicas under mutation tracking (CEP-45/CEP-46) reuse this form, so
Review Comment:
Nit: Transient replication was added before MT, it was updated to work on top of MT later. Also why do we use term reuse here?
```suggestion
* replicas of which one is transient. Witness replicas (CEP-46) reuse this form, so
```
##########
cassandra-analytics-common/src/main/java/org/apache/cassandra/spark/data/ReplicationFactor.java:
##########
@@ -108,11 +114,44 @@ public static ReplicationFactor simpleStrategy(int rf)
private final ReplicationStrategy replicationStrategy;
@NotNull
private final Map<String, Integer> options;
+ /**
+ * Per-datacenter count of transient (witness) replicas, parsed from the {@code <replicas>/<transient>} form.
+ * A datacenter absent from this map has no transient replicas. Always empty for untracked keyspaces using the
+ * plain {@code <replicas>} form, which keeps behaviour identical for those keyspaces.
+ */
+ @NotNull
+ private final Map<String, Integer> transientOptions;
+ /**
+ * Lenient parse: a replication value that cannot be parsed is logged and its datacenter omitted. Retained for
+ * callers that tolerate a partial replication factor.
+ *
+ * @param options the raw replication map, including the {@code class} entry
+ */
public ReplicationFactor(@NotNull Map<String, String> options)
+ {
+ this(options, false);
+ }
+
+ /**
+ * Strict parse: a replication value that cannot be parsed raises {@link IllegalArgumentException} naming the
+ * offending datacenter, rather than silently omitting it. Prefer this when a partial replication factor would
+ * produce a misleading failure later.
+ *
+ * @param options the raw replication map, including the {@code class} entry
+ * @return the parsed replication factor
+ * @throws IllegalArgumentException when any replication value cannot be parsed
+ */
+ public static ReplicationFactor parseStrict(@NotNull Map<String, String> options)
+ {
+ return new ReplicationFactor(options, true);
+ }
+
+ private ReplicationFactor(@NotNull Map<String, String> options, boolean strict)
{
this.replicationStrategy = ReplicationFactor.ReplicationStrategy.getEnum(options.get("class"));
this.options = new LinkedHashMap<>(options.size());
Review Comment:
If we plan to merge the maps, shall we make this immutable ?
##########
cassandra-analytics-common/src/main/java/org/apache/cassandra/spark/data/ReplicationFactor.java:
##########
@@ -108,11 +114,44 @@ public static ReplicationFactor simpleStrategy(int rf)
private final ReplicationStrategy replicationStrategy;
@NotNull
private final Map<String, Integer> options;
+ /**
+ * Per-datacenter count of transient (witness) replicas, parsed from the {@code <replicas>/<transient>} form.
+ * A datacenter absent from this map has no transient replicas. Always empty for untracked keyspaces using the
+ * plain {@code <replicas>} form, which keeps behaviour identical for those keyspaces.
+ */
+ @NotNull
+ private final Map<String, Integer> transientOptions;
Review Comment:
Options hold `dc : 3` and transient options hold `dc : 1` for transient replication `dc: 3/1`. The maps could diverge. Shall we combine the 2 maps into 1 using `ReplicaCounts`?
##########
cassandra-analytics-common/src/test/java/org/apache/cassandra/spark/data/ReplicationFactorTests.java:
##########
@@ -111,4 +118,296 @@ public void testEquality()
assertThat(replicationFactor1).isEqualTo(replicationFactor2);
assertThat(replicationFactor1.hashCode()).isEqualTo(replicationFactor2.hashCode());
}
+
+ // Transient / witness replicas: the <replicas>/<transient> form, reused by witness replicas under
+ // mutation tracking (CEP-45/CEP-46)
+
+ @Test
+ public void testNoTransientReplicasByDefault()
+ {
+ ReplicationFactor replicationFactor = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "3"));
+ assertThat(replicationFactor.hasTransientReplicas()).isFalse();
+ assertThat(replicationFactor.getTransientOptions()).isEmpty();
+ assertThat(replicationFactor.getTotalReplicationFactor()).isEqualTo(3);
+ assertThat(replicationFactor.getFullReplicationFactor()).isEqualTo(3);
+ assertThat(replicationFactor.getTransientReplicationFactor()).isEqualTo(0);
+ assertThat(replicationFactor.getFullReplicas("datacenter1")).isEqualTo(3);
+ assertThat(replicationFactor.getTransientReplicas("datacenter1")).isEqualTo(0);
+ }
+
+ @Test
+ public void testTransientReplicasSingleDatacenter()
+ {
+ ReplicationFactor replicationFactor = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "3/1"));
+ assertThat(replicationFactor.hasTransientReplicas()).isTrue();
+ // total keeps its original meaning: all replicas, witnesses included
+ assertThat(replicationFactor.getOptions().get("datacenter1")).isEqualTo(Integer.valueOf(3));
+ assertThat(replicationFactor.getTotalReplicationFactor()).isEqualTo(3);
+ assertThat(replicationFactor.getFullReplicationFactor()).isEqualTo(2);
+ assertThat(replicationFactor.getTransientReplicationFactor()).isEqualTo(1);
+ assertThat(replicationFactor.getFullReplicas("datacenter1")).isEqualTo(2);
+ assertThat(replicationFactor.getTransientReplicas("datacenter1")).isEqualTo(1);
+ }
+
+ @Test
+ public void testTransientReplicasMultipleDatacenters()
+ {
+ ReplicationFactor replicationFactor = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "3/1",
+ "datacenter2", "3/1"));
+ assertThat(replicationFactor.getTotalReplicationFactor()).isEqualTo(6);
+ assertThat(replicationFactor.getFullReplicationFactor()).isEqualTo(4);
+ assertThat(replicationFactor.getTransientReplicationFactor()).isEqualTo(2);
+ }
+
+ @Test
+ public void testMixedTransientAndFullDatacenters()
+ {
+ ReplicationFactor replicationFactor = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "3/1",
+ "datacenter2", "3"));
+ assertThat(replicationFactor.getTotalReplicationFactor()).isEqualTo(6);
+ assertThat(replicationFactor.getFullReplicationFactor()).isEqualTo(5);
+ assertThat(replicationFactor.getTransientReplicas("datacenter1")).isEqualTo(1);
+ assertThat(replicationFactor.getTransientReplicas("datacenter2")).isEqualTo(0);
+ assertThat(replicationFactor.getFullReplicas("datacenter2")).isEqualTo(3);
+ // datacenter2 has no transient replicas, so it must be absent rather than mapped to zero
+ assertThat(replicationFactor.getTransientOptions()).containsOnlyKeys("datacenter1");
+ }
+
+ @Test
+ public void testTransientReplicasSimpleStrategy()
+ {
+ ReplicationFactor replicationFactor = new ReplicationFactor(ImmutableMap.of(
+ "class", "SimpleStrategy",
+ "replication_factor", "3/1"));
+ assertThat(replicationFactor.getReplicationStrategy())
+ .isEqualTo(ReplicationFactor.ReplicationStrategy.SimpleStrategy);
+ assertThat(replicationFactor.getTotalReplicationFactor()).isEqualTo(3);
+ assertThat(replicationFactor.getFullReplicationFactor()).isEqualTo(2);
+ }
+
+ @Test
+ public void testTransientReplicasWithWhitespace()
+ {
+ ReplicationFactor replicationFactor = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", " 3 / 1 "));
+ assertThat(replicationFactor.getTotalReplicationFactor()).isEqualTo(3);
+ assertThat(replicationFactor.getFullReplicationFactor()).isEqualTo(2);
+ }
+
+ @Test
+ public void testTransientEqualToTotalIsRejected()
+ {
+ // Cassandra requires at least one full replica, so 3/3 is invalid
+ ReplicationFactor replicationFactor = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "3/3"));
+ assertThat(replicationFactor.getOptions()).doesNotContainKey("datacenter1");
Review Comment:
We should throw in this scenario instead, if Cassandra does not allow it, Sidecar should fail as well.
##########
cassandra-analytics-core/src/test/java/org/apache/cassandra/spark/utils/CqlUtilsTest.java:
##########
@@ -142,6 +142,84 @@ public void testExtractReplicationFactor(CassandraBridge bridge)
assertThat(systemSchemaRf.getOptions()).isEqualTo(ImmutableMap.of());
}
+ @Test
+ public void testExtractReplicationFactorWithWitnessReplicas()
+ {
+ // Witness-enabled keyspace as created by Cassandra's WitnessAlwaysReadsFullReplicaTest on the
+ // cep-45-mutation-tracking branch: the <replicas>/<transient> form plus replication_type = 'tracked'
+ String schema = "CREATE KEYSPACE witnessks WITH REPLICATION = {'class': 'NetworkTopologyStrategy', "
+ + "'datacenter1': '3/1', 'datacenter2': '3/1'} AND replication_type = 'tracked' "
Review Comment:
`replication_type = 'tracked'` this field is not yet supported in Sidecar schema response, shall we remove this?
##########
cassandra-analytics-common/src/test/java/org/apache/cassandra/spark/data/ReplicationFactorTests.java:
##########
@@ -111,4 +118,296 @@ public void testEquality()
assertThat(replicationFactor1).isEqualTo(replicationFactor2);
assertThat(replicationFactor1.hashCode()).isEqualTo(replicationFactor2.hashCode());
}
+
+ // Transient / witness replicas: the <replicas>/<transient> form, reused by witness replicas under
+ // mutation tracking (CEP-45/CEP-46)
+
+ @Test
+ public void testNoTransientReplicasByDefault()
+ {
+ ReplicationFactor replicationFactor = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "3"));
+ assertThat(replicationFactor.hasTransientReplicas()).isFalse();
+ assertThat(replicationFactor.getTransientOptions()).isEmpty();
+ assertThat(replicationFactor.getTotalReplicationFactor()).isEqualTo(3);
+ assertThat(replicationFactor.getFullReplicationFactor()).isEqualTo(3);
+ assertThat(replicationFactor.getTransientReplicationFactor()).isEqualTo(0);
+ assertThat(replicationFactor.getFullReplicas("datacenter1")).isEqualTo(3);
+ assertThat(replicationFactor.getTransientReplicas("datacenter1")).isEqualTo(0);
+ }
+
+ @Test
+ public void testTransientReplicasSingleDatacenter()
+ {
+ ReplicationFactor replicationFactor = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "3/1"));
+ assertThat(replicationFactor.hasTransientReplicas()).isTrue();
+ // total keeps its original meaning: all replicas, witnesses included
+ assertThat(replicationFactor.getOptions().get("datacenter1")).isEqualTo(Integer.valueOf(3));
+ assertThat(replicationFactor.getTotalReplicationFactor()).isEqualTo(3);
+ assertThat(replicationFactor.getFullReplicationFactor()).isEqualTo(2);
+ assertThat(replicationFactor.getTransientReplicationFactor()).isEqualTo(1);
+ assertThat(replicationFactor.getFullReplicas("datacenter1")).isEqualTo(2);
+ assertThat(replicationFactor.getTransientReplicas("datacenter1")).isEqualTo(1);
+ }
+
+ @Test
+ public void testTransientReplicasMultipleDatacenters()
+ {
+ ReplicationFactor replicationFactor = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "3/1",
+ "datacenter2", "3/1"));
+ assertThat(replicationFactor.getTotalReplicationFactor()).isEqualTo(6);
+ assertThat(replicationFactor.getFullReplicationFactor()).isEqualTo(4);
+ assertThat(replicationFactor.getTransientReplicationFactor()).isEqualTo(2);
+ }
+
+ @Test
+ public void testMixedTransientAndFullDatacenters()
+ {
+ ReplicationFactor replicationFactor = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "3/1",
+ "datacenter2", "3"));
+ assertThat(replicationFactor.getTotalReplicationFactor()).isEqualTo(6);
+ assertThat(replicationFactor.getFullReplicationFactor()).isEqualTo(5);
+ assertThat(replicationFactor.getTransientReplicas("datacenter1")).isEqualTo(1);
+ assertThat(replicationFactor.getTransientReplicas("datacenter2")).isEqualTo(0);
+ assertThat(replicationFactor.getFullReplicas("datacenter2")).isEqualTo(3);
+ // datacenter2 has no transient replicas, so it must be absent rather than mapped to zero
+ assertThat(replicationFactor.getTransientOptions()).containsOnlyKeys("datacenter1");
+ }
+
+ @Test
+ public void testTransientReplicasSimpleStrategy()
+ {
+ ReplicationFactor replicationFactor = new ReplicationFactor(ImmutableMap.of(
+ "class", "SimpleStrategy",
+ "replication_factor", "3/1"));
+ assertThat(replicationFactor.getReplicationStrategy())
+ .isEqualTo(ReplicationFactor.ReplicationStrategy.SimpleStrategy);
+ assertThat(replicationFactor.getTotalReplicationFactor()).isEqualTo(3);
+ assertThat(replicationFactor.getFullReplicationFactor()).isEqualTo(2);
+ }
+
+ @Test
+ public void testTransientReplicasWithWhitespace()
+ {
+ ReplicationFactor replicationFactor = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", " 3 / 1 "));
+ assertThat(replicationFactor.getTotalReplicationFactor()).isEqualTo(3);
+ assertThat(replicationFactor.getFullReplicationFactor()).isEqualTo(2);
+ }
+
+ @Test
+ public void testTransientEqualToTotalIsRejected()
+ {
+ // Cassandra requires at least one full replica, so 3/3 is invalid
+ ReplicationFactor replicationFactor = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "3/3"));
+ assertThat(replicationFactor.getOptions()).doesNotContainKey("datacenter1");
+ }
+
+ @Test
+ public void testMalformedTransientValuesAreSkipped()
+ {
+ for (String malformed : new String[]{ "3/", "/1", "3/1/1", "3/x", "x/1", "3/-1", "" })
+ {
+ ReplicationFactor replicationFactor = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", malformed));
+ assertThat(replicationFactor.getOptions())
+ .as("malformed value '%s' should not produce a replication factor entry", malformed)
+ .doesNotContainKey("datacenter1");
+ }
+ }
+
+ @Test
+ public void testGetFullReplicasUnknownDatacenter()
+ {
+ ReplicationFactor replicationFactor = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "3/1"));
+ assertThatThrownBy(() -> replicationFactor.getFullReplicas("nosuchdc"))
+ .isInstanceOf(IllegalArgumentException.class);
+ }
+
+ @Test
+ public void testTransientOptionsForUnknownDatacenterRejected()
+ {
+ assertThatThrownBy(() -> new ReplicationFactor(
+ ReplicationFactor.ReplicationStrategy.NetworkTopologyStrategy,
+ ImmutableMap.of("datacenter1", 3),
+ ImmutableMap.of("datacenter2", 1)))
+ .isInstanceOf(IllegalArgumentException.class);
+ }
+
+ @Test
+ public void testEqualityConsidersTransientReplicas()
+ {
+ ReplicationFactor full = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "3"));
+ ReplicationFactor withTransient = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "3/1"));
+ assertThat(full).isNotEqualTo(withTransient);
+ assertThat(full.hashCode()).isNotEqualTo(withTransient.hashCode());
+ }
+
+ @Test
+ public void testNegativeReplicationFactorIsRejected()
+ {
+ ReplicationFactor replicationFactor = new ReplicationFactor(ImmutableMap.of(
+ "class", "NetworkTopologyStrategy",
+ "datacenter1", "-3"));
+ assertThat(replicationFactor.getOptions()).doesNotContainKey("datacenter1");
Review Comment:
Should we throw in this scenario as well?
##########
cassandra-analytics-common/src/main/java/org/apache/cassandra/spark/data/ReplicationFactor.java:
##########
@@ -108,11 +114,44 @@ public static ReplicationFactor simpleStrategy(int rf)
private final ReplicationStrategy replicationStrategy;
@NotNull
private final Map<String, Integer> options;
+ /**
+ * Per-datacenter count of transient (witness) replicas, parsed from the {@code <replicas>/<transient>} form.
+ * A datacenter absent from this map has no transient replicas. Always empty for untracked keyspaces using the
+ * plain {@code <replicas>} form, which keeps behaviour identical for those keyspaces.
+ */
+ @NotNull
+ private final Map<String, Integer> transientOptions;
+ /**
+ * Lenient parse: a replication value that cannot be parsed is logged and its datacenter omitted. Retained for
Review Comment:
In what scenario do we anticipate using lenient parse?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For additional commands, e-mail: commits-help@cassandra.apache.org
Re: [PR] CASSANALYTICS-194: Parse / replication factor fo… [cassandra-analytics]
Posted by "mansikhara (via GitHub)" <gi...@apache.org>.
mansikhara commented on code in PR #238:
URL: https://github.com/apache/cassandra-analytics/pull/238#discussion_r4041080934
##########
cassandra-analytics-common/src/main/java/org/apache/cassandra/spark/data/ReplicationFactor.java:
##########
@@ -106,62 +110,209 @@ public static ReplicationFactor simpleStrategy(int rf)
@NotNull
private final ReplicationStrategy replicationStrategy;
+ /**
+ * Per-datacenter replica counts. Holding the total and the transient count together, rather than in two
+ * parallel maps, means the two cannot drift apart.
+ */
@NotNull
- private final Map<String, Integer> options;
+ private final Map<String, ReplicaCounts> replication;
+ /**
+ * Parses a raw replication map. A value that cannot be parsed, or that Cassandra itself would reject, raises
+ * {@link IllegalArgumentException} naming the offending datacenter: a partial replication factor is not usable
+ * and reporting it here avoids a misleading failure later, such as "DC not found in replication factor".
+ *
+ * @param options the raw replication map, including the {@code class} entry
+ * @throws IllegalArgumentException when any replication value cannot be parsed
+ */
public ReplicationFactor(@NotNull Map<String, String> options)
{
- this.replicationStrategy = ReplicationFactor.ReplicationStrategy.getEnum(options.get("class"));
- this.options = new LinkedHashMap<>(options.size());
- for (Map.Entry<String, String> entry : options.entrySet())
+ this(ReplicationStrategy.getEnum(options.get("class")), parse(options), options);
+ }
+
+ public ReplicationFactor(@NotNull ReplicationStrategy replicationStrategy, @NotNull Map<String, Integer> options)
+ {
+ this(replicationStrategy, options, Collections.emptyMap());
+ }
+
+ public ReplicationFactor(@NotNull ReplicationStrategy replicationStrategy,
+ @NotNull Map<String, Integer> options,
+ @NotNull Map<String, Integer> transientOptions)
+ {
+ this(replicationStrategy, merge(options, transientOptions), options);
+ }
+
+ /**
+ * Canonical constructor. Every other constructor resolves its input to per-datacenter counts and delegates here.
+ *
+ * @param replicationStrategy the replication strategy
+ * @param replication per-datacenter replica counts, already validated individually
+ * @param raw the caller's original input, used only in the error message
+ */
+ private ReplicationFactor(@NotNull ReplicationStrategy replicationStrategy,
+ @NotNull Map<String, ReplicaCounts> replication,
+ @NotNull Object raw)
+ {
+ // A strategy other than LocalStrategy with no datacenter entries is not usable
+ if (replicationStrategy != ReplicationStrategy.LocalStrategy && replication.isEmpty())
{
- if ("class".equals(entry.getKey()))
+ throw new IllegalArgumentException("Could not find replication info in schema map: " + raw);
+ }
+ this.replicationStrategy = replicationStrategy;
+ this.replication = Collections.unmodifiableMap(new LinkedHashMap<>(replication));
+ }
+
+ /**
+ * Resolves raw string values, e.g. {@code "3"} or {@code "3/1"}, to per-datacenter counts.
+ */
+ private static Map<String, ReplicaCounts> parse(@NotNull Map<String, String> options)
+ {
+ Map<String, ReplicaCounts> parsed = new LinkedHashMap<>(options.size());
+ options.forEach((datacenter, value) -> {
+ if ("class".equals(datacenter))
{
- continue;
+ return;
}
-
try
{
- this.options.put(entry.getKey(), Integer.parseInt(entry.getValue()));
+ parsed.put(datacenter, ReplicaCounts.parse(value));
}
- catch (NumberFormatException exception)
+ catch (IllegalArgumentException exception)
{
- LOGGER.warn("Could not parse replication option: {} = {}", entry.getKey(), entry.getValue());
+ throw new IllegalArgumentException(String.format("Could not parse replication option: %s = %s",
+ datacenter, value), exception);
}
- }
+ });
+ return parsed;
}
- public ReplicationFactor(@NotNull ReplicationStrategy replicationStrategy, @NotNull Map<String, Integer> options)
+ /**
+ * Resolves separate total and transient maps to per-datacenter counts, rejecting a transient entry for a
+ * datacenter that has no replication factor.
+ */
+ private static Map<String, ReplicaCounts> merge(@NotNull Map<String, Integer> options,
+ @NotNull Map<String, Integer> transientOptions)
{
- this.replicationStrategy = replicationStrategy;
- this.options = new LinkedHashMap<>(options.size());
+ Map<String, ReplicaCounts> merged = new LinkedHashMap<>(options.size());
+ options.forEach((datacenter, allReplicas) -> {
+ if (!"class".equals(datacenter))
+ {
+ merged.put(datacenter,
+ ReplicaCounts.of(datacenter, allReplicas, transientOptions.getOrDefault(datacenter, 0)));
+ }
+ });
+ transientOptions.forEach((datacenter, transientReplicas) -> {
+ if (!"class".equals(datacenter) && transientReplicas != null && transientReplicas != 0
+ && !merged.containsKey(datacenter))
+ {
+ throw new IllegalArgumentException(String.format(
+ "Transient replicas specified for %s but it has no replication factor", datacenter));
+ }
+ });
+ return merged;
+ }
- if (!replicationStrategy.equals(ReplicationStrategy.LocalStrategy) && options.isEmpty())
- {
- throw new RuntimeException(String.format("Could not find replication info in schema map: %s.", options));
- }
+ /**
+ * @return the total number of replicas across all datacenters, including transient (witness) replicas.
+ * Semantics are unchanged from before transient replica support was added.
+ */
+ public Integer getTotalReplicationFactor()
+ {
+ return replication.values().stream().mapToInt(ReplicaCounts::allReplicas).sum();
+ }
- for (Map.Entry<String, Integer> entry : options.entrySet())
+ /**
+ * @return the number of replicas across all datacenters that hold the full data set, i.e. the total
+ * replication factor minus transient (witness) replicas
+ */
+ public Integer getFullReplicationFactor()
+ {
+ return replication.values().stream().mapToInt(ReplicaCounts::fullReplicas).sum();
Review Comment:
Done!
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For additional commands, e-mail: commits-help@cassandra.apache.org
Re: [PR] CASSANALYTICS-194: Parse / replication factor fo… [cassandra-analytics]
Posted by "sarankk (via GitHub)" <gi...@apache.org>.
sarankk commented on code in PR #238:
URL: https://github.com/apache/cassandra-analytics/pull/238#discussion_r4039597244
##########
cassandra-analytics-common/src/main/java/org/apache/cassandra/spark/data/ReplicationFactor.java:
##########
@@ -106,62 +110,209 @@ public static ReplicationFactor simpleStrategy(int rf)
@NotNull
private final ReplicationStrategy replicationStrategy;
+ /**
+ * Per-datacenter replica counts. Holding the total and the transient count together, rather than in two
+ * parallel maps, means the two cannot drift apart.
+ */
@NotNull
- private final Map<String, Integer> options;
+ private final Map<String, ReplicaCounts> replication;
+ /**
+ * Parses a raw replication map. A value that cannot be parsed, or that Cassandra itself would reject, raises
+ * {@link IllegalArgumentException} naming the offending datacenter: a partial replication factor is not usable
+ * and reporting it here avoids a misleading failure later, such as "DC not found in replication factor".
+ *
+ * @param options the raw replication map, including the {@code class} entry
+ * @throws IllegalArgumentException when any replication value cannot be parsed
+ */
public ReplicationFactor(@NotNull Map<String, String> options)
{
- this.replicationStrategy = ReplicationFactor.ReplicationStrategy.getEnum(options.get("class"));
- this.options = new LinkedHashMap<>(options.size());
- for (Map.Entry<String, String> entry : options.entrySet())
+ this(ReplicationStrategy.getEnum(options.get("class")), parse(options), options);
+ }
+
+ public ReplicationFactor(@NotNull ReplicationStrategy replicationStrategy, @NotNull Map<String, Integer> options)
+ {
+ this(replicationStrategy, options, Collections.emptyMap());
+ }
+
+ public ReplicationFactor(@NotNull ReplicationStrategy replicationStrategy,
+ @NotNull Map<String, Integer> options,
+ @NotNull Map<String, Integer> transientOptions)
+ {
+ this(replicationStrategy, merge(options, transientOptions), options);
+ }
+
+ /**
+ * Canonical constructor. Every other constructor resolves its input to per-datacenter counts and delegates here.
+ *
+ * @param replicationStrategy the replication strategy
+ * @param replication per-datacenter replica counts, already validated individually
+ * @param raw the caller's original input, used only in the error message
+ */
+ private ReplicationFactor(@NotNull ReplicationStrategy replicationStrategy,
+ @NotNull Map<String, ReplicaCounts> replication,
+ @NotNull Object raw)
+ {
+ // A strategy other than LocalStrategy with no datacenter entries is not usable
+ if (replicationStrategy != ReplicationStrategy.LocalStrategy && replication.isEmpty())
{
- if ("class".equals(entry.getKey()))
+ throw new IllegalArgumentException("Could not find replication info in schema map: " + raw);
+ }
+ this.replicationStrategy = replicationStrategy;
+ this.replication = Collections.unmodifiableMap(new LinkedHashMap<>(replication));
+ }
+
+ /**
+ * Resolves raw string values, e.g. {@code "3"} or {@code "3/1"}, to per-datacenter counts.
+ */
+ private static Map<String, ReplicaCounts> parse(@NotNull Map<String, String> options)
+ {
+ Map<String, ReplicaCounts> parsed = new LinkedHashMap<>(options.size());
+ options.forEach((datacenter, value) -> {
+ if ("class".equals(datacenter))
{
- continue;
+ return;
}
-
try
{
- this.options.put(entry.getKey(), Integer.parseInt(entry.getValue()));
+ parsed.put(datacenter, ReplicaCounts.parse(value));
}
- catch (NumberFormatException exception)
+ catch (IllegalArgumentException exception)
{
- LOGGER.warn("Could not parse replication option: {} = {}", entry.getKey(), entry.getValue());
+ throw new IllegalArgumentException(String.format("Could not parse replication option: %s = %s",
+ datacenter, value), exception);
}
- }
+ });
+ return parsed;
}
- public ReplicationFactor(@NotNull ReplicationStrategy replicationStrategy, @NotNull Map<String, Integer> options)
+ /**
+ * Resolves separate total and transient maps to per-datacenter counts, rejecting a transient entry for a
+ * datacenter that has no replication factor.
+ */
+ private static Map<String, ReplicaCounts> merge(@NotNull Map<String, Integer> options,
+ @NotNull Map<String, Integer> transientOptions)
{
- this.replicationStrategy = replicationStrategy;
- this.options = new LinkedHashMap<>(options.size());
+ Map<String, ReplicaCounts> merged = new LinkedHashMap<>(options.size());
+ options.forEach((datacenter, allReplicas) -> {
+ if (!"class".equals(datacenter))
+ {
+ merged.put(datacenter,
+ ReplicaCounts.of(datacenter, allReplicas, transientOptions.getOrDefault(datacenter, 0)));
+ }
+ });
+ transientOptions.forEach((datacenter, transientReplicas) -> {
+ if (!"class".equals(datacenter) && transientReplicas != null && transientReplicas != 0
+ && !merged.containsKey(datacenter))
+ {
+ throw new IllegalArgumentException(String.format(
+ "Transient replicas specified for %s but it has no replication factor", datacenter));
+ }
+ });
+ return merged;
+ }
- if (!replicationStrategy.equals(ReplicationStrategy.LocalStrategy) && options.isEmpty())
- {
- throw new RuntimeException(String.format("Could not find replication info in schema map: %s.", options));
- }
+ /**
+ * @return the total number of replicas across all datacenters, including transient (witness) replicas.
+ * Semantics are unchanged from before transient replica support was added.
+ */
+ public Integer getTotalReplicationFactor()
+ {
+ return replication.values().stream().mapToInt(ReplicaCounts::allReplicas).sum();
+ }
- for (Map.Entry<String, Integer> entry : options.entrySet())
+ /**
+ * @return the number of replicas across all datacenters that hold the full data set, i.e. the total
+ * replication factor minus transient (witness) replicas
+ */
+ public Integer getFullReplicationFactor()
+ {
+ return replication.values().stream().mapToInt(ReplicaCounts::fullReplicas).sum();
Review Comment:
Nit: Shall we precompute these values in constructor and return here
##########
cassandra-analytics-common/src/main/java/org/apache/cassandra/spark/data/ReplicationFactor.java:
##########
@@ -106,62 +110,209 @@ public static ReplicationFactor simpleStrategy(int rf)
@NotNull
private final ReplicationStrategy replicationStrategy;
+ /**
+ * Per-datacenter replica counts. Holding the total and the transient count together, rather than in two
+ * parallel maps, means the two cannot drift apart.
+ */
@NotNull
- private final Map<String, Integer> options;
+ private final Map<String, ReplicaCounts> replication;
+ /**
+ * Parses a raw replication map. A value that cannot be parsed, or that Cassandra itself would reject, raises
+ * {@link IllegalArgumentException} naming the offending datacenter: a partial replication factor is not usable
+ * and reporting it here avoids a misleading failure later, such as "DC not found in replication factor".
+ *
+ * @param options the raw replication map, including the {@code class} entry
+ * @throws IllegalArgumentException when any replication value cannot be parsed
+ */
public ReplicationFactor(@NotNull Map<String, String> options)
{
- this.replicationStrategy = ReplicationFactor.ReplicationStrategy.getEnum(options.get("class"));
- this.options = new LinkedHashMap<>(options.size());
- for (Map.Entry<String, String> entry : options.entrySet())
+ this(ReplicationStrategy.getEnum(options.get("class")), parse(options), options);
+ }
+
+ public ReplicationFactor(@NotNull ReplicationStrategy replicationStrategy, @NotNull Map<String, Integer> options)
+ {
+ this(replicationStrategy, options, Collections.emptyMap());
+ }
+
+ public ReplicationFactor(@NotNull ReplicationStrategy replicationStrategy,
+ @NotNull Map<String, Integer> options,
+ @NotNull Map<String, Integer> transientOptions)
+ {
+ this(replicationStrategy, merge(options, transientOptions), options);
+ }
+
+ /**
+ * Canonical constructor. Every other constructor resolves its input to per-datacenter counts and delegates here.
+ *
+ * @param replicationStrategy the replication strategy
+ * @param replication per-datacenter replica counts, already validated individually
+ * @param raw the caller's original input, used only in the error message
+ */
+ private ReplicationFactor(@NotNull ReplicationStrategy replicationStrategy,
+ @NotNull Map<String, ReplicaCounts> replication,
+ @NotNull Object raw)
+ {
+ // A strategy other than LocalStrategy with no datacenter entries is not usable
+ if (replicationStrategy != ReplicationStrategy.LocalStrategy && replication.isEmpty())
{
- if ("class".equals(entry.getKey()))
+ throw new IllegalArgumentException("Could not find replication info in schema map: " + raw);
+ }
+ this.replicationStrategy = replicationStrategy;
+ this.replication = Collections.unmodifiableMap(new LinkedHashMap<>(replication));
+ }
+
+ /**
+ * Resolves raw string values, e.g. {@code "3"} or {@code "3/1"}, to per-datacenter counts.
+ */
+ private static Map<String, ReplicaCounts> parse(@NotNull Map<String, String> options)
+ {
+ Map<String, ReplicaCounts> parsed = new LinkedHashMap<>(options.size());
+ options.forEach((datacenter, value) -> {
+ if ("class".equals(datacenter))
{
- continue;
+ return;
}
-
try
{
- this.options.put(entry.getKey(), Integer.parseInt(entry.getValue()));
+ parsed.put(datacenter, ReplicaCounts.parse(value));
}
- catch (NumberFormatException exception)
+ catch (IllegalArgumentException exception)
{
- LOGGER.warn("Could not parse replication option: {} = {}", entry.getKey(), entry.getValue());
+ throw new IllegalArgumentException(String.format("Could not parse replication option: %s = %s",
+ datacenter, value), exception);
}
- }
+ });
+ return parsed;
}
- public ReplicationFactor(@NotNull ReplicationStrategy replicationStrategy, @NotNull Map<String, Integer> options)
+ /**
+ * Resolves separate total and transient maps to per-datacenter counts, rejecting a transient entry for a
+ * datacenter that has no replication factor.
+ */
+ private static Map<String, ReplicaCounts> merge(@NotNull Map<String, Integer> options,
+ @NotNull Map<String, Integer> transientOptions)
{
- this.replicationStrategy = replicationStrategy;
- this.options = new LinkedHashMap<>(options.size());
+ Map<String, ReplicaCounts> merged = new LinkedHashMap<>(options.size());
+ options.forEach((datacenter, allReplicas) -> {
+ if (!"class".equals(datacenter))
+ {
+ merged.put(datacenter,
+ ReplicaCounts.of(datacenter, allReplicas, transientOptions.getOrDefault(datacenter, 0)));
+ }
+ });
+ transientOptions.forEach((datacenter, transientReplicas) -> {
+ if (!"class".equals(datacenter) && transientReplicas != null && transientReplicas != 0
+ && !merged.containsKey(datacenter))
+ {
+ throw new IllegalArgumentException(String.format(
+ "Transient replicas specified for %s but it has no replication factor", datacenter));
+ }
+ });
+ return merged;
+ }
- if (!replicationStrategy.equals(ReplicationStrategy.LocalStrategy) && options.isEmpty())
- {
- throw new RuntimeException(String.format("Could not find replication info in schema map: %s.", options));
- }
+ /**
+ * @return the total number of replicas across all datacenters, including transient (witness) replicas.
+ * Semantics are unchanged from before transient replica support was added.
+ */
+ public Integer getTotalReplicationFactor()
+ {
+ return replication.values().stream().mapToInt(ReplicaCounts::allReplicas).sum();
+ }
- for (Map.Entry<String, Integer> entry : options.entrySet())
+ /**
+ * @return the number of replicas across all datacenters that hold the full data set, i.e. the total
+ * replication factor minus transient (witness) replicas
+ */
+ public Integer getFullReplicationFactor()
+ {
+ return replication.values().stream().mapToInt(ReplicaCounts::fullReplicas).sum();
+ }
+
+ /**
+ * @return the number of transient (witness) replicas across all datacenters, {@code 0} when none are configured
+ */
+ public Integer getTransientReplicationFactor()
+ {
+ return replication.values().stream().mapToInt(ReplicaCounts::transientReplicas).sum();
+ }
+
+ /**
+ * @return {@code true} if any datacenter is configured with transient (witness) replicas
+ */
+ public boolean hasTransientReplicas()
+ {
+ return replication.values().stream().anyMatch(counts -> counts.transientReplicas() > 0);
+ }
+
+ /**
+ * @param datacenter the datacenter to look up
+ * @return the number of transient (witness) replicas in {@code datacenter}, {@code 0} when none are configured
+ */
+ public int getTransientReplicas(@NotNull String datacenter)
+ {
+ ReplicaCounts counts = replication.get(datacenter);
+ return counts == null ? 0 : counts.transientReplicas();
+ }
+
+ /**
+ * @param datacenter the datacenter to look up
+ * @return the number of replicas in {@code datacenter} holding the full data set
+ * @throws IllegalArgumentException when {@code datacenter} has no replication factor
+ */
+ public int getFullReplicas(@NotNull String datacenter)
+ {
+ return counts(datacenter).fullReplicas();
+ }
+
+ private ReplicaCounts counts(@NotNull String datacenter)
+ {
+ ReplicaCounts counts = replication.get(datacenter);
+ if (counts == null)
{
- if ("class".equals(entry.getKey()))
- {
- continue;
- }
- this.options.put(entry.getKey(), entry.getValue());
+ throw new IllegalArgumentException(String.format("Datacenter %s not found in replication factor %s",
+ datacenter, replication.keySet()));
}
+ return counts;
}
- public Integer getTotalReplicationFactor()
+ /**
+ * @return per-datacenter replica counts, unmodifiable
+ */
+ @NotNull
+ public Map<String, ReplicaCounts> getReplication()
{
- return options.values().stream()
- .mapToInt(Integer::intValue)
- .sum();
+ return replication;
}
+ /**
+ * @return per-datacenter total replica counts, including transient (witness) replicas. Unmodifiable, and derived
+ * from {@link #getReplication()}.
+ */
@NotNull
public Map<String, Integer> getOptions()
{
- return options;
+ Map<String, Integer> options = new LinkedHashMap<>(replication.size());
Review Comment:
Similarly shall we precompute these and return here, instead of compute on every call
##########
cassandra-analytics-common/src/main/java/org/apache/cassandra/spark/data/ReplicationFactor.java:
##########
@@ -106,62 +110,209 @@ public static ReplicationFactor simpleStrategy(int rf)
@NotNull
private final ReplicationStrategy replicationStrategy;
+ /**
+ * Per-datacenter replica counts. Holding the total and the transient count together, rather than in two
+ * parallel maps, means the two cannot drift apart.
+ */
@NotNull
- private final Map<String, Integer> options;
+ private final Map<String, ReplicaCounts> replication;
+ /**
+ * Parses a raw replication map. A value that cannot be parsed, or that Cassandra itself would reject, raises
+ * {@link IllegalArgumentException} naming the offending datacenter: a partial replication factor is not usable
+ * and reporting it here avoids a misleading failure later, such as "DC not found in replication factor".
+ *
+ * @param options the raw replication map, including the {@code class} entry
+ * @throws IllegalArgumentException when any replication value cannot be parsed
+ */
public ReplicationFactor(@NotNull Map<String, String> options)
{
- this.replicationStrategy = ReplicationFactor.ReplicationStrategy.getEnum(options.get("class"));
- this.options = new LinkedHashMap<>(options.size());
- for (Map.Entry<String, String> entry : options.entrySet())
+ this(ReplicationStrategy.getEnum(options.get("class")), parse(options), options);
+ }
+
+ public ReplicationFactor(@NotNull ReplicationStrategy replicationStrategy, @NotNull Map<String, Integer> options)
+ {
+ this(replicationStrategy, options, Collections.emptyMap());
+ }
+
+ public ReplicationFactor(@NotNull ReplicationStrategy replicationStrategy,
+ @NotNull Map<String, Integer> options,
+ @NotNull Map<String, Integer> transientOptions)
+ {
+ this(replicationStrategy, merge(options, transientOptions), options);
+ }
+
+ /**
+ * Canonical constructor. Every other constructor resolves its input to per-datacenter counts and delegates here.
+ *
+ * @param replicationStrategy the replication strategy
+ * @param replication per-datacenter replica counts, already validated individually
+ * @param raw the caller's original input, used only in the error message
+ */
+ private ReplicationFactor(@NotNull ReplicationStrategy replicationStrategy,
+ @NotNull Map<String, ReplicaCounts> replication,
+ @NotNull Object raw)
+ {
+ // A strategy other than LocalStrategy with no datacenter entries is not usable
+ if (replicationStrategy != ReplicationStrategy.LocalStrategy && replication.isEmpty())
{
- if ("class".equals(entry.getKey()))
+ throw new IllegalArgumentException("Could not find replication info in schema map: " + raw);
+ }
+ this.replicationStrategy = replicationStrategy;
+ this.replication = Collections.unmodifiableMap(new LinkedHashMap<>(replication));
+ }
+
+ /**
+ * Resolves raw string values, e.g. {@code "3"} or {@code "3/1"}, to per-datacenter counts.
+ */
+ private static Map<String, ReplicaCounts> parse(@NotNull Map<String, String> options)
+ {
+ Map<String, ReplicaCounts> parsed = new LinkedHashMap<>(options.size());
+ options.forEach((datacenter, value) -> {
+ if ("class".equals(datacenter))
{
- continue;
+ return;
}
-
try
{
- this.options.put(entry.getKey(), Integer.parseInt(entry.getValue()));
+ parsed.put(datacenter, ReplicaCounts.parse(value));
}
- catch (NumberFormatException exception)
+ catch (IllegalArgumentException exception)
{
- LOGGER.warn("Could not parse replication option: {} = {}", entry.getKey(), entry.getValue());
+ throw new IllegalArgumentException(String.format("Could not parse replication option: %s = %s",
+ datacenter, value), exception);
}
- }
+ });
+ return parsed;
}
- public ReplicationFactor(@NotNull ReplicationStrategy replicationStrategy, @NotNull Map<String, Integer> options)
+ /**
+ * Resolves separate total and transient maps to per-datacenter counts, rejecting a transient entry for a
+ * datacenter that has no replication factor.
+ */
+ private static Map<String, ReplicaCounts> merge(@NotNull Map<String, Integer> options,
+ @NotNull Map<String, Integer> transientOptions)
{
- this.replicationStrategy = replicationStrategy;
- this.options = new LinkedHashMap<>(options.size());
+ Map<String, ReplicaCounts> merged = new LinkedHashMap<>(options.size());
+ options.forEach((datacenter, allReplicas) -> {
+ if (!"class".equals(datacenter))
+ {
+ merged.put(datacenter,
+ ReplicaCounts.of(datacenter, allReplicas, transientOptions.getOrDefault(datacenter, 0)));
+ }
+ });
+ transientOptions.forEach((datacenter, transientReplicas) -> {
+ if (!"class".equals(datacenter) && transientReplicas != null && transientReplicas != 0
+ && !merged.containsKey(datacenter))
+ {
+ throw new IllegalArgumentException(String.format(
+ "Transient replicas specified for %s but it has no replication factor", datacenter));
+ }
+ });
+ return merged;
+ }
- if (!replicationStrategy.equals(ReplicationStrategy.LocalStrategy) && options.isEmpty())
- {
- throw new RuntimeException(String.format("Could not find replication info in schema map: %s.", options));
- }
+ /**
+ * @return the total number of replicas across all datacenters, including transient (witness) replicas.
+ * Semantics are unchanged from before transient replica support was added.
+ */
+ public Integer getTotalReplicationFactor()
+ {
+ return replication.values().stream().mapToInt(ReplicaCounts::allReplicas).sum();
+ }
- for (Map.Entry<String, Integer> entry : options.entrySet())
+ /**
+ * @return the number of replicas across all datacenters that hold the full data set, i.e. the total
+ * replication factor minus transient (witness) replicas
+ */
+ public Integer getFullReplicationFactor()
+ {
+ return replication.values().stream().mapToInt(ReplicaCounts::fullReplicas).sum();
+ }
+
+ /**
+ * @return the number of transient (witness) replicas across all datacenters, {@code 0} when none are configured
+ */
+ public Integer getTransientReplicationFactor()
+ {
+ return replication.values().stream().mapToInt(ReplicaCounts::transientReplicas).sum();
+ }
+
+ /**
+ * @return {@code true} if any datacenter is configured with transient (witness) replicas
+ */
+ public boolean hasTransientReplicas()
+ {
+ return replication.values().stream().anyMatch(counts -> counts.transientReplicas() > 0);
+ }
+
+ /**
+ * @param datacenter the datacenter to look up
+ * @return the number of transient (witness) replicas in {@code datacenter}, {@code 0} when none are configured
+ */
+ public int getTransientReplicas(@NotNull String datacenter)
+ {
+ ReplicaCounts counts = replication.get(datacenter);
+ return counts == null ? 0 : counts.transientReplicas();
+ }
+
+ /**
+ * @param datacenter the datacenter to look up
+ * @return the number of replicas in {@code datacenter} holding the full data set
+ * @throws IllegalArgumentException when {@code datacenter} has no replication factor
+ */
+ public int getFullReplicas(@NotNull String datacenter)
+ {
+ return counts(datacenter).fullReplicas();
+ }
+
+ private ReplicaCounts counts(@NotNull String datacenter)
+ {
+ ReplicaCounts counts = replication.get(datacenter);
+ if (counts == null)
{
- if ("class".equals(entry.getKey()))
- {
- continue;
- }
- this.options.put(entry.getKey(), entry.getValue());
+ throw new IllegalArgumentException(String.format("Datacenter %s not found in replication factor %s",
Review Comment:
We seem to throw this only for full replica count extraction and not for transient replica, any reason why?
##########
cassandra-analytics-common/src/main/java/org/apache/cassandra/spark/data/ReplicationFactor.java:
##########
@@ -106,62 +110,209 @@ public static ReplicationFactor simpleStrategy(int rf)
@NotNull
private final ReplicationStrategy replicationStrategy;
+ /**
+ * Per-datacenter replica counts. Holding the total and the transient count together, rather than in two
+ * parallel maps, means the two cannot drift apart.
+ */
@NotNull
- private final Map<String, Integer> options;
+ private final Map<String, ReplicaCounts> replication;
+ /**
+ * Parses a raw replication map. A value that cannot be parsed, or that Cassandra itself would reject, raises
+ * {@link IllegalArgumentException} naming the offending datacenter: a partial replication factor is not usable
+ * and reporting it here avoids a misleading failure later, such as "DC not found in replication factor".
+ *
+ * @param options the raw replication map, including the {@code class} entry
+ * @throws IllegalArgumentException when any replication value cannot be parsed
+ */
public ReplicationFactor(@NotNull Map<String, String> options)
{
- this.replicationStrategy = ReplicationFactor.ReplicationStrategy.getEnum(options.get("class"));
- this.options = new LinkedHashMap<>(options.size());
- for (Map.Entry<String, String> entry : options.entrySet())
+ this(ReplicationStrategy.getEnum(options.get("class")), parse(options), options);
+ }
+
+ public ReplicationFactor(@NotNull ReplicationStrategy replicationStrategy, @NotNull Map<String, Integer> options)
+ {
+ this(replicationStrategy, options, Collections.emptyMap());
+ }
+
+ public ReplicationFactor(@NotNull ReplicationStrategy replicationStrategy,
+ @NotNull Map<String, Integer> options,
+ @NotNull Map<String, Integer> transientOptions)
+ {
+ this(replicationStrategy, merge(options, transientOptions), options);
+ }
+
+ /**
+ * Canonical constructor. Every other constructor resolves its input to per-datacenter counts and delegates here.
+ *
+ * @param replicationStrategy the replication strategy
+ * @param replication per-datacenter replica counts, already validated individually
+ * @param raw the caller's original input, used only in the error message
+ */
+ private ReplicationFactor(@NotNull ReplicationStrategy replicationStrategy,
+ @NotNull Map<String, ReplicaCounts> replication,
+ @NotNull Object raw)
+ {
+ // A strategy other than LocalStrategy with no datacenter entries is not usable
+ if (replicationStrategy != ReplicationStrategy.LocalStrategy && replication.isEmpty())
{
- if ("class".equals(entry.getKey()))
+ throw new IllegalArgumentException("Could not find replication info in schema map: " + raw);
+ }
+ this.replicationStrategy = replicationStrategy;
+ this.replication = Collections.unmodifiableMap(new LinkedHashMap<>(replication));
+ }
+
+ /**
+ * Resolves raw string values, e.g. {@code "3"} or {@code "3/1"}, to per-datacenter counts.
+ */
+ private static Map<String, ReplicaCounts> parse(@NotNull Map<String, String> options)
+ {
+ Map<String, ReplicaCounts> parsed = new LinkedHashMap<>(options.size());
+ options.forEach((datacenter, value) -> {
+ if ("class".equals(datacenter))
{
- continue;
+ return;
}
-
try
{
- this.options.put(entry.getKey(), Integer.parseInt(entry.getValue()));
+ parsed.put(datacenter, ReplicaCounts.parse(value));
}
- catch (NumberFormatException exception)
+ catch (IllegalArgumentException exception)
{
- LOGGER.warn("Could not parse replication option: {} = {}", entry.getKey(), entry.getValue());
+ throw new IllegalArgumentException(String.format("Could not parse replication option: %s = %s",
+ datacenter, value), exception);
}
- }
+ });
+ return parsed;
}
- public ReplicationFactor(@NotNull ReplicationStrategy replicationStrategy, @NotNull Map<String, Integer> options)
+ /**
+ * Resolves separate total and transient maps to per-datacenter counts, rejecting a transient entry for a
+ * datacenter that has no replication factor.
+ */
+ private static Map<String, ReplicaCounts> merge(@NotNull Map<String, Integer> options,
+ @NotNull Map<String, Integer> transientOptions)
{
- this.replicationStrategy = replicationStrategy;
- this.options = new LinkedHashMap<>(options.size());
+ Map<String, ReplicaCounts> merged = new LinkedHashMap<>(options.size());
+ options.forEach((datacenter, allReplicas) -> {
+ if (!"class".equals(datacenter))
+ {
+ merged.put(datacenter,
+ ReplicaCounts.of(datacenter, allReplicas, transientOptions.getOrDefault(datacenter, 0)));
+ }
+ });
+ transientOptions.forEach((datacenter, transientReplicas) -> {
+ if (!"class".equals(datacenter) && transientReplicas != null && transientReplicas != 0
+ && !merged.containsKey(datacenter))
+ {
+ throw new IllegalArgumentException(String.format(
+ "Transient replicas specified for %s but it has no replication factor", datacenter));
+ }
+ });
+ return merged;
+ }
- if (!replicationStrategy.equals(ReplicationStrategy.LocalStrategy) && options.isEmpty())
- {
- throw new RuntimeException(String.format("Could not find replication info in schema map: %s.", options));
- }
+ /**
+ * @return the total number of replicas across all datacenters, including transient (witness) replicas.
+ * Semantics are unchanged from before transient replica support was added.
+ */
+ public Integer getTotalReplicationFactor()
+ {
+ return replication.values().stream().mapToInt(ReplicaCounts::allReplicas).sum();
+ }
- for (Map.Entry<String, Integer> entry : options.entrySet())
+ /**
+ * @return the number of replicas across all datacenters that hold the full data set, i.e. the total
+ * replication factor minus transient (witness) replicas
+ */
+ public Integer getFullReplicationFactor()
+ {
+ return replication.values().stream().mapToInt(ReplicaCounts::fullReplicas).sum();
+ }
+
+ /**
+ * @return the number of transient (witness) replicas across all datacenters, {@code 0} when none are configured
+ */
+ public Integer getTransientReplicationFactor()
+ {
+ return replication.values().stream().mapToInt(ReplicaCounts::transientReplicas).sum();
+ }
+
+ /**
+ * @return {@code true} if any datacenter is configured with transient (witness) replicas
+ */
+ public boolean hasTransientReplicas()
+ {
+ return replication.values().stream().anyMatch(counts -> counts.transientReplicas() > 0);
+ }
+
+ /**
+ * @param datacenter the datacenter to look up
+ * @return the number of transient (witness) replicas in {@code datacenter}, {@code 0} when none are configured
+ */
+ public int getTransientReplicas(@NotNull String datacenter)
+ {
+ ReplicaCounts counts = replication.get(datacenter);
+ return counts == null ? 0 : counts.transientReplicas();
+ }
+
+ /**
+ * @param datacenter the datacenter to look up
+ * @return the number of replicas in {@code datacenter} holding the full data set
+ * @throws IllegalArgumentException when {@code datacenter} has no replication factor
+ */
+ public int getFullReplicas(@NotNull String datacenter)
+ {
+ return counts(datacenter).fullReplicas();
+ }
+
+ private ReplicaCounts counts(@NotNull String datacenter)
+ {
+ ReplicaCounts counts = replication.get(datacenter);
+ if (counts == null)
{
- if ("class".equals(entry.getKey()))
- {
- continue;
- }
- this.options.put(entry.getKey(), entry.getValue());
+ throw new IllegalArgumentException(String.format("Datacenter %s not found in replication factor %s",
+ datacenter, replication.keySet()));
}
+ return counts;
}
- public Integer getTotalReplicationFactor()
+ /**
+ * @return per-datacenter replica counts, unmodifiable
+ */
+ @NotNull
+ public Map<String, ReplicaCounts> getReplication()
{
- return options.values().stream()
- .mapToInt(Integer::intValue)
- .sum();
+ return replication;
}
+ /**
+ * @return per-datacenter total replica counts, including transient (witness) replicas. Unmodifiable, and derived
+ * from {@link #getReplication()}.
+ */
@NotNull
public Map<String, Integer> getOptions()
{
- return options;
+ Map<String, Integer> options = new LinkedHashMap<>(replication.size());
+ replication.forEach((datacenter, counts) -> options.put(datacenter, counts.allReplicas()));
+ return Collections.unmodifiableMap(options);
+ }
+
+ /**
+ * @return per-datacenter transient (witness) replica counts, unmodifiable. Datacenters without transient
+ * replicas are absent.
+ */
+ @NotNull
+ public Map<String, Integer> getTransientOptions()
+ {
+ Map<String, Integer> transientOptions = new LinkedHashMap<>();
Review Comment:
Same as above
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For additional commands, e-mail: commits-help@cassandra.apache.org
Re: [PR] CASSANALYTICS-194: Parse / replication factor fo… [cassandra-analytics]
Posted by "mansikhara (via GitHub)" <gi...@apache.org>.
mansikhara commented on code in PR #238:
URL: https://github.com/apache/cassandra-analytics/pull/238#discussion_r4032256575
##########
cassandra-analytics-common/src/main/java/org/apache/cassandra/spark/data/ReplicationFactor.java:
##########
@@ -106,62 +110,204 @@ public static ReplicationFactor simpleStrategy(int rf)
@NotNull
private final ReplicationStrategy replicationStrategy;
+ /**
+ * Per-datacenter replica counts. Holding the total and the transient count together, rather than in two
+ * parallel maps, means the two cannot drift apart.
+ */
@NotNull
- private final Map<String, Integer> options;
+ private final Map<String, ReplicaCounts> replication;
+ /**
+ * Parses a raw replication map. A value that cannot be parsed, or that Cassandra itself would reject, raises
+ * {@link IllegalArgumentException} naming the offending datacenter: a partial replication factor is not usable
+ * and reporting it here avoids a misleading failure later, such as "DC not found in replication factor".
+ *
+ * @param options the raw replication map, including the {@code class} entry
+ * @throws IllegalArgumentException when any replication value cannot be parsed
+ */
public ReplicationFactor(@NotNull Map<String, String> options)
{
this.replicationStrategy = ReplicationFactor.ReplicationStrategy.getEnum(options.get("class"));
- this.options = new LinkedHashMap<>(options.size());
+ Map<String, ReplicaCounts> parsed = new LinkedHashMap<>(options.size());
for (Map.Entry<String, String> entry : options.entrySet())
{
if ("class".equals(entry.getKey()))
{
continue;
}
-
try
{
- this.options.put(entry.getKey(), Integer.parseInt(entry.getValue()));
+ parsed.put(entry.getKey(), ReplicaCounts.parse(entry.getValue()));
}
- catch (NumberFormatException exception)
+ catch (IllegalArgumentException exception)
{
- LOGGER.warn("Could not parse replication option: {} = {}", entry.getKey(), entry.getValue());
+ throw new IllegalArgumentException(String.format("Could not parse replication option: %s = %s",
+ entry.getKey(), entry.getValue()), exception);
}
}
+ validateNotEmpty(this.replicationStrategy, parsed, options);
+ this.replication = Collections.unmodifiableMap(parsed);
}
public ReplicationFactor(@NotNull ReplicationStrategy replicationStrategy, @NotNull Map<String, Integer> options)
{
- this.replicationStrategy = replicationStrategy;
- this.options = new LinkedHashMap<>(options.size());
-
- if (!replicationStrategy.equals(ReplicationStrategy.LocalStrategy) && options.isEmpty())
- {
- throw new RuntimeException(String.format("Could not find replication info in schema map: %s.", options));
- }
+ this(replicationStrategy, options, Collections.emptyMap());
+ }
+ public ReplicationFactor(@NotNull ReplicationStrategy replicationStrategy,
+ @NotNull Map<String, Integer> options,
+ @NotNull Map<String, Integer> transientOptions)
+ {
+ this.replicationStrategy = replicationStrategy;
+ Map<String, ReplicaCounts> merged = new LinkedHashMap<>(options.size());
for (Map.Entry<String, Integer> entry : options.entrySet())
Review Comment:
Done! Good eye, thanks!
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For additional commands, e-mail: commits-help@cassandra.apache.org