kikocis/java-driver public
Changesets · Branches · Tags · Compare
| Changeset | 33520f173c298e1095e3d3f45b725d86157999f13fb31ec8071b1dcbcd016550 |
|---|---|
| Author | olim7t <omichallat+github@gmail.com> · 2014-12-01 11:32 +01:00 |
| Committer | olim7t <omichallat+github@gmail.com> · 2015-02-19 14:57 +01:00 |
| Parents | b1ca3ae13f03 |
21 files changed
modified driver-core/CHANGELOG.rst +1 −0
| @@ -7,6 +7,7 @@ | ||
| 7 | 7 | - [new feature] Add AddressTranslater for EC2 multi-region deployment (JAVA-518) |
| 8 | 8 | - [improvement] Add connection heartbeat (JAVA-533) |
| 9 | 9 | - [improvement] Reduce level of logs on missing rpc_address (JAVA-568) |
| 10 | +- [improvement] Expose node token and range information (JAVA-312) | |
| 10 | 11 | |
| 11 | 12 | Merged from 2.0.9_fixes branch: |
| 12 | 13 |
modified driver-core/src/main/java/com/datastax/driver/core/ArrayBackedResultSet.java +15 −8
| @@ -40,10 +40,12 @@ | ||
| 40 | 40 | private static final Queue<List<ByteBuffer>> EMPTY_QUEUE = new ArrayDeque<List<ByteBuffer>>(0); |
| 41 | 41 | |
| 42 | 42 | protected final ColumnDefinitions metadata; |
| 43 | + protected final Token.Factory tokenFactory; | |
| 43 | 44 | private final boolean wasApplied; |
| 44 | 45 | |
| 45 | - private ArrayBackedResultSet(ColumnDefinitions metadata, List<ByteBuffer> firstRow) { | |
| 46 | + private ArrayBackedResultSet(ColumnDefinitions metadata, Token.Factory tokenFactory, List<ByteBuffer> firstRow) { | |
| 46 | 47 | this.metadata = metadata; |
| 48 | + this.tokenFactory = tokenFactory; | |
| 47 | 49 | this.wasApplied = checkWasApplied(firstRow, metadata); |
| 48 | 50 | } |
| 49 | 51 | |
| @@ -65,12 +67,15 @@ | ||
| 65 | 67 | columnDefs = r.metadata.columns; |
| 66 | 68 | } |
| 67 | 69 | |
| 70 | + Token.Factory tokenFactory = (session == null) ? null | |
| 71 | + : session.getCluster().getMetadata().tokenFactory(); | |
| 72 | + | |
| 68 | 73 | // info can be null only for internal calls, but we don't page those. We assert |
| 69 | 74 | // this explicitly because MultiPage implementation don't support info == null. |
| 70 | 75 | assert r.metadata.pagingState == null || info != null; |
| 71 | 76 | return r.metadata.pagingState == null |
| 72 | - ? new SinglePage(columnDefs, r.data, info) | |
| 73 | - : new MultiPage(columnDefs, r.data, info, r.metadata.pagingState, session, statement); | |
| 77 | + ? new SinglePage(columnDefs, tokenFactory, r.data, info) | |
| 78 | + : new MultiPage(columnDefs, tokenFactory, r.data, info, r.metadata.pagingState, session, statement); | |
| 74 | 79 | |
| 75 | 80 | case SET_KEYSPACE: |
| 76 | 81 | case SCHEMA_CHANGE: |
| @@ -89,7 +94,7 @@ | ||
| 89 | 94 | } |
| 90 | 95 | |
| 91 | 96 | private static ArrayBackedResultSet empty(ExecutionInfo info) { |
| 92 | - return new SinglePage(ColumnDefinitions.EMPTY, EMPTY_QUEUE, info); | |
| 97 | + return new SinglePage(ColumnDefinitions.EMPTY, null, EMPTY_QUEUE, info); | |
| 93 | 98 | } |
| 94 | 99 | |
| 95 | 100 | public ColumnDefinitions getColumnDefinitions() { |
| @@ -148,9 +153,10 @@ | ||
| 148 | 153 | private final ExecutionInfo info; |
| 149 | 154 | |
| 150 | 155 | private SinglePage(ColumnDefinitions metadata, |
| 156 | + Token.Factory tokenFactory, | |
| 151 | 157 | Queue<List<ByteBuffer>> rows, |
| 152 | 158 | ExecutionInfo info) { |
| 153 | - super(metadata, rows.peek()); | |
| 159 | + super(metadata, tokenFactory, rows.peek()); | |
| 154 | 160 | this.info = info; |
| 155 | 161 | this.rows = rows; |
| 156 | 162 | } |
| @@ -160,7 +166,7 @@ | ||
| 160 | 166 | } |
| 161 | 167 | |
| 162 | 168 | public Row one() { |
| 163 | - return ArrayBackedRow.fromData(metadata, rows.poll()); | |
| 169 | + return ArrayBackedRow.fromData(metadata, tokenFactory, rows.poll()); | |
| 164 | 170 | } |
| 165 | 171 | |
| 166 | 172 | public int getAvailableWithoutFetching() { |
| @@ -210,6 +216,7 @@ | ||
| 210 | 216 | private final Statement statement; |
| 211 | 217 | |
| 212 | 218 | private MultiPage(ColumnDefinitions metadata, |
| 219 | + Token.Factory tokenFactory, | |
| 213 | 220 | Queue<List<ByteBuffer>> rows, |
| 214 | 221 | ExecutionInfo info, |
| 215 | 222 | ByteBuffer pagingState, |
| @@ -219,7 +226,7 @@ | ||
| 219 | 226 | // Note: as of Cassandra 2.1.0, it turns out that the result of a CAS update is never paged, so |
| 220 | 227 | // we could hard-code the result of wasApplied in this class to "true". However, we can not be sure |
| 221 | 228 | // that this will never change, so apply the generic check by peeking at the first row. |
| 222 | - super(metadata, rows.peek()); | |
| 229 | + super(metadata, tokenFactory, rows.peek()); | |
| 223 | 230 | this.currentPage = rows; |
| 224 | 231 | this.infos.offer(info); |
| 225 | 232 | |
| @@ -235,7 +242,7 @@ | ||
| 235 | 242 | |
| 236 | 243 | public Row one() { |
| 237 | 244 | prepareNextRow(); |
| 238 | - return ArrayBackedRow.fromData(metadata, currentPage.poll()); | |
| 245 | + return ArrayBackedRow.fromData(metadata, tokenFactory, currentPage.poll()); | |
| 239 | 246 | } |
| 240 | 247 | |
| 241 | 248 | public int getAvailableWithoutFetching() { |
modified driver-core/src/main/java/com/datastax/driver/core/ArrayBackedRow.java +33 −3
| @@ -21,6 +21,7 @@ | ||
| 21 | 21 | import java.nio.ByteBuffer; |
| 22 | 22 | import java.util.*; |
| 23 | 23 | |
| 24 | +import com.datastax.driver.core.exceptions.DriverInternalError; | |
| 24 | 25 | import com.datastax.driver.core.exceptions.InvalidTypeException; |
| 25 | 26 | |
| 26 | 27 | /** |
| @@ -29,18 +30,20 @@ | ||
| 29 | 30 | class ArrayBackedRow implements Row { |
| 30 | 31 | |
| 31 | 32 | private final ColumnDefinitions metadata; |
| 33 | + private final Token.Factory tokenFactory; | |
| 32 | 34 | private final List<ByteBuffer> data; |
| 33 | 35 | |
| 34 | - private ArrayBackedRow(ColumnDefinitions metadata, List<ByteBuffer> data) { | |
| 36 | + private ArrayBackedRow(ColumnDefinitions metadata, Token.Factory tokenFactory, List<ByteBuffer> data) { | |
| 35 | 37 | this.metadata = metadata; |
| 38 | + this.tokenFactory = tokenFactory; | |
| 36 | 39 | this.data = data; |
| 37 | 40 | } |
| 38 | 41 | |
| 39 | - static Row fromData(ColumnDefinitions metadata, List<ByteBuffer> data) { | |
| 42 | + static Row fromData(ColumnDefinitions metadata, Token.Factory tokenFactory, List<ByteBuffer> data) { | |
| 40 | 43 | if (data == null) |
| 41 | 44 | return null; |
| 42 | 45 | |
| 43 | - return new ArrayBackedRow(metadata, data); | |
| 46 | + return new ArrayBackedRow(metadata, tokenFactory, data); | |
| 44 | 47 | } |
| 45 | 48 | |
| 46 | 49 | public ColumnDefinitions getColumnDefinitions() { |
| @@ -239,6 +242,33 @@ | ||
| 239 | 242 | return getInet(metadata.getFirstIdx(name)); |
| 240 | 243 | } |
| 241 | 244 | |
| 245 | + public Token getToken(int i) { | |
| 246 | + if (tokenFactory == null) | |
| 247 | + throw new DriverInternalError("Token factory not set. This should only happen at initialization time"); | |
| 248 | + | |
| 249 | + metadata.checkType(i, tokenFactory.getTokenType().getName()); | |
| 250 | + | |
| 251 | + ByteBuffer value = data.get(i); | |
| 252 | + if (value == null || value.remaining() == 0) | |
| 253 | + return null; | |
| 254 | + | |
| 255 | + return tokenFactory.deserialize(value); | |
| 256 | + } | |
| 257 | + | |
| 258 | + public Token getToken(String name) { | |
| 259 | + // first, try with `token(name)`, preserving case sensitivity | |
| 260 | + String tokenName = (name.length() >= 2 && name.charAt(0) == '"' && name.charAt(name.length() - 1) == '"') | |
| 261 | + ? "\"token(" + name.substring(1, name.length() - 1) + ")\"" | |
| 262 | + : "token(" + name + ")"; | |
| 263 | + int[] indexes = metadata.findAllIdx(tokenName); | |
| 264 | + if (indexes != null) { | |
| 265 | + return getToken(indexes[0]); | |
| 266 | + } | |
| 267 | + | |
| 268 | + // Otherwise, use normal name | |
| 269 | + return getToken(metadata.getFirstIdx(name)); | |
| 270 | + } | |
| 271 | + | |
| 242 | 272 | @SuppressWarnings("unchecked") |
| 243 | 273 | public <T> List<T> getList(int i, Class<T> elementsClass) { |
| 244 | 274 | DataType type = metadata.getType(i); |
modified driver-core/src/main/java/com/datastax/driver/core/BoundStatement.java +39 −0
| @@ -185,6 +185,9 @@ | ||
| 185 | 185 | } |
| 186 | 186 | break; |
| 187 | 187 | default: |
| 188 | + if (toSet instanceof Token) | |
| 189 | + toSet = ((Token)toSet).getValue(); | |
| 190 | + | |
| 188 | 191 | Class<?> providedClass = toSet.getClass(); |
| 189 | 192 | Class<?> expectedClass = columnType.getName().javaType; |
| 190 | 193 | if (!expectedClass.isAssignableFrom(providedClass)) |
| @@ -818,6 +821,42 @@ | ||
| 818 | 821 | return this; |
| 819 | 822 | } |
| 820 | 823 | |
| 824 | + /** | |
| 825 | + * Sets the {@code i}th value to the provided {@link Token}. | |
| 826 | + * | |
| 827 | + * @param i the index of the variable to set. | |
| 828 | + * @param v the value to set. | |
| 829 | + * @return this BoundStatement. | |
| 830 | + * | |
| 831 | + * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.preparedStatement().variables().size()}. | |
| 832 | + * @throws InvalidTypeException if column {@code i} is not of the type of the token's value. | |
| 833 | + */ | |
| 834 | + public BoundStatement setToken(int i, Token v) { | |
| 835 | + metadata().checkType(i, v.getType().getName()); | |
| 836 | + return setValue(i, v.getType().serialize(v.getValue())); | |
| 837 | + } | |
| 838 | + | |
| 839 | + /** | |
| 840 | + * Sets the value for (all occurrences of) variable {@code name} to the | |
| 841 | + * provided token. | |
| 842 | + * | |
| 843 | + * @param name the name of the variable to set; if multiple variables | |
| 844 | + * {@code name} are prepared, all of them are set. | |
| 845 | + * @param v the value to set. | |
| 846 | + * @return this BoundStatement. | |
| 847 | + * | |
| 848 | + * @throws IllegalArgumentException if {@code name} is not a prepared | |
| 849 | + * variable, that is, if {@code !this.preparedStatement().variables().names().contains(name)}. | |
| 850 | + * @throws InvalidTypeException if (any occurrence of) {@code name} is | |
| 851 | + * not of the type of the token's value. | |
| 852 | + */ | |
| 853 | + public BoundStatement setToken(String name, Token v) { | |
| 854 | + int[] indexes = metadata().getAllIdx(name); | |
| 855 | + for (int i = 0; i < indexes.length; i++) | |
| 856 | + setToken(indexes[i], v); | |
| 857 | + return this; | |
| 858 | + } | |
| 859 | + | |
| 821 | 860 | /** |
| 822 | 861 | * Sets the {@code i}th value to the provided list. |
| 823 | 862 | * <p> |
modified driver-core/src/main/java/com/datastax/driver/core/Host.java +16 −0
| @@ -17,6 +17,7 @@ | ||
| 17 | 17 | |
| 18 | 18 | import java.net.InetAddress; |
| 19 | 19 | import java.net.InetSocketAddress; |
| 20 | +import java.util.Set; | |
| 20 | 21 | import java.util.concurrent.atomic.AtomicReference; |
| 21 | 22 | import java.util.concurrent.locks.ReentrantLock; |
| 22 | 23 | |
| @@ -64,6 +65,8 @@ | ||
| 64 | 65 | // (partly because the 'System.local' doesn't have it for some weird reason for instance). |
| 65 | 66 | volatile InetAddress listenAddress; |
| 66 | 67 | |
| 68 | + private volatile Set<Token> tokens; | |
| 69 | + | |
| 67 | 70 | // ClusterMetadata keeps one Host object per inet address and we rely on this (more precisely, |
| 68 | 71 | // we rely on the fact that we can use Object equality as a valid equality), so don't use |
| 69 | 72 | // that constructor but ClusterMetadata.getHost instead. |
| @@ -156,6 +159,19 @@ | ||
| 156 | 159 | return cassandraVersion; |
| 157 | 160 | } |
| 158 | 161 | |
| 162 | + /** | |
| 163 | + * Returns the tokens that this host owns. | |
| 164 | + * | |
| 165 | + * @return the (immutable) set of tokens. | |
| 166 | + */ | |
| 167 | + public Set<Token> getTokens() { | |
| 168 | + return tokens; | |
| 169 | + } | |
| 170 | + | |
| 171 | + void setTokens(Set<Token> tokens) { | |
| 172 | + this.tokens = tokens; | |
| 173 | + } | |
| 174 | + | |
| 159 | 175 | /** |
| 160 | 176 | * Returns whether the host is considered up by the driver. |
| 161 | 177 | * <p> |
modified driver-core/src/main/java/com/datastax/driver/core/Metadata.java +143 −15
| @@ -15,7 +15,6 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | -import java.net.InetAddress; | |
| 19 | 18 | import java.net.InetSocketAddress; |
| 20 | 19 | import java.nio.ByteBuffer; |
| 21 | 20 | import java.util.*; |
| @@ -24,6 +23,7 @@ | ||
| 24 | 23 | import java.util.regex.Pattern; |
| 25 | 24 | |
| 26 | 25 | import com.google.common.collect.ImmutableSet; |
| 26 | +import com.google.common.collect.Maps; | |
| 27 | 27 | import org.slf4j.Logger; |
| 28 | 28 | import org.slf4j.LoggerFactory; |
| 29 | 29 | |
| @@ -234,19 +234,61 @@ | ||
| 234 | 234 | return '"' + id + '"'; |
| 235 | 235 | } |
| 236 | 236 | |
| 237 | + /** | |
| 238 | + * Returns the token ranges that define data distribution in the ring. | |
| 239 | + * <p> | |
| 240 | + * Note that this information is refreshed asynchronously by the control | |
| 241 | + * connection, when schema or ring topology changes. It might occasionally | |
| 242 | + * be stale. | |
| 243 | + * | |
| 244 | + * @return the token ranges. | |
| 245 | + */ | |
| 246 | + public Set<TokenRange> getTokenRanges() { | |
| 247 | + TokenMap current = tokenMap; | |
| 248 | + return (current == null) ? Collections.<TokenRange>emptySet() : current.tokenRanges; | |
| 249 | + } | |
| 250 | + | |
| 251 | + /** | |
| 252 | + * Returns the token ranges that are replicated on the given host, for the given | |
| 253 | + * keyspace. | |
| 254 | + * <p> | |
| 255 | + * Note that this information is refreshed asynchronously by the control | |
| 256 | + * connection, when schema or ring topology changes. It might occasionally | |
| 257 | + * be stale (or even empty). | |
| 258 | + * | |
| 259 | + * @param keyspace the name of the keyspace to get token ranges for. | |
| 260 | + * @param host the host. | |
| 261 | + * @return the (immutable) set of token ranges for {@code host} as known | |
| 262 | + * by the driver. | |
| 263 | + */ | |
| 264 | + public Set<TokenRange> getTokenRanges(String keyspace, Host host) { | |
| 265 | + keyspace = handleId(keyspace); | |
| 266 | + TokenMap current = tokenMap; | |
| 267 | + if (current == null) { | |
| 268 | + return Collections.emptySet(); | |
| 269 | + } else { | |
| 270 | + Map<Host, Set<TokenRange>> dcRanges = current.hostsToRanges.get(keyspace); | |
| 271 | + if (dcRanges == null) { | |
| 272 | + return Collections.emptySet(); | |
| 273 | + } else { | |
| 274 | + Set<TokenRange> ranges = dcRanges.get(host); | |
| 275 | + return (ranges == null) ? Collections.<TokenRange>emptySet() : ranges; | |
| 276 | + } | |
| 277 | + } | |
| 278 | + } | |
| 279 | + | |
| 237 | 280 | /** |
| 238 | 281 | * Returns the set of hosts that are replica for a given partition key. |
| 239 | 282 | * <p> |
| 240 | - * Note that this method is a best effort method. Consumers should not rely | |
| 241 | - * too heavily on the result of this method not being stale (or even empty). | |
| 283 | + * Note that this information is refreshed asynchronously by the control | |
| 284 | + * connection, when schema or ring topology changes. It might occasionally | |
| 285 | + * be stale (or even empty). | |
| 242 | 286 | * |
| 243 | 287 | * @param keyspace the name of the keyspace to get replicas for. |
| 244 | 288 | * @param partitionKey the partition key for which to find the set of |
| 245 | 289 | * replica. |
| 246 | - * @return the (immutable) set of replicas for {@code partitionKey} as know | |
| 247 | - * by the driver. No strong guarantee is provided on the stalelessness of | |
| 248 | - * this information. It is also not guarantee that the returned set won't | |
| 249 | - * be empty (which is then some form of staleness). | |
| 290 | + * @return the (immutable) set of replicas for {@code partitionKey} as known | |
| 291 | + * by the driver. | |
| 250 | 292 | */ |
| 251 | 293 | public Set<Host> getReplicas(String keyspace, ByteBuffer partitionKey) { |
| 252 | 294 | keyspace = handleId(keyspace); |
| @@ -259,6 +301,28 @@ | ||
| 259 | 301 | } |
| 260 | 302 | } |
| 261 | 303 | |
| 304 | + /** | |
| 305 | + * Returns the set of hosts that are replica for a given token range. | |
| 306 | + * <p> | |
| 307 | + * Note that this information is refreshed asynchronously by the control | |
| 308 | + * connection, when schema or ring topology changes. It might occasionally | |
| 309 | + * be stale (or even empty). | |
| 310 | + * | |
| 311 | + * @param keyspace the name of the keyspace to get replicas for. | |
| 312 | + * @param range the token range. | |
| 313 | + * @return the (immutable) set of replicas for {@code range} as known by the driver. | |
| 314 | + */ | |
| 315 | + public Set<Host> getReplicas(String keyspace, TokenRange range) { | |
| 316 | + keyspace = handleId(keyspace); | |
| 317 | + TokenMap current = tokenMap; | |
| 318 | + if (current == null) { | |
| 319 | + return Collections.emptySet(); | |
| 320 | + } else { | |
| 321 | + Set<Host> hosts = current.getReplicas(keyspace, range.getEnd()); | |
| 322 | + return hosts == null ? Collections.<Host>emptySet() : hosts; | |
| 323 | + } | |
| 324 | + } | |
| 325 | + | |
| 262 | 326 | /** |
| 263 | 327 | * The Cassandra name for the cluster connect to. |
| 264 | 328 | * |
| @@ -335,24 +399,42 @@ | ||
| 335 | 399 | return sb.toString(); |
| 336 | 400 | } |
| 337 | 401 | |
| 402 | + Token.Factory tokenFactory() { | |
| 403 | + TokenMap current = tokenMap; | |
| 404 | + return (current == null) ? null : current.factory; | |
| 405 | + } | |
| 406 | + | |
| 338 | 407 | static class TokenMap { |
| 339 | 408 | |
| 340 | 409 | private final Token.Factory factory; |
| 341 | 410 | private final Map<String, Map<Token, Set<Host>>> tokenToHosts; |
| 411 | + private final Map<String, Map<Host, Set<TokenRange>>> hostsToRanges; | |
| 342 | 412 | private final List<Token> ring; |
| 413 | + private final Set<TokenRange> tokenRanges; | |
| 343 | 414 | final Set<Host> hosts; |
| 344 | 415 | |
| 345 | - private TokenMap(Token.Factory factory, Map<String, Map<Token, Set<Host>>> tokenToHosts, List<Token> ring, Set<Host> hosts) { | |
| 416 | + private TokenMap(Token.Factory factory, | |
| 417 | + Map<Host, Set<Token>> primaryToTokens, | |
| 418 | + Map<String, Map<Token, Set<Host>>> tokenToHosts, | |
| 419 | + Map<String, Map<Host, Set<TokenRange>>> hostsToRanges, | |
| 420 | + List<Token> ring, Set<TokenRange> tokenRanges, Set<Host> hosts) { | |
| 346 | 421 | this.factory = factory; |
| 347 | 422 | this.tokenToHosts = tokenToHosts; |
| 423 | + this.hostsToRanges = hostsToRanges; | |
| 348 | 424 | this.ring = ring; |
| 425 | + this.tokenRanges = tokenRanges; | |
| 349 | 426 | this.hosts = hosts; |
| 427 | + for (Map.Entry<Host, Set<Token>> entry : primaryToTokens.entrySet()) { | |
| 428 | + Host host = entry.getKey(); | |
| 429 | + host.setTokens(ImmutableSet.copyOf(entry.getValue())); | |
| 430 | + } | |
| 350 | 431 | } |
| 351 | 432 | |
| 352 | 433 | public static TokenMap build(Token.Factory factory, Map<Host, Collection<String>> allTokens, Collection<KeyspaceMetadata> keyspaces) { |
| 353 | 434 | |
| 354 | 435 | Set<Host> hosts = allTokens.keySet(); |
| 355 | 436 | Map<Token, Host> tokenToPrimary = new HashMap<Token, Host>(); |
| 437 | + Map<Host, Set<Token>> primaryToTokens = new HashMap<Host, Set<Token>>(); | |
| 356 | 438 | Set<Token> allSorted = new TreeSet<Token>(); |
| 357 | 439 | |
| 358 | 440 | for (Map.Entry<Host, Collection<String>> entry : allTokens.entrySet()) { |
| @@ -362,6 +444,12 @@ | ||
| 362 | 444 | Token t = factory.fromString(tokenStr); |
| 363 | 445 | allSorted.add(t); |
| 364 | 446 | tokenToPrimary.put(t, host); |
| 447 | + Set<Token> hostTokens = primaryToTokens.get(host); | |
| 448 | + if (hostTokens == null) { | |
| 449 | + hostTokens = new HashSet<Token>(); | |
| 450 | + primaryToTokens.put(host, hostTokens); | |
| 451 | + } | |
| 452 | + hostTokens.add(t); | |
| 365 | 453 | } catch (IllegalArgumentException e) { |
| 366 | 454 | // If we failed parsing that token, skip it |
| 367 | 455 | } |
| @@ -369,18 +457,23 @@ | ||
| 369 | 457 | } |
| 370 | 458 | |
| 371 | 459 | List<Token> ring = new ArrayList<Token>(allSorted); |
| 460 | + Set<TokenRange> tokenRanges = makeTokenRanges(ring, factory); | |
| 372 | 461 | |
| 373 | 462 | Map<String, Map<Token, Set<Host>>> tokenToHosts = new HashMap<String, Map<Token, Set<Host>>>(); |
| 463 | + Map<String, Map<Host, Set<TokenRange>>> hostsToRanges = new HashMap<String, Map<Host, Set<TokenRange>>>(); | |
| 374 | 464 | for (KeyspaceMetadata keyspace : keyspaces) |
| 375 | 465 | { |
| 376 | 466 | ReplicationStrategy strategy = keyspace.replicationStrategy(); |
| 377 | - if (strategy == null) { | |
| 378 | - tokenToHosts.put(keyspace.getName(), makeNonReplicatedMap(tokenToPrimary)); | |
| 379 | - } else { | |
| 380 | - tokenToHosts.put(keyspace.getName(), strategy.computeTokenToReplicaMap(tokenToPrimary, ring)); | |
| 381 | - } | |
| 467 | + Map<Token, Set<Host>> ksTokens = (strategy == null) | |
| 468 | + ? makeNonReplicatedMap(tokenToPrimary) | |
| 469 | + : strategy.computeTokenToReplicaMap(tokenToPrimary, ring); | |
| 470 | + | |
| 471 | + tokenToHosts.put(keyspace.getName(), ksTokens); | |
| 472 | + | |
| 473 | + Map<Host, Set<TokenRange>> ksRanges = computeHostsToRangesMap(tokenRanges, ksTokens, hosts.size()); | |
| 474 | + hostsToRanges.put(keyspace.getName(), ksRanges); | |
| 382 | 475 | } |
| 383 | - return new TokenMap(factory, tokenToHosts, ring, hosts); | |
| 476 | + return new TokenMap(factory, primaryToTokens, tokenToHosts, hostsToRanges, ring, tokenRanges, hosts); | |
| 384 | 477 | } |
| 385 | 478 | |
| 386 | 479 | private Set<Host> getReplicas(String keyspace, Token token) { |
| @@ -389,7 +482,12 @@ | ||
| 389 | 482 | if (keyspaceHosts == null) |
| 390 | 483 | return Collections.emptySet(); |
| 391 | 484 | |
| 392 | - // Find the primary replica | |
| 485 | + // If the token happens to be one of the "primary" tokens, get result directly | |
| 486 | + Set<Host> hosts = keyspaceHosts.get(token); | |
| 487 | + if (hosts != null) | |
| 488 | + return hosts; | |
| 489 | + | |
| 490 | + // Otherwise, find closest "primary" token on the ring | |
| 393 | 491 | int i = Collections.binarySearch(ring, token); |
| 394 | 492 | if (i < 0) { |
| 395 | 493 | i = -i - 1; |
| @@ -406,5 +504,35 @@ | ||
| 406 | 504 | output.put(entry.getKey(), ImmutableSet.of(entry.getValue())); |
| 407 | 505 | return output; |
| 408 | 506 | } |
| 507 | + | |
| 508 | + private static Set<TokenRange> makeTokenRanges(List<Token> ring, Token.Factory factory) { | |
| 509 | + ImmutableSet.Builder<TokenRange> builder = ImmutableSet.builder(); | |
| 510 | + for (int i = 0; i < ring.size(); i++) { | |
| 511 | + Token start = ring.get(i); | |
| 512 | + Token end = ring.get((i + 1) % ring.size()); | |
| 513 | + builder.add(new TokenRange(start, end, factory)); | |
| 514 | + } | |
| 515 | + return builder.build(); | |
| 516 | + } | |
| 517 | + | |
| 518 | + private static Map<Host, Set<TokenRange>> computeHostsToRangesMap(Set<TokenRange> tokenRanges, Map<Token, Set<Host>> ksTokens, int hostCount) { | |
| 519 | + Map<Host, ImmutableSet.Builder<TokenRange>> builders = Maps.newHashMapWithExpectedSize(hostCount); | |
| 520 | + for (TokenRange range : tokenRanges) { | |
| 521 | + Set<Host> replicas = ksTokens.get(range.getEnd()); | |
| 522 | + for (Host host : replicas) { | |
| 523 | + ImmutableSet.Builder<TokenRange> hostRanges = builders.get(host); | |
| 524 | + if (hostRanges == null) { | |
| 525 | + hostRanges = ImmutableSet.builder(); | |
| 526 | + builders.put(host, hostRanges); | |
| 527 | + } | |
| 528 | + hostRanges.add(range); | |
| 529 | + } | |
| 530 | + } | |
| 531 | + Map<Host, Set<TokenRange>> ksRanges = Maps.newHashMapWithExpectedSize(hostCount); | |
| 532 | + for (Map.Entry<Host, ImmutableSet.Builder<TokenRange>> entry : builders.entrySet()) { | |
| 533 | + ksRanges.put(entry.getKey(), entry.getValue().build()); | |
| 534 | + } | |
| 535 | + return ksRanges; | |
| 536 | + } | |
| 409 | 537 | } |
| 410 | 538 | } |
modified driver-core/src/main/java/com/datastax/driver/core/Row.java +44 −0
| @@ -404,6 +404,50 @@ | ||
| 404 | 404 | */ |
| 405 | 405 | public InetAddress getInet(String name); |
| 406 | 406 | |
| 407 | + /** | |
| 408 | + * Returns the {@code i}th value of this row as a {@link Token}. | |
| 409 | + * | |
| 410 | + * @param i the index ({@code 0 <= i < size()}) of the column to retrieve. | |
| 411 | + * @return the value of the {@code i}th column in this row as an Token. | |
| 412 | + * If the value is NULL, {@code null} is returned. | |
| 413 | + * | |
| 414 | + * @throws IndexOutOfBoundsException if {@code i < 0 || i >= this.columns().size()}. | |
| 415 | + * @throws InvalidTypeException if column {@code i} is not of the type of token values | |
| 416 | + * for this cluster (this depends on the configured partitioner). | |
| 417 | + */ | |
| 418 | + public Token getToken(int i); | |
| 419 | + | |
| 420 | + /** | |
| 421 | + * Returns the value of column {@code name} as a {@link Token}. | |
| 422 | + * <p> | |
| 423 | + * This method will first try with {@code token(name)}, because in most cases the column | |
| 424 | + * is named that way since it results from the application of a CQL function: | |
| 425 | + * <pre> | |
| 426 | + * {@code | |
| 427 | + * ResultSet rs = session.execute("SELECT token(k) FROM my_table WHERE k = 1"); | |
| 428 | + * Token token = rs.one().getToken("k"); // retrieves token(k) | |
| 429 | + * } | |
| 430 | + * </pre> | |
| 431 | + * If that fails, it will try will {@code name}. This handles the case where the column | |
| 432 | + * was aliased: | |
| 433 | + * <pre> | |
| 434 | + * {@code | |
| 435 | + * ResultSet rs = session.execute("SELECT token(k) AS t FROM my_table WHERE k = 1"); | |
| 436 | + * Token token = rs.one().getToken("t"); | |
| 437 | + * } | |
| 438 | + * </pre> | |
| 439 | + * | |
| 440 | + * @param name the name of the column to retrieve. | |
| 441 | + * @return the value of column {@code name} as a Token. | |
| 442 | + * If the value is NULL, {@code null} is returned. | |
| 443 | + * | |
| 444 | + * @throws IllegalArgumentException if {@code name} is not part of the | |
| 445 | + * ResultSet this row is part of, i.e. if {@code !this.columns().names().contains(name)}. | |
| 446 | + * @throws InvalidTypeException if column {@code name} is not of the type of token values | |
| 447 | + * for this cluster (this depends on the configured partitioner). | |
| 448 | + */ | |
| 449 | + public Token getToken(String name); | |
| 450 | + | |
| 407 | 451 | /** |
| 408 | 452 | * Returns the {@code i}th value of this row as a list. |
| 409 | 453 | * |
modified driver-core/src/main/java/com/datastax/driver/core/SimpleStatement.java +5 −2
| @@ -92,11 +92,14 @@ | ||
| 92 | 92 | private static ByteBuffer[] convert(Object[] values) { |
| 93 | 93 | ByteBuffer[] serializedValues = new ByteBuffer[values.length]; |
| 94 | 94 | for (int i = 0; i < values.length; i++) { |
| 95 | + Object value = values[i]; | |
| 95 | 96 | try { |
| 96 | - serializedValues[i] = DataType.serializeValue(values[i]); | |
| 97 | + if (value instanceof Token) | |
| 98 | + value = ((Token)value).getValue(); | |
| 99 | + serializedValues[i] = DataType.serializeValue(value); | |
| 97 | 100 | } catch (IllegalArgumentException e) { |
| 98 | 101 | // Catch and rethrow to provide a more helpful error message (one that include which value is bad) |
| 99 | - throw new IllegalArgumentException(String.format("Value %d of type %s does not correspond to any CQL3 type", i, values[i].getClass())); | |
| 102 | + throw new IllegalArgumentException(String.format("Value %d of type %s does not correspond to any CQL3 type", i, value.getClass())); | |
| 100 | 103 | } |
| 101 | 104 | } |
| 102 | 105 | return serializedValues; |
modified driver-core/src/main/java/com/datastax/driver/core/Token.java +339 −19
| @@ -19,15 +19,35 @@ | ||
| 19 | 19 | import java.nio.ByteBuffer; |
| 20 | 20 | import java.security.MessageDigest; |
| 21 | 21 | import java.security.NoSuchAlgorithmException; |
| 22 | +import java.util.Arrays; | |
| 23 | +import java.util.List; | |
| 22 | 24 | |
| 23 | -/* | |
| 24 | - * It's not an interface because we don't want to expose it | |
| 25 | - * Note: we may want to expose this later if people use custom partitioner and want to be able to extend that. | |
| 26 | - * This is way premature however. | |
| 27 | - */ | |
| 28 | -abstract class Token implements Comparable<Token> { | |
| 25 | +import com.google.common.annotations.VisibleForTesting; | |
| 26 | +import com.google.common.collect.Lists; | |
| 27 | +import com.google.common.primitives.UnsignedBytes; | |
| 28 | + | |
| 29 | +import com.datastax.driver.core.utils.Bytes; | |
| 29 | 30 | |
| 30 | - public static Token.Factory getFactory(String partitionerName) { | |
| 31 | +/** | |
| 32 | + * A token on the Cassandra ring. | |
| 33 | + */ | |
| 34 | +public abstract class Token implements Comparable<Token> { | |
| 35 | + | |
| 36 | + /** | |
| 37 | + * Returns the data type of this token's value. | |
| 38 | + * | |
| 39 | + * @return the datatype. | |
| 40 | + */ | |
| 41 | + public abstract DataType getType(); | |
| 42 | + | |
| 43 | + /** | |
| 44 | + * Returns the raw value of this token. | |
| 45 | + * | |
| 46 | + * @return the value. | |
| 47 | + */ | |
| 48 | + public abstract Object getValue(); | |
| 49 | + | |
| 50 | + static Token.Factory getFactory(String partitionerName) { | |
| 31 | 51 | if (partitionerName.endsWith("Murmur3Partitioner")) |
| 32 | 52 | return M3PToken.FACTORY; |
| 33 | 53 | else if (partitionerName.endsWith("RandomPartitioner")) |
| @@ -38,16 +58,50 @@ | ||
| 38 | 58 | return null; |
| 39 | 59 | } |
| 40 | 60 | |
| 41 | - public interface Factory { | |
| 42 | - public Token fromString(String tokenStr); | |
| 43 | - public Token hash(ByteBuffer partitionKey); | |
| 61 | + static abstract class Factory { | |
| 62 | + abstract Token fromString(String tokenStr); | |
| 63 | + abstract DataType getTokenType(); | |
| 64 | + abstract Token deserialize(ByteBuffer buffer); | |
| 65 | + /** The minimum token is a special value that no key ever hashes to, it's used both as lower and upper bound. */ | |
| 66 | + abstract Token minToken(); | |
| 67 | + abstract Token hash(ByteBuffer partitionKey); | |
| 68 | + abstract List<Token> split(Token startToken, Token endToken, int numberOfSplits); | |
| 69 | + | |
| 70 | + // Base implementation for split | |
| 71 | + protected List<BigInteger> split(BigInteger start, BigInteger range, | |
| 72 | + BigInteger ringEnd, BigInteger ringLength, | |
| 73 | + int numberOfSplits) { | |
| 74 | + BigInteger[] tmp = range.divideAndRemainder(BigInteger.valueOf(numberOfSplits)); | |
| 75 | + BigInteger divider = tmp[0]; | |
| 76 | + int remainder = tmp[1].intValue(); | |
| 77 | + | |
| 78 | + List<BigInteger> results = Lists.newArrayListWithExpectedSize(numberOfSplits - 1); | |
| 79 | + BigInteger current = start; | |
| 80 | + BigInteger dividerPlusOne = (remainder == 0) ? null // won't be used | |
| 81 | + : divider.add(BigInteger.ONE); | |
| 82 | + | |
| 83 | + for (int i = 1; i < numberOfSplits; i++) { | |
| 84 | + current = current.add(remainder-- > 0 ? dividerPlusOne : divider); | |
| 85 | + if (ringEnd != null && current.compareTo(ringEnd) > 0) | |
| 86 | + current = current.subtract(ringLength); | |
| 87 | + results.add(current); | |
| 88 | + } | |
| 89 | + return results; | |
| 90 | + } | |
| 44 | 91 | } |
| 45 | 92 | |
| 46 | 93 | // Murmur3Partitioner tokens |
| 47 | 94 | static class M3PToken extends Token { |
| 48 | 95 | private final long value; |
| 49 | 96 | |
| 50 | - public static final Factory FACTORY = new Factory() { | |
| 97 | + public static final Factory FACTORY = new M3PTokenFactory(); | |
| 98 | + | |
| 99 | + private static class M3PTokenFactory extends Factory { | |
| 100 | + | |
| 101 | + private static final BigInteger RING_END = BigInteger.valueOf(Long.MAX_VALUE); | |
| 102 | + private static final BigInteger RING_LENGTH = RING_END.subtract(BigInteger.valueOf(Long.MIN_VALUE)); | |
| 103 | + public static final M3PToken MIN_TOKEN = new M3PToken(Long.MIN_VALUE); | |
| 104 | + public static final M3PToken MAX_TOKEN = new M3PToken(Long.MAX_VALUE); | |
| 51 | 105 | |
| 52 | 106 | private long getblock(ByteBuffer key, int offset, int index) { |
| 53 | 107 | int i_8 = index << 3; |
| @@ -152,17 +206,64 @@ | ||
| 152 | 206 | return new M3PToken(Long.parseLong(tokenStr)); |
| 153 | 207 | } |
| 154 | 208 | |
| 209 | + @Override | |
| 210 | + DataType getTokenType() { | |
| 211 | + return DataType.bigint(); | |
| 212 | + } | |
| 213 | + | |
| 214 | + @Override | |
| 215 | + Token deserialize(ByteBuffer buffer) { | |
| 216 | + return new M3PToken((Long) getTokenType().deserialize(buffer)); | |
| 217 | + } | |
| 218 | + | |
| 219 | + @Override | |
| 220 | + Token minToken() { | |
| 221 | + return MIN_TOKEN; | |
| 222 | + } | |
| 223 | + | |
| 155 | 224 | @Override |
| 156 | 225 | public M3PToken hash(ByteBuffer partitionKey) { |
| 157 | 226 | long v = murmur(partitionKey); |
| 158 | 227 | return new M3PToken(v == Long.MIN_VALUE ? Long.MAX_VALUE : v); |
| 159 | 228 | } |
| 160 | - }; | |
| 229 | + | |
| 230 | + @Override | |
| 231 | + List<Token> split(Token startToken, Token endToken, int numberOfSplits) { | |
| 232 | + // edge case: ]min, min] means the whole ring | |
| 233 | + if (startToken.equals(endToken) && startToken.equals(MIN_TOKEN)) | |
| 234 | + endToken = MAX_TOKEN; | |
| 235 | + | |
| 236 | + BigInteger start = BigInteger.valueOf(((M3PToken)startToken).value); | |
| 237 | + BigInteger end = BigInteger.valueOf(((M3PToken)endToken).value); | |
| 238 | + | |
| 239 | + BigInteger range = end.subtract(start); | |
| 240 | + if (range.compareTo(BigInteger.ZERO) < 0) | |
| 241 | + range = range.add(RING_LENGTH); | |
| 242 | + | |
| 243 | + List<BigInteger> values = super.split(start, range, | |
| 244 | + RING_END, RING_LENGTH, | |
| 245 | + numberOfSplits); | |
| 246 | + List<Token> tokens = Lists.newArrayListWithExpectedSize(values.size()); | |
| 247 | + for (BigInteger value : values) | |
| 248 | + tokens.add(new M3PToken(value.longValue())); | |
| 249 | + return tokens; | |
| 250 | + } | |
| 251 | + } | |
| 161 | 252 | |
| 162 | 253 | private M3PToken(long value) { |
| 163 | 254 | this.value = value; |
| 164 | 255 | } |
| 165 | 256 | |
| 257 | + @Override | |
| 258 | + public DataType getType() { | |
| 259 | + return FACTORY.getTokenType(); | |
| 260 | + } | |
| 261 | + | |
| 262 | + @Override | |
| 263 | + public Object getValue() { | |
| 264 | + return value; | |
| 265 | + } | |
| 266 | + | |
| 166 | 267 | @Override |
| 167 | 268 | public int compareTo(Token other) { |
| 168 | 269 | assert other instanceof M3PToken; |
| @@ -184,32 +285,186 @@ | ||
| 184 | 285 | public int hashCode() { |
| 185 | 286 | return (int)(value^(value>>>32)); |
| 186 | 287 | } |
| 288 | + | |
| 289 | + @Override | |
| 290 | + public String toString() { | |
| 291 | + return Long.toString(value); | |
| 292 | + } | |
| 187 | 293 | } |
| 188 | 294 | |
| 189 | 295 | // OPPartitioner tokens |
| 190 | 296 | static class OPPToken extends Token { |
| 297 | + | |
| 191 | 298 | private final ByteBuffer value; |
| 192 | 299 | |
| 193 | - public static final Factory FACTORY = new Factory() { | |
| 300 | + public static final Factory FACTORY = new OPPTokenFactory(); | |
| 301 | + | |
| 302 | + private static class OPPTokenFactory extends Factory { | |
| 303 | + private static final BigInteger TWO = BigInteger.valueOf(2); | |
| 304 | + private static final Token MIN_TOKEN = new OPPToken(ByteBuffer.allocate(0)); | |
| 305 | + | |
| 194 | 306 | @Override |
| 195 | 307 | public OPPToken fromString(String tokenStr) { |
| 196 | - return new OPPToken(TypeCodec.StringCodec.utf8Instance.serialize(tokenStr)); | |
| 308 | + String prefix = (tokenStr.length() % 2 == 0) ? "0x" : "0x0"; | |
| 309 | + ByteBuffer value = Bytes.fromHexString(prefix + tokenStr); | |
| 310 | + return new OPPToken(value); | |
| 311 | + } | |
| 312 | + | |
| 313 | + @Override | |
| 314 | + DataType getTokenType() { | |
| 315 | + return DataType.blob(); | |
| 316 | + } | |
| 317 | + | |
| 318 | + @Override | |
| 319 | + Token deserialize(ByteBuffer buffer) { | |
| 320 | + return new OPPToken(buffer); | |
| 321 | + } | |
| 322 | + | |
| 323 | + @Override | |
| 324 | + Token minToken() { | |
| 325 | + return MIN_TOKEN; | |
| 197 | 326 | } |
| 198 | 327 | |
| 199 | 328 | @Override |
| 200 | 329 | public OPPToken hash(ByteBuffer partitionKey) { |
| 201 | 330 | return new OPPToken(partitionKey); |
| 202 | 331 | } |
| 203 | - }; | |
| 204 | 332 | |
| 205 | - private OPPToken(ByteBuffer value) { | |
| 206 | - this.value = value; | |
| 333 | + @Override | |
| 334 | + public List<Token> split(Token startToken, Token endToken, int numberOfSplits) { | |
| 335 | + int tokenOrder = startToken.compareTo(endToken); | |
| 336 | + | |
| 337 | + // ]min,min] means the whole ring. However, since there is no "max token" with this partitioner, we can't come up | |
| 338 | + // with a magic end value that would cover the whole ring | |
| 339 | + if (tokenOrder == 0 && startToken.equals(MIN_TOKEN)) | |
| 340 | + throw new IllegalArgumentException("Cannot split whole ring with ordered partitioner"); | |
| 341 | + | |
| 342 | + OPPToken oppStartToken = (OPPToken)startToken; | |
| 343 | + OPPToken oppEndToken = (OPPToken)endToken; | |
| 344 | + | |
| 345 | + int significantBytes; | |
| 346 | + BigInteger start, end, range, ringEnd, ringLength; | |
| 347 | + BigInteger bigNumberOfSplits = BigInteger.valueOf(numberOfSplits); | |
| 348 | + if (tokenOrder < 0) { | |
| 349 | + // Since tokens are compared lexicographically, convert to integers using the largest length | |
| 350 | + // (ex: given 0x0A and 0x0BCD, switch to 0x0A00 and 0x0BCD) | |
| 351 | + significantBytes = Math.max(oppStartToken.value.capacity(), oppEndToken.value.capacity()); | |
| 352 | + | |
| 353 | + // If the number of splits does not fit in the difference between the two integers, use more bytes | |
| 354 | + // (ex: cannot fit 4 splits between 0x01 and 0x03, so switch to 0x0100 and 0x0300) | |
| 355 | + // At most 4 additional bytes will be needed, since numberOfSplits is an integer. | |
| 356 | + int addedBytes = 0; | |
| 357 | + while (true) { | |
| 358 | + start = toBigInteger(oppStartToken.value, significantBytes); | |
| 359 | + end = toBigInteger(oppEndToken.value, significantBytes); | |
| 360 | + range = end.subtract(start); | |
| 361 | + if (addedBytes == 4 || range.compareTo(bigNumberOfSplits) >= 0) | |
| 362 | + break; | |
| 363 | + significantBytes += 1; | |
| 364 | + addedBytes += 1; | |
| 365 | + } | |
| 366 | + ringEnd = ringLength = null; // won't be used | |
| 367 | + } else { | |
| 368 | + // Same logic except that we wrap around the ring | |
| 369 | + significantBytes = Math.max(oppStartToken.value.capacity(), oppEndToken.value.capacity()); | |
| 370 | + int addedBytes = 0; | |
| 371 | + while (true) { | |
| 372 | + start = toBigInteger(oppStartToken.value, significantBytes); | |
| 373 | + end = toBigInteger(oppEndToken.value, significantBytes); | |
| 374 | + ringLength = TWO.pow(significantBytes * 8); | |
| 375 | + ringEnd = ringLength.subtract(BigInteger.ONE); | |
| 376 | + range = end.subtract(start).add(ringLength); | |
| 377 | + if (addedBytes == 4 || range.compareTo(bigNumberOfSplits) >= 0) | |
| 378 | + break; | |
| 379 | + significantBytes += 1; | |
| 380 | + addedBytes += 1; | |
| 381 | + } | |
| 382 | + } | |
| 383 | + | |
| 384 | + List<BigInteger> values = super.split(start, range, | |
| 385 | + ringEnd, ringLength, | |
| 386 | + numberOfSplits); | |
| 387 | + List<Token> tokens = Lists.newArrayListWithExpectedSize(values.size()); | |
| 388 | + for (BigInteger value : values) | |
| 389 | + tokens.add(new OPPToken(toBytes(value, significantBytes))); | |
| 390 | + return tokens; | |
| 391 | + } | |
| 392 | + | |
| 393 | + // Convert a token's byte array to a number in order to perform computations. | |
| 394 | + // This depends on the number of "significant bytes" that we use to normalize all tokens to the same size. | |
| 395 | + // For example if the token is 0x01 but significantBytes is 2, the result is 8 (0x0100). | |
| 396 | + private BigInteger toBigInteger(ByteBuffer bb, int significantBytes) { | |
| 397 | + byte[] bytes = Bytes.getArray(bb); | |
| 398 | + byte[] target; | |
| 399 | + if (significantBytes != bytes.length) { | |
| 400 | + target = new byte[significantBytes]; | |
| 401 | + System.arraycopy(bytes, 0, target, 0, bytes.length); | |
| 402 | + } else | |
| 403 | + target = bytes; | |
| 404 | + return new BigInteger(1, target); | |
| 405 | + } | |
| 406 | + | |
| 407 | + // Convert a numeric representation back to a byte array. | |
| 408 | + // Again, the number of significant bytes matters: if the input value is 1 but significantBytes is 2, the | |
| 409 | + // expected result is 0x0001 (a simple conversion would produce 0x01). | |
| 410 | + protected ByteBuffer toBytes(BigInteger value, int significantBytes) { | |
| 411 | + byte[] rawBytes = value.toByteArray(); | |
| 412 | + byte[] result; | |
| 413 | + if (rawBytes.length == significantBytes) | |
| 414 | + result = rawBytes; | |
| 415 | + else { | |
| 416 | + result = new byte[significantBytes]; | |
| 417 | + int start, length; | |
| 418 | + if (rawBytes[0] == 0) { // that's a sign byte, ignore (it can cause rawBytes.length == significantBytes + 1) | |
| 419 | + start = 1; | |
| 420 | + length = rawBytes.length - 1; | |
| 421 | + } else { | |
| 422 | + start = 0; | |
| 423 | + length = rawBytes.length; | |
| 424 | + } | |
| 425 | + System.arraycopy(rawBytes, start, result, significantBytes - length, length); | |
| 426 | + } | |
| 427 | + return ByteBuffer.wrap(result); | |
| 428 | + } | |
| 429 | + } | |
| 430 | + | |
| 431 | + @VisibleForTesting | |
| 432 | + OPPToken(ByteBuffer value) { | |
| 433 | + this.value = stripTrailingZeroBytes(value); | |
| 434 | + } | |
| 435 | + | |
| 436 | + /** | |
| 437 | + * @return A new ByteBuffer from the input Buffer with any trailing 0-bytes stripped off. | |
| 438 | + */ | |
| 439 | + private static ByteBuffer stripTrailingZeroBytes(ByteBuffer b) { | |
| 440 | + byte result[] = Bytes.getArray(b); | |
| 441 | + int zeroIndex = result.length; | |
| 442 | + for(int i = result.length-1; i > 0; i--) { | |
| 443 | + if(result[i] == 0) { | |
| 444 | + zeroIndex = i; | |
| 445 | + } else { | |
| 446 | + break; | |
| 447 | + } | |
| 448 | + } | |
| 449 | + return ByteBuffer.wrap(result, 0, zeroIndex); | |
| 450 | + } | |
| 451 | + | |
| 452 | + @Override | |
| 453 | + public DataType getType() { | |
| 454 | + return FACTORY.getTokenType(); | |
| 455 | + } | |
| 456 | + | |
| 457 | + @Override | |
| 458 | + public Object getValue() { | |
| 459 | + return value; | |
| 207 | 460 | } |
| 208 | 461 | |
| 209 | 462 | @Override |
| 210 | 463 | public int compareTo(Token other) { |
| 211 | 464 | assert other instanceof OPPToken; |
| 212 | - return value.compareTo(((OPPToken)other).value); | |
| 465 | + return UnsignedBytes.lexicographicalComparator().compare( | |
| 466 | + Bytes.getArray(value), | |
| 467 | + Bytes.getArray(((OPPToken)other).value)); | |
| 213 | 468 | } |
| 214 | 469 | |
| 215 | 470 | @Override |
| @@ -226,6 +481,11 @@ | ||
| 226 | 481 | public int hashCode() { |
| 227 | 482 | return value.hashCode(); |
| 228 | 483 | } |
| 484 | + | |
| 485 | + @Override | |
| 486 | + public String toString() { | |
| 487 | + return Bytes.toHexString(value); | |
| 488 | + } | |
| 229 | 489 | } |
| 230 | 490 | |
| 231 | 491 | // RandomPartitioner tokens |
| @@ -233,7 +493,15 @@ | ||
| 233 | 493 | |
| 234 | 494 | private final BigInteger value; |
| 235 | 495 | |
| 236 | - public static final Factory FACTORY = new Factory() { | |
| 496 | + public static final Factory FACTORY = new RPTokenFactory(); | |
| 497 | + | |
| 498 | + private static class RPTokenFactory extends Factory { | |
| 499 | + | |
| 500 | + private static final BigInteger MIN_VALUE = BigInteger.ONE.negate(); | |
| 501 | + private static final BigInteger MAX_VALUE = BigInteger.valueOf(2).pow(127); | |
| 502 | + private static final BigInteger RING_LENGTH = MAX_VALUE.add(BigInteger.ONE); | |
| 503 | + private static final Token MIN_TOKEN = new RPToken(MIN_VALUE); | |
| 504 | + private static final Token MAX_TOKEN = new RPToken(MAX_VALUE); | |
| 237 | 505 | |
| 238 | 506 | private BigInteger md5(ByteBuffer data) { |
| 239 | 507 | try { |
| @@ -250,16 +518,63 @@ | ||
| 250 | 518 | return new RPToken(new BigInteger(tokenStr)); |
| 251 | 519 | } |
| 252 | 520 | |
| 521 | + @Override | |
| 522 | + DataType getTokenType() { | |
| 523 | + return DataType.varint(); | |
| 524 | + } | |
| 525 | + | |
| 526 | + @Override | |
| 527 | + Token deserialize(ByteBuffer buffer) { | |
| 528 | + return new RPToken((BigInteger)getTokenType().deserialize(buffer)); | |
| 529 | + } | |
| 530 | + | |
| 531 | + @Override | |
| 532 | + Token minToken() { | |
| 533 | + return MIN_TOKEN; | |
| 534 | + } | |
| 535 | + | |
| 253 | 536 | @Override |
| 254 | 537 | public RPToken hash(ByteBuffer partitionKey) { |
| 255 | 538 | return new RPToken(md5(partitionKey)); |
| 256 | 539 | } |
| 540 | + | |
| 541 | + @Override | |
| 542 | + List<Token> split(Token startToken, Token endToken, int numberOfSplits) { | |
| 543 | + // edge case: ]min, min] means the whole ring | |
| 544 | + if (startToken.equals(endToken) && startToken.equals(MIN_TOKEN)) | |
| 545 | + endToken = MAX_TOKEN; | |
| 546 | + | |
| 547 | + BigInteger start = ((RPToken)startToken).value; | |
| 548 | + BigInteger end = ((RPToken)endToken).value; | |
| 549 | + | |
| 550 | + BigInteger range = end.subtract(start); | |
| 551 | + if (range.compareTo(BigInteger.ZERO) < 0) | |
| 552 | + range = range.add(RING_LENGTH); | |
| 553 | + | |
| 554 | + List<BigInteger> values = super.split(start, range, | |
| 555 | + MAX_VALUE, RING_LENGTH, | |
| 556 | + numberOfSplits); | |
| 557 | + List<Token> tokens = Lists.newArrayListWithExpectedSize(values.size()); | |
| 558 | + for (BigInteger value : values) | |
| 559 | + tokens.add(new RPToken(value)); | |
| 560 | + return tokens; | |
| 561 | + } | |
| 257 | 562 | }; |
| 258 | 563 | |
| 259 | 564 | private RPToken(BigInteger value) { |
| 260 | 565 | this.value = value; |
| 261 | 566 | } |
| 262 | 567 | |
| 568 | + @Override | |
| 569 | + public DataType getType() { | |
| 570 | + return FACTORY.getTokenType(); | |
| 571 | + } | |
| 572 | + | |
| 573 | + @Override | |
| 574 | + public Object getValue() { | |
| 575 | + return value; | |
| 576 | + } | |
| 577 | + | |
| 263 | 578 | @Override |
| 264 | 579 | public int compareTo(Token other) { |
| 265 | 580 | assert other instanceof RPToken; |
| @@ -280,5 +595,10 @@ | ||
| 280 | 595 | public int hashCode() { |
| 281 | 596 | return value.hashCode(); |
| 282 | 597 | } |
| 598 | + | |
| 599 | + @Override | |
| 600 | + public String toString() { | |
| 601 | + return value.toString(); | |
| 602 | + } | |
| 283 | 603 | } |
| 284 | 604 | } |
added driver-core/src/main/java/com/datastax/driver/core/TokenRange.java +265 −0
| @@ -0,0 +1,265 @@ | ||
| 1 | +/* | |
| 2 | + * Copyright (C) 2012-2014 DataStax Inc. | |
| 3 | + * | |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); | |
| 5 | + * you may not use this file except in compliance with the License. | |
| 6 | + * You may obtain a copy of the License at | |
| 7 | + * | |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 | |
| 9 | + * | |
| 10 | + * Unless required by applicable law or agreed to in writing, software | |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, | |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 13 | + * See the License for the specific language governing permissions and | |
| 14 | + * limitations under the License. | |
| 15 | + */ | |
| 16 | +package com.datastax.driver.core; | |
| 17 | + | |
| 18 | +import java.util.ArrayList; | |
| 19 | +import java.util.List; | |
| 20 | + | |
| 21 | +import com.google.common.base.Objects; | |
| 22 | +import com.google.common.collect.ImmutableList; | |
| 23 | + | |
| 24 | +/** | |
| 25 | + * A range of tokens on the Cassandra ring. | |
| 26 | + * <p> | |
| 27 | + * A range is start-exclusive and end-inclusive. It is empty when start and end are the same token, except if that is the minimum | |
| 28 | + * token, in which case the range covers the whole ring (this is consistent with the behavior of CQL range queries). | |
| 29 | + * <p> | |
| 30 | + * Note that CQL does not handle wrapping. To query all partitions in a range, see {@link #unwrap()}. | |
| 31 | + */ | |
| 32 | +public final class TokenRange implements Comparable<TokenRange> { | |
| 33 | + private final Token start; | |
| 34 | + private final Token end; | |
| 35 | + private final Token.Factory factory; | |
| 36 | + | |
| 37 | + TokenRange(Token start, Token end, Token.Factory factory) { | |
| 38 | + this.start = start; | |
| 39 | + this.end = end; | |
| 40 | + this.factory = factory; | |
| 41 | + } | |
| 42 | + | |
| 43 | + /** | |
| 44 | + * Return the start of the range. | |
| 45 | + * | |
| 46 | + * @return the start of the range (exclusive). | |
| 47 | + */ | |
| 48 | + public Token getStart() { | |
| 49 | + return start; | |
| 50 | + } | |
| 51 | + | |
| 52 | + /** | |
| 53 | + * Return the end of the range. | |
| 54 | + * | |
| 55 | + * @return the end of the range (inclusive). | |
| 56 | + */ | |
| 57 | + public Token getEnd() { | |
| 58 | + return end; | |
| 59 | + } | |
| 60 | + | |
| 61 | + /** | |
| 62 | + * Splits this range into a number of smaller ranges of equal "size" (referring to the number of tokens, not the actual amount of data). | |
| 63 | + * <p> | |
| 64 | + * Splitting an empty range is not permitted. But note that, in edge cases, splitting a range might produce one or more empty ranges. | |
| 65 | + * | |
| 66 | + * @param numberOfSplits the number of splits to create. | |
| 67 | + * @return the splits. | |
| 68 | + * | |
| 69 | + * @throws IllegalArgumentException if the range is empty or if numberOfSplits < 1. | |
| 70 | + */ | |
| 71 | + public List<TokenRange> splitEvenly(int numberOfSplits) { | |
| 72 | + if (numberOfSplits < 1) | |
| 73 | + throw new IllegalArgumentException(String.format("numberOfSplits (%d) must be greater than 0.", numberOfSplits)); | |
| 74 | + if (isEmpty()) | |
| 75 | + throw new IllegalArgumentException("Can't split empty range " + this); | |
| 76 | + | |
| 77 | + List<TokenRange> tokenRanges = new ArrayList<TokenRange>(); | |
| 78 | + List<Token> splitPoints = factory.split(start, end, numberOfSplits); | |
| 79 | + Token splitStart = start; | |
| 80 | + for (Token splitEnd : splitPoints) { | |
| 81 | + tokenRanges.add(new TokenRange(splitStart, splitEnd, factory)); | |
| 82 | + splitStart = splitEnd; | |
| 83 | + } | |
| 84 | + tokenRanges.add(new TokenRange(splitStart, end, factory)); | |
| 85 | + return tokenRanges; | |
| 86 | + } | |
| 87 | + | |
| 88 | + /** | |
| 89 | + * Returns whether this range is empty. | |
| 90 | + * <p> | |
| 91 | + * A range is empty when start and end are the same token, except if that is the minimum token, | |
| 92 | + * in which case the range covers the whole ring (this is consistent with the behavior of CQL | |
| 93 | + * range queries). | |
| 94 | + * | |
| 95 | + * @return whether the range is empty. | |
| 96 | + */ | |
| 97 | + public boolean isEmpty() { | |
| 98 | + return start.equals(end) && !start.equals(factory.minToken()); | |
| 99 | + } | |
| 100 | + | |
| 101 | + /** | |
| 102 | + * Returns whether this range wraps around the end of the ring. | |
| 103 | + * | |
| 104 | + * @return whether this range wraps around. | |
| 105 | + */ | |
| 106 | + public boolean isWrappedAround() { | |
| 107 | + return start.compareTo(end) > 0 && !end.equals(factory.minToken()); | |
| 108 | + } | |
| 109 | + | |
| 110 | + /** | |
| 111 | + * Splits this range into a list of two non-wrapping ranges. This will return the range itself if it is | |
| 112 | + * non-wrapping, or two ranges otherwise. | |
| 113 | + * <p> | |
| 114 | + * For example: | |
| 115 | + * <ul> | |
| 116 | + * <li>{@code ]1,10]} unwraps to itself;</li> | |
| 117 | + * <li>{@code ]10,1]} unwraps to {@code ]10,min_token]} and {@code ]min_token,1]}.</li> | |
| 118 | + * </ul> | |
| 119 | + * <p> | |
| 120 | + * This is useful for CQL range queries, which do not handle wrapping: | |
| 121 | + * <pre> | |
| 122 | + * {@code | |
| 123 | + * List<Row> rows = new ArrayList<Row>(); | |
| 124 | + * for (TokenRange subRange : range.unwrap()) { | |
| 125 | + * ResultSet rs = session.execute("SELECT * FROM mytable WHERE token(pk) > ? and token(pk) <= ?", | |
| 126 | + * subRange.getStart(), subRange.getEnd()); | |
| 127 | + * rows.addAll(rs.all()); | |
| 128 | + * } | |
| 129 | + * }</pre> | |
| 130 | + * | |
| 131 | + * @return the list of non-wrapping ranges. | |
| 132 | + */ | |
| 133 | + public List<TokenRange> unwrap() { | |
| 134 | + if (isWrappedAround()) { | |
| 135 | + return ImmutableList.of( | |
| 136 | + new TokenRange(start, factory.minToken(), factory), | |
| 137 | + new TokenRange(factory.minToken(), end, factory)); | |
| 138 | + } else { | |
| 139 | + return ImmutableList.of(this); | |
| 140 | + } | |
| 141 | + } | |
| 142 | + | |
| 143 | + /** | |
| 144 | + * Returns whether this range intersects another one. | |
| 145 | + * <p> | |
| 146 | + * For example: | |
| 147 | + * <ul> | |
| 148 | + * <li>{@code ]3,5]} intersects {@code ]1,4]}, {@code ]4,5]}...</li> | |
| 149 | + * <li>{@code ]3,5]} does not intersect {@code ]1,2]}, {@code ]2,3]}, {@code ]5,7]}...</li> | |
| 150 | + * </ul> | |
| 151 | + * | |
| 152 | + * @param that the other range. | |
| 153 | + * @return whether they intersect. | |
| 154 | + */ | |
| 155 | + public boolean intersects(TokenRange that) { | |
| 156 | + // Empty ranges never intersect any other range | |
| 157 | + if (this.isEmpty() || that.isEmpty()) | |
| 158 | + return false; | |
| 159 | + | |
| 160 | + return this.contains(that.start, true) | |
| 161 | + || this.contains(that.end, false) | |
| 162 | + || that.contains(this.start, true) | |
| 163 | + || that.contains(this.end, false); | |
| 164 | + } | |
| 165 | + | |
| 166 | + // isStart handles the case where the token is the start of another range, for example: | |
| 167 | + // * ]1,2] contains 2, but it does not contain the start of ]2,3] | |
| 168 | + // * ]1,2] does not contain 1, but it contains the start of ]1,3] | |
| 169 | + private boolean contains(Token token, boolean isStart) { | |
| 170 | + boolean isAfterStart = isStart ? token.compareTo(start) >= 0 : token.compareTo(start) > 0; | |
| 171 | + boolean isBeforeEnd = end.equals(factory.minToken()) || | |
| 172 | + (isStart ? token.compareTo(end) < 0 : token.compareTo(end) <= 0); | |
| 173 | + return isWrappedAround() | |
| 174 | + ? isAfterStart || isBeforeEnd | |
| 175 | + : isAfterStart && isBeforeEnd; | |
| 176 | + } | |
| 177 | + | |
| 178 | + /** | |
| 179 | + * Merges this range with another one. | |
| 180 | + * <p> | |
| 181 | + * The two ranges should either intersect or be adjacent; in other words, the merged range | |
| 182 | + * should not include tokens that are in neither of the original ranges. | |
| 183 | + * <p> | |
| 184 | + * For example: | |
| 185 | + * <ul> | |
| 186 | + * <li>merging {@code ]3,5]} with {@code ]4,7]} produces {@code ]3,7]};</li> | |
| 187 | + * <li>merging {@code ]3,5]} with {@code ]4,5]} produces {@code ]3,5]};</li> | |
| 188 | + * <li>merging {@code ]3,5]} with {@code ]5,8]} produces {@code ]3,8]};</li> | |
| 189 | + * <li>merging {@code ]3,5]} with {@code ]6,8]} fails.</li> | |
| 190 | + * </ul> | |
| 191 | + * | |
| 192 | + * @param that the other range. | |
| 193 | + * @return the resulting range. | |
| 194 | + * | |
| 195 | + * @throws IllegalArgumentException if the ranges neither intersect nor are adjacent. | |
| 196 | + */ | |
| 197 | + public TokenRange mergeWith(TokenRange that) { | |
| 198 | + if (this.equals(that)) | |
| 199 | + return this; | |
| 200 | + | |
| 201 | + if (!(this.intersects(that) || this.end.equals(that.start) || that.end.equals(this.start))) | |
| 202 | + throw new IllegalArgumentException(String.format( | |
| 203 | + "Can't merge %s with %s because they neither intersect nor are adjacent", | |
| 204 | + this, that)); | |
| 205 | + | |
| 206 | + if (this.isEmpty()) | |
| 207 | + return that; | |
| 208 | + | |
| 209 | + if (that.isEmpty()) | |
| 210 | + return this; | |
| 211 | + | |
| 212 | + // That's actually "starts in or is adjacent to the end of" | |
| 213 | + boolean thisStartsInThat = that.contains(this.start, true) || this.start.equals(that.end); | |
| 214 | + boolean thatStartsInThis = this.contains(that.start, true) || that.start.equals(this.end); | |
| 215 | + | |
| 216 | + // This takes care of all the cases that return the full ring, so that we don't have to worry about them below | |
| 217 | + if (thisStartsInThat && thatStartsInThis) | |
| 218 | + return fullRing(); | |
| 219 | + | |
| 220 | + // Starting at this.start, see how far we can go while staying in at least one of the ranges. | |
| 221 | + Token mergedEnd = (thatStartsInThis && !this.contains(that.end, false)) | |
| 222 | + ? that.end | |
| 223 | + : this.end; | |
| 224 | + | |
| 225 | + // Repeat in the other direction. | |
| 226 | + Token mergedStart = thisStartsInThat ? that.start : this.start; | |
| 227 | + | |
| 228 | + return new TokenRange(mergedStart, mergedEnd, factory); | |
| 229 | + } | |
| 230 | + | |
| 231 | + private TokenRange fullRing() { | |
| 232 | + return new TokenRange(factory.minToken(), factory.minToken(), factory); | |
| 233 | + } | |
| 234 | + | |
| 235 | + @Override | |
| 236 | + public boolean equals(Object other) { | |
| 237 | + if (other == this) | |
| 238 | + return true; | |
| 239 | + if (other instanceof TokenRange) { | |
| 240 | + TokenRange that = (TokenRange)other; | |
| 241 | + return Objects.equal(this.start, that.start) && | |
| 242 | + Objects.equal(this.end, that.end); | |
| 243 | + } | |
| 244 | + return false; | |
| 245 | + } | |
| 246 | + | |
| 247 | + @Override | |
| 248 | + public int hashCode() { | |
| 249 | + return Objects.hashCode(start, end); | |
| 250 | + } | |
| 251 | + | |
| 252 | + @Override | |
| 253 | + public String toString() { | |
| 254 | + return String.format("]%s, %s]", start, end); | |
| 255 | + } | |
| 256 | + | |
| 257 | + @Override public int compareTo(TokenRange other) { | |
| 258 | + if(this.equals(other)) { | |
| 259 | + return 0; | |
| 260 | + } else { | |
| 261 | + int compareStart = this.start.compareTo(other.start); | |
| 262 | + return compareStart != 0 ? compareStart : this.end.compareTo(other.end); | |
| 263 | + } | |
| 264 | + } | |
| 265 | +} |
modified driver-core/src/test/java/com/datastax/driver/core/Assertions.java +4 −0
| @@ -11,4 +11,8 @@ | ||
| 11 | 11 | public static SessionAssert assertThat(Session session) { |
| 12 | 12 | return new SessionAssert(session); |
| 13 | 13 | } |
| 14 | + | |
| 15 | + public static TokenRangeAssert assertThat(TokenRange range) { | |
| 16 | + return new TokenRangeAssert(range); | |
| 17 | + } | |
| 14 | 18 | } |
modified driver-core/src/test/java/com/datastax/driver/core/CCMBridge.java +3 −2
| @@ -20,6 +20,7 @@ | ||
| 20 | 20 | import com.datastax.driver.core.exceptions.DriverException; |
| 21 | 21 | import com.datastax.driver.core.exceptions.NoHostAvailableException; |
| 22 | 22 | |
| 23 | +import com.google.common.base.Joiner; | |
| 23 | 24 | import com.google.common.io.Files; |
| 24 | 25 | import org.slf4j.Logger; |
| 25 | 26 | import org.slf4j.LoggerFactory; |
| @@ -89,11 +90,11 @@ | ||
| 89 | 90 | return bridge; |
| 90 | 91 | } |
| 91 | 92 | |
| 92 | - public static CCMBridge create(String name, int nbNodes) { | |
| 93 | + public static CCMBridge create(String name, int nbNodes, String... options) { | |
| 93 | 94 | checkArgument(!"current".equals(name.toLowerCase()), |
| 94 | 95 | "cluster can't be called \"current\""); |
| 95 | 96 | CCMBridge bridge = new CCMBridge(); |
| 96 | - bridge.execute("ccm create %s -n %d -s -i %s -b %s", name, nbNodes, IP_PREFIX, CASSANDRA_VERSION); | |
| 97 | + bridge.execute("ccm create %s -n %d -s -i %s -b %s " + Joiner.on(" ").join(options), name, nbNodes, IP_PREFIX, CASSANDRA_VERSION); | |
| 97 | 98 | return bridge; |
| 98 | 99 | } |
| 99 | 100 |
added driver-core/src/test/java/com/datastax/driver/core/M3PTokenFactoryTest.java +77 −0
| @@ -0,0 +1,77 @@ | ||
| 1 | +package com.datastax.driver.core; | |
| 2 | + | |
| 3 | +import java.util.List; | |
| 4 | + | |
| 5 | +import org.testng.annotations.Test; | |
| 6 | + | |
| 7 | +import static org.assertj.core.api.Assertions.assertThat; | |
| 8 | + | |
| 9 | +public class M3PTokenFactoryTest { | |
| 10 | + Token.Factory factory = Token.M3PToken.FACTORY; | |
| 11 | + | |
| 12 | + @Test(groups = "unit") | |
| 13 | + public void should_split_range() { | |
| 14 | + List<Token> splits = factory.split(factory.fromString("-9223372036854775808"), factory.fromString("4611686018427387904"), 3); | |
| 15 | + assertThat(splits).containsExactly( | |
| 16 | + factory.fromString("-4611686018427387904"), | |
| 17 | + factory.fromString("0") | |
| 18 | + ); | |
| 19 | + } | |
| 20 | + | |
| 21 | + @Test(groups = "unit") | |
| 22 | + public void should_split_range_that_wraps_around_the_ring() { | |
| 23 | + List<Token> splits = factory.split(factory.fromString("4611686018427387904"), factory.fromString("0"), 3); | |
| 24 | + assertThat(splits).containsExactly( | |
| 25 | + factory.fromString("-9223372036854775807"), | |
| 26 | + factory.fromString("-4611686018427387903") | |
| 27 | + ); | |
| 28 | + } | |
| 29 | + | |
| 30 | + @Test(groups = "unit") | |
| 31 | + public void should_split_range_when_division_not_integral() { | |
| 32 | + List<Token> splits = factory.split(factory.fromString("0"), factory.fromString("11"), 3); | |
| 33 | + assertThat(splits).containsExactly( | |
| 34 | + factory.fromString("4"), | |
| 35 | + factory.fromString("8") | |
| 36 | + ); | |
| 37 | + } | |
| 38 | + | |
| 39 | + @Test(groups = "unit") | |
| 40 | + public void should_split_range_producing_empty_splits() { | |
| 41 | + List<Token> splits = factory.split(factory.fromString("0"), factory.fromString("2"), 5); | |
| 42 | + assertThat(splits).containsExactly( | |
| 43 | + factory.fromString("1"), | |
| 44 | + factory.fromString("2"), | |
| 45 | + factory.fromString("2"), | |
| 46 | + factory.fromString("2") | |
| 47 | + ); | |
| 48 | + } | |
| 49 | + | |
| 50 | + @Test(groups = "unit") | |
| 51 | + public void should_split_range_producing_empty_splits_near_ring_end() { | |
| 52 | + Token minToken = factory.fromString("-9223372036854775808"); | |
| 53 | + Token maxToken = factory.fromString("9223372036854775807"); | |
| 54 | + | |
| 55 | + // These are edge cases where we want to make sure we don't accidentally generate the ]min,min] range (which is the whole ring) | |
| 56 | + List<Token> splits = factory.split(maxToken, minToken, 3); | |
| 57 | + assertThat(splits).containsExactly( | |
| 58 | + maxToken, | |
| 59 | + maxToken | |
| 60 | + ); | |
| 61 | + | |
| 62 | + splits = factory.split(minToken, factory.fromString("-9223372036854775807"), 3); | |
| 63 | + assertThat(splits).containsExactly( | |
| 64 | + factory.fromString("-9223372036854775807"), | |
| 65 | + factory.fromString("-9223372036854775807") | |
| 66 | + ); | |
| 67 | + } | |
| 68 | + | |
| 69 | + @Test(groups = "unit") | |
| 70 | + public void should_split_whole_ring() { | |
| 71 | + List<Token> splits = factory.split(factory.fromString("-9223372036854775808"), factory.fromString("-9223372036854775808"), 3); | |
| 72 | + assertThat(splits).containsExactly( | |
| 73 | + factory.fromString("-3074457345618258603"), | |
| 74 | + factory.fromString("3074457345618258602") | |
| 75 | + ); | |
| 76 | + } | |
| 77 | +} | |
| No newline at the end of the file |
added driver-core/src/test/java/com/datastax/driver/core/M3PTokenIntegrationTest.java +13 −0
| @@ -0,0 +1,13 @@ | ||
| 1 | +package com.datastax.driver.core; | |
| 2 | + | |
| 3 | +import com.datastax.driver.core.Token.M3PToken; | |
| 4 | + | |
| 5 | +public class M3PTokenIntegrationTest extends TokenIntegrationTest { | |
| 6 | + public M3PTokenIntegrationTest() { | |
| 7 | + super("", DataType.bigint()); | |
| 8 | + } | |
| 9 | + | |
| 10 | + @Override protected Token.Factory tokenFactory() { | |
| 11 | + return M3PToken.FACTORY; | |
| 12 | + } | |
| 13 | +} |
added driver-core/src/test/java/com/datastax/driver/core/OPPTokenFactoryTest.java +40 −0
| @@ -0,0 +1,40 @@ | ||
| 1 | +package com.datastax.driver.core; | |
| 2 | + | |
| 3 | +import java.nio.ByteBuffer; | |
| 4 | +import java.util.List; | |
| 5 | + | |
| 6 | +import com.google.common.collect.Lists; | |
| 7 | +import org.testng.annotations.Test; | |
| 8 | + | |
| 9 | +import static org.assertj.core.api.Assertions.assertThat; | |
| 10 | + | |
| 11 | +public class OPPTokenFactoryTest { | |
| 12 | + Token.Factory factory = Token.OPPToken.FACTORY; | |
| 13 | + | |
| 14 | + @Test(groups = "unit") | |
| 15 | + public void should_split_range() { | |
| 16 | + List<Token> splits = factory.split(token('a'), token('d'), 3); | |
| 17 | + assertThat(splits).containsExactly( | |
| 18 | + token('b'), | |
| 19 | + token('c') | |
| 20 | + ); | |
| 21 | + } | |
| 22 | + | |
| 23 | + @Test(groups = "unit") | |
| 24 | + public void should_split_range_producing_empty_splits_near_ring_end() { | |
| 25 | + Token minToken = factory.deserialize(ByteBuffer.allocate(0)); | |
| 26 | + // the first token following min | |
| 27 | + Token zero = factory.deserialize(ByteBuffer.wrap(new byte[]{0})); | |
| 28 | + | |
| 29 | + // These are edge cases where we want to make sure we don't accidentally generate the ]min,min] range (which is the whole ring) | |
| 30 | + List<Token> splits = factory.split(minToken, zero, 3); | |
| 31 | + assertThat(splits).containsExactly( | |
| 32 | + zero, | |
| 33 | + zero | |
| 34 | + ); | |
| 35 | + } | |
| 36 | + | |
| 37 | + private Token token(char c) { | |
| 38 | + return new Token.OPPToken(ByteBuffer.wrap(new byte[]{ (byte)c })); | |
| 39 | + } | |
| 40 | +} |
added driver-core/src/test/java/com/datastax/driver/core/OPPTokenIntegrationTest.java +13 −0
| @@ -0,0 +1,13 @@ | ||
| 1 | +package com.datastax.driver.core; | |
| 2 | + | |
| 3 | +import com.datastax.driver.core.Token.OPPToken; | |
| 4 | + | |
| 5 | +public class OPPTokenIntegrationTest extends TokenIntegrationTest { | |
| 6 | + public OPPTokenIntegrationTest() { | |
| 7 | + super("-p ByteOrderedPartitioner", DataType.blob()); | |
| 8 | + } | |
| 9 | + | |
| 10 | + @Override protected Token.Factory tokenFactory() { | |
| 11 | + return OPPToken.FACTORY; | |
| 12 | + } | |
| 13 | +} |
added driver-core/src/test/java/com/datastax/driver/core/RPTokenFactoryTest.java +61 −0
| @@ -0,0 +1,61 @@ | ||
| 1 | +package com.datastax.driver.core; | |
| 2 | + | |
| 3 | +import java.util.List; | |
| 4 | + | |
| 5 | +import org.testng.annotations.Test; | |
| 6 | + | |
| 7 | +import static org.assertj.core.api.Assertions.assertThat; | |
| 8 | + | |
| 9 | +public class RPTokenFactoryTest { | |
| 10 | + Token.Factory factory = Token.RPToken.FACTORY; | |
| 11 | + | |
| 12 | + @Test(groups = "unit") | |
| 13 | + public void should_split_range() { | |
| 14 | + List<Token> splits = factory.split(factory.fromString("0"), factory.fromString("127605887595351923798765477786913079296"), 3); | |
| 15 | + assertThat(splits).containsExactly( | |
| 16 | + factory.fromString("42535295865117307932921825928971026432"), | |
| 17 | + factory.fromString("85070591730234615865843651857942052864") | |
| 18 | + ); | |
| 19 | + } | |
| 20 | + | |
| 21 | + @Test(groups = "unit") | |
| 22 | + public void should_split_range_that_wraps_around_the_ring() { | |
| 23 | + List<Token> splits = factory.split( | |
| 24 | + factory.fromString("127605887595351923798765477786913079296"), | |
| 25 | + factory.fromString("85070591730234615865843651857942052864"), | |
| 26 | + 3); | |
| 27 | + | |
| 28 | + assertThat(splits).containsExactly( | |
| 29 | + factory.fromString("0"), | |
| 30 | + factory.fromString("42535295865117307932921825928971026432") | |
| 31 | + ); | |
| 32 | + } | |
| 33 | + | |
| 34 | + @Test(groups = "unit") | |
| 35 | + public void should_split_range_producing_empty_splits_near_ring_end() { | |
| 36 | + Token minToken = factory.fromString("-1"); | |
| 37 | + Token maxToken = factory.fromString("170141183460469231731687303715884105728"); | |
| 38 | + | |
| 39 | + // These are edge cases where we want to make sure we don't accidentally generate the ]min,min] range (which is the whole ring) | |
| 40 | + List<Token> splits = factory.split(maxToken, minToken, 3); | |
| 41 | + assertThat(splits).containsExactly( | |
| 42 | + maxToken, | |
| 43 | + maxToken | |
| 44 | + ); | |
| 45 | + | |
| 46 | + splits = factory.split(minToken, factory.fromString("0"), 3); | |
| 47 | + assertThat(splits).containsExactly( | |
| 48 | + factory.fromString("0"), | |
| 49 | + factory.fromString("0") | |
| 50 | + ); | |
| 51 | + } | |
| 52 | + | |
| 53 | + @Test(groups = "unit") | |
| 54 | + public void should_split_whole_ring() { | |
| 55 | + List<Token> splits = factory.split(factory.fromString("-1"), factory.fromString("-1"), 3); | |
| 56 | + assertThat(splits).containsExactly( | |
| 57 | + factory.fromString("56713727820156410577229101238628035242"), | |
| 58 | + factory.fromString("113427455640312821154458202477256070485") | |
| 59 | + ); | |
| 60 | + } | |
| 61 | +} |
added driver-core/src/test/java/com/datastax/driver/core/RPTokenIntegrationTest.java +13 −0
| @@ -0,0 +1,13 @@ | ||
| 1 | +package com.datastax.driver.core; | |
| 2 | + | |
| 3 | +import com.datastax.driver.core.Token.RPToken; | |
| 4 | + | |
| 5 | +public class RPTokenIntegrationTest extends TokenIntegrationTest { | |
| 6 | + public RPTokenIntegrationTest() { | |
| 7 | + super("-p RandomPartitioner", DataType.varint()); | |
| 8 | + } | |
| 9 | + | |
| 10 | + @Override protected Token.Factory tokenFactory() { | |
| 11 | + return RPToken.FACTORY; | |
| 12 | + } | |
| 13 | +} |
added driver-core/src/test/java/com/datastax/driver/core/TokenIntegrationTest.java +212 −0
| @@ -0,0 +1,212 @@ | ||
| 1 | +package com.datastax.driver.core; | |
| 2 | + | |
| 3 | +import java.net.InetSocketAddress; | |
| 4 | +import java.util.Iterator; | |
| 5 | +import java.util.List; | |
| 6 | +import java.util.Set; | |
| 7 | + | |
| 8 | +import com.beust.jcommander.internal.Sets; | |
| 9 | +import com.google.common.collect.Lists; | |
| 10 | +import org.testng.annotations.AfterClass; | |
| 11 | +import org.testng.annotations.BeforeClass; | |
| 12 | +import org.testng.annotations.Test; | |
| 13 | + | |
| 14 | +import com.datastax.driver.core.policies.LoadBalancingPolicy; | |
| 15 | +import com.datastax.driver.core.policies.RoundRobinPolicy; | |
| 16 | +import com.datastax.driver.core.policies.WhiteListPolicy; | |
| 17 | + | |
| 18 | +import static com.datastax.driver.core.Assertions.assertThat; | |
| 19 | + | |
| 20 | +/** | |
| 21 | + * This class uses subclasses for each type of partitioner. | |
| 22 | + * | |
| 23 | + * There's normally a way to parametrize a TestNG class with @Factory and @DataProvider, | |
| 24 | + * but it doesn't seem to work with multiple methods. | |
| 25 | + */ | |
| 26 | +public abstract class TokenIntegrationTest { | |
| 27 | + | |
| 28 | + List<String> schema = Lists.newArrayList( | |
| 29 | + "CREATE KEYSPACE IF NOT EXISTS test WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}", | |
| 30 | + "CREATE KEYSPACE IF NOT EXISTS test2 WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 2}", | |
| 31 | + "USE test", | |
| 32 | + "CREATE TABLE IF NOT EXISTS foo(i int primary key)", | |
| 33 | + "INSERT INTO foo (i) VALUES (1)", | |
| 34 | + "INSERT INTO foo (i) VALUES (2)", | |
| 35 | + "INSERT INTO foo (i) VALUES (3)", | |
| 36 | + "CREATE TABLE IF NOT EXISTS foo2(\"caseSensitiveKey\" int primary key)", | |
| 37 | + "INSERT INTO foo2 (\"caseSensitiveKey\") VALUES (1)" | |
| 38 | + ); | |
| 39 | + | |
| 40 | + private final String ccmOptions; | |
| 41 | + private final DataType expectedTokenType; | |
| 42 | + CCMBridge ccm; | |
| 43 | + Cluster cluster; | |
| 44 | + Session session; | |
| 45 | + | |
| 46 | + public TokenIntegrationTest(String ccmOptions, DataType expectedTokenType) { | |
| 47 | + this.ccmOptions = ccmOptions; | |
| 48 | + this.expectedTokenType = expectedTokenType; | |
| 49 | + } | |
| 50 | + | |
| 51 | + @BeforeClass(groups = "short") | |
| 52 | + public void setup() { | |
| 53 | + ccm = CCMBridge.create("test", 3, ccmOptions); | |
| 54 | + | |
| 55 | + // Only connect to node 1, which makes it easier to query system tables in should_expose_tokens_per_host() | |
| 56 | + LoadBalancingPolicy lbp = new WhiteListPolicy(new RoundRobinPolicy(), | |
| 57 | + Lists.newArrayList(new InetSocketAddress(CCMBridge.ipOfNode(1), 9042))); | |
| 58 | + | |
| 59 | + cluster = Cluster.builder() | |
| 60 | + .addContactPoints(CCMBridge.ipOfNode(1)) | |
| 61 | + .withLoadBalancingPolicy(lbp) | |
| 62 | + .build(); | |
| 63 | + cluster.init(); | |
| 64 | + session = cluster.connect(); | |
| 65 | + | |
| 66 | + for (String statement : schema) | |
| 67 | + session.execute(statement); | |
| 68 | + } | |
| 69 | + | |
| 70 | + @AfterClass(groups = "short") | |
| 71 | + public void teardown() { | |
| 72 | + if (cluster != null) | |
| 73 | + cluster.close(); | |
| 74 | + if (ccm != null) | |
| 75 | + ccm.remove(); | |
| 76 | + } | |
| 77 | + | |
| 78 | + @Test(groups = "short") | |
| 79 | + public void should_expose_token_ranges() throws Exception { | |
| 80 | + Metadata metadata = cluster.getMetadata(); | |
| 81 | + | |
| 82 | + // Find the replica for a given partition key | |
| 83 | + int testKey = 1; | |
| 84 | + Set<Host> replicas = metadata.getReplicas("test", DataType.cint().serialize(testKey)); | |
| 85 | + assertThat(replicas).hasSize(1); | |
| 86 | + Host replica = replicas.iterator().next(); | |
| 87 | + | |
| 88 | + // Iterate the cluster's token ranges. For each one, use a range query to ask Cassandra which partition keys | |
| 89 | + // are in this range. | |
| 90 | + TokenRange foundRange = null; | |
| 91 | + for (TokenRange range : metadata.getTokenRanges()) { | |
| 92 | + List<Row> rows = rangeQuery("SELECT i FROM foo WHERE token(i) > ? and token(i) <= ?", range); | |
| 93 | + for (Row row : rows) { | |
| 94 | + if (row.getInt("i") == testKey) { | |
| 95 | + // We should find our test key exactly once | |
| 96 | + assertThat(foundRange) | |
| 97 | + .describedAs("found the same key in two ranges: " + foundRange + " and " + range) | |
| 98 | + .isNull(); | |
| 99 | + foundRange = range; | |
| 100 | + // That range should be managed by the replica | |
| 101 | + assertThat(metadata.getReplicas("test", range)).contains(replica); | |
| 102 | + } | |
| 103 | + } | |
| 104 | + } | |
| 105 | + assertThat(foundRange).isNotNull(); | |
| 106 | + } | |
| 107 | + | |
| 108 | + private List<Row> rangeQuery(String query, TokenRange range) { | |
| 109 | + List<Row> rows = Lists.newArrayList(); | |
| 110 | + for (TokenRange subRange : range.unwrap()) { | |
| 111 | + rows.addAll(session.execute(query, | |
| 112 | + subRange.getStart(), subRange.getEnd()) | |
| 113 | + .all()); | |
| 114 | + } | |
| 115 | + return rows; | |
| 116 | + } | |
| 117 | + | |
| 118 | + @Test(groups = "short") | |
| 119 | + public void should_get_token_from_row_and_set_token_in_query() { | |
| 120 | + // get by index: | |
| 121 | + Row row = session.execute("SELECT token(i) FROM test.foo WHERE i = 1").one(); | |
| 122 | + Token token = row.getToken(0); | |
| 123 | + assertThat(token.getType()).isEqualTo(expectedTokenType); | |
| 124 | + | |
| 125 | + // get by "base" column name (will add token() around it): | |
| 126 | + assertThat( | |
| 127 | + row.getToken("i") | |
| 128 | + ).isEqualTo(token); | |
| 129 | + | |
| 130 | + // get by name: | |
| 131 | + assertThat( | |
| 132 | + session.execute("SELECT token(i) AS t FROM test.foo WHERE i = 1").one() | |
| 133 | + .getToken("t") | |
| 134 | + ).isEqualTo(token); | |
| 135 | + | |
| 136 | + // get by "base" column name when it's case-sensitive | |
| 137 | + session.execute("SELECT token(\"caseSensitiveKey\") FROM test.foo2 WHERE \"caseSensitiveKey\" = 1").one() | |
| 138 | + .getToken("\"caseSensitiveKey\""); | |
| 139 | + | |
| 140 | + | |
| 141 | + PreparedStatement pst = session.prepare("SELECT * FROM test.foo WHERE token(i) = ?"); | |
| 142 | + row = session.execute(pst.bind(token)).one(); | |
| 143 | + assertThat(row.getInt(0)).isEqualTo(1); | |
| 144 | + | |
| 145 | + row = session.execute(pst.bind().setToken(0, token)).one(); | |
| 146 | + assertThat(row.getInt(0)).isEqualTo(1); | |
| 147 | + | |
| 148 | + row = session.execute("SELECT * FROM test.foo WHERE token(i) = ?", token).one(); | |
| 149 | + assertThat(row.getInt(0)).isEqualTo(1); | |
| 150 | + } | |
| 151 | + | |
| 152 | + @Test(groups = "short") | |
| 153 | + public void should_expose_token_ranges_per_host() { | |
| 154 | + checkRangesPerHost("test", 1); | |
| 155 | + checkRangesPerHost("test2", 2); | |
| 156 | + } | |
| 157 | + | |
| 158 | + private void checkRangesPerHost(String keyspace, int replicationFactor) { | |
| 159 | + Set<TokenRange> allRanges = Sets.newHashSet(); | |
| 160 | + | |
| 161 | + // Get each host's ranges, the count should match the replication factor | |
| 162 | + for (int i = 1; i <= 3; i++) { | |
| 163 | + Host host = TestUtils.findHost(cluster, i); | |
| 164 | + Set<TokenRange> hostRanges = cluster.getMetadata().getTokenRanges(keyspace, host); | |
| 165 | + assertThat(hostRanges).hasSize(replicationFactor); | |
| 166 | + allRanges.addAll(hostRanges); | |
| 167 | + } | |
| 168 | + | |
| 169 | + // Once we ignore duplicates, the number of ranges should match the number of nodes. | |
| 170 | + assertThat(allRanges).hasSize(3); | |
| 171 | + Iterator<TokenRange> it = allRanges.iterator(); | |
| 172 | + TokenRange range1 = it.next(); | |
| 173 | + TokenRange range2 = it.next(); | |
| 174 | + TokenRange range3 = it.next(); | |
| 175 | + | |
| 176 | + // No two ranges should intersect | |
| 177 | + assertThat(range1) | |
| 178 | + .doesNotIntersect(range2) | |
| 179 | + .doesNotIntersect(range3); | |
| 180 | + assertThat(range2) | |
| 181 | + .doesNotIntersect(range3); | |
| 182 | + | |
| 183 | + // And the ranges should cover the whole ring | |
| 184 | + TokenRange mergedRange = range1.mergeWith(range2.mergeWith(range3)); | |
| 185 | + boolean isFullRing = mergedRange.getStart().equals(mergedRange.getEnd()) | |
| 186 | + && !mergedRange.isEmpty(); | |
| 187 | + assertThat(isFullRing).isTrue(); | |
| 188 | + } | |
| 189 | + | |
| 190 | + @Test(groups = "short") | |
| 191 | + public void should_expose_tokens_per_host() { | |
| 192 | + for (Host host : cluster.getMetadata().allHosts()) { | |
| 193 | + // We don't use virtual nodes in this test, so there is only one token | |
| 194 | + assertThat(host.getTokens()).hasSize(1); | |
| 195 | + Token tokenFromMetadata = host.getTokens().iterator().next(); | |
| 196 | + | |
| 197 | + // Check against the info in the system tables, which is a bit weak since it's exactly how the metadata is | |
| 198 | + // constructed in the first place, but there's not much else we can do. | |
| 199 | + // Note that this relies on all queries going to node 1, which is why we use a WhiteList LBP in setup(). | |
| 200 | + Row row = (host.listenAddress == null) | |
| 201 | + ? session.execute("select tokens from system.local").one() | |
| 202 | + : session.execute("select tokens from system.peers where peer = ?", host.listenAddress).one(); | |
| 203 | + Set<String> tokenStrings = row.getSet("tokens", String.class); | |
| 204 | + assertThat(tokenStrings).hasSize(1); | |
| 205 | + Token tokenFromSystemTable = tokenFactory().fromString(tokenStrings.iterator().next()); | |
| 206 | + | |
| 207 | + assertThat(tokenFromMetadata).isEqualTo(tokenFromSystemTable); | |
| 208 | + } | |
| 209 | + } | |
| 210 | + | |
| 211 | + protected abstract Token.Factory tokenFactory(); | |
| 212 | +} |
added driver-core/src/test/java/com/datastax/driver/core/TokenRangeAssert.java +41 −0
| @@ -0,0 +1,41 @@ | ||
| 1 | +package com.datastax.driver.core; | |
| 2 | + | |
| 3 | +import org.assertj.core.api.AbstractAssert; | |
| 4 | + | |
| 5 | +import static org.assertj.core.api.Assertions.assertThat; | |
| 6 | + | |
| 7 | +public class TokenRangeAssert extends AbstractAssert<TokenRangeAssert, TokenRange> { | |
| 8 | + protected TokenRangeAssert(TokenRange actual) { | |
| 9 | + super(actual, TokenRangeAssert.class); | |
| 10 | + } | |
| 11 | + | |
| 12 | + public TokenRangeAssert intersects(TokenRange that) { | |
| 13 | + assertThat(actual.intersects(that)) | |
| 14 | + .as("%s should intersect %s", actual, that) | |
| 15 | + .isTrue(); | |
| 16 | + assertThat(that.intersects(actual)) | |
| 17 | + .as("%s should intersect %s", that, actual) | |
| 18 | + .isTrue(); | |
| 19 | + return this; | |
| 20 | + } | |
| 21 | + | |
| 22 | + public TokenRangeAssert doesNotIntersect(TokenRange that) { | |
| 23 | + assertThat(actual.intersects(that)) | |
| 24 | + .as("%s should not intersect %s", actual, that) | |
| 25 | + .isFalse(); | |
| 26 | + assertThat(that.intersects(actual)) | |
| 27 | + .as("%s should not intersect %s", that, actual) | |
| 28 | + .isFalse(); | |
| 29 | + return this; | |
| 30 | + } | |
| 31 | + | |
| 32 | + public TokenRangeAssert unwrapsToItself() { | |
| 33 | + assertThat(actual.unwrap()).containsExactly(actual); | |
| 34 | + return this; | |
| 35 | + } | |
| 36 | + | |
| 37 | + public TokenRangeAssert unwrapsTo(TokenRange... subRanges) { | |
| 38 | + assertThat(actual.unwrap()).containsExactly(subRanges); | |
| 39 | + return this; | |
| 40 | + } | |
| 41 | +} |
added driver-core/src/test/java/com/datastax/driver/core/TokenRangeTest.java +149 −0
| @@ -0,0 +1,149 @@ | ||
| 1 | +package com.datastax.driver.core; | |
| 2 | + | |
| 3 | +import java.math.BigInteger; | |
| 4 | + | |
| 5 | +import org.testng.annotations.Test; | |
| 6 | + | |
| 7 | +import static com.datastax.driver.core.Assertions.assertThat; | |
| 8 | + | |
| 9 | +public class TokenRangeTest { | |
| 10 | + // The tests in this class don't depend on the kind of factory used, so use Murmur3 everywhere | |
| 11 | + Token.Factory factory = Token.getFactory("Murmur3Partitioner"); | |
| 12 | + private Token minToken = factory.minToken(); | |
| 13 | + | |
| 14 | + @Test(groups = "unit") | |
| 15 | + public void should_check_intersection() { | |
| 16 | + // NB - to make the test more visual, we use watch face numbers | |
| 17 | + assertThat(tokenRange(3, 9)) | |
| 18 | + .doesNotIntersect(tokenRange(11, 1)) | |
| 19 | + .doesNotIntersect(tokenRange(1, 2)) | |
| 20 | + .doesNotIntersect(tokenRange(11, 3)) | |
| 21 | + .doesNotIntersect(tokenRange(2, 3)) | |
| 22 | + .doesNotIntersect(tokenRange(3, 3)) | |
| 23 | + .intersects(tokenRange(2, 6)) | |
| 24 | + .intersects(tokenRange(2, 10)) | |
| 25 | + .intersects(tokenRange(6, 10)) | |
| 26 | + .intersects(tokenRange(4, 8)) | |
| 27 | + .intersects(tokenRange(3, 9)) | |
| 28 | + .doesNotIntersect(tokenRange(9, 10)) | |
| 29 | + .doesNotIntersect(tokenRange(10, 11)) | |
| 30 | + ; | |
| 31 | + assertThat(tokenRange(9, 3)) | |
| 32 | + .doesNotIntersect(tokenRange(5, 7)) | |
| 33 | + .doesNotIntersect(tokenRange(7, 8)) | |
| 34 | + .doesNotIntersect(tokenRange(5, 9)) | |
| 35 | + .doesNotIntersect(tokenRange(8, 9)) | |
| 36 | + .doesNotIntersect(tokenRange(9, 9)) | |
| 37 | + .intersects(tokenRange(8, 2)) | |
| 38 | + .intersects(tokenRange(8, 4)) | |
| 39 | + .intersects(tokenRange(2, 4)) | |
| 40 | + .intersects(tokenRange(10, 2)) | |
| 41 | + .intersects(tokenRange(9, 3)) | |
| 42 | + .doesNotIntersect(tokenRange(3, 4)) | |
| 43 | + .doesNotIntersect(tokenRange(4, 5)) | |
| 44 | + ; | |
| 45 | + assertThat(tokenRange(3, 3)).doesNotIntersect(tokenRange(3, 3)); | |
| 46 | + | |
| 47 | + // Reminder: minToken serves as both lower and upper bound | |
| 48 | + assertThat(tokenRange(minToken, 5)) | |
| 49 | + .doesNotIntersect(tokenRange(6, 7)) | |
| 50 | + .doesNotIntersect(tokenRange(6, minToken)) | |
| 51 | + .intersects(tokenRange(6, 4)) | |
| 52 | + .intersects(tokenRange(2, 4)) | |
| 53 | + .intersects(tokenRange(minToken, 4)) | |
| 54 | + .intersects(tokenRange(minToken, 5)) | |
| 55 | + ; | |
| 56 | + | |
| 57 | + assertThat(tokenRange(5, minToken)) | |
| 58 | + .doesNotIntersect(tokenRange(3, 4)) | |
| 59 | + .doesNotIntersect(tokenRange(minToken, 4)) | |
| 60 | + .intersects(tokenRange(6, 7)) | |
| 61 | + .intersects(tokenRange(4, 1)) | |
| 62 | + .intersects(tokenRange(6, minToken)) | |
| 63 | + .intersects(tokenRange(5, minToken)) | |
| 64 | + ; | |
| 65 | + | |
| 66 | + assertThat(tokenRange(minToken, minToken)) | |
| 67 | + .intersects(tokenRange(3, 4)) | |
| 68 | + .intersects(tokenRange(3, minToken)) | |
| 69 | + .intersects(tokenRange(minToken, 3)) | |
| 70 | + .doesNotIntersect(tokenRange(3, 3)) | |
| 71 | + ; | |
| 72 | + } | |
| 73 | + | |
| 74 | + @Test(groups = "unit") | |
| 75 | + public void should_merge_with_other_range() { | |
| 76 | + assertThat(tokenRange(3, 9).mergeWith(tokenRange(2, 3))).isEqualTo(tokenRange(2, 9)); | |
| 77 | + assertThat(tokenRange(3, 9).mergeWith(tokenRange(2, 4))).isEqualTo(tokenRange(2, 9)); | |
| 78 | + assertThat(tokenRange(3, 9).mergeWith(tokenRange(11, 3))).isEqualTo(tokenRange(11, 9)); | |
| 79 | + assertThat(tokenRange(3, 9).mergeWith(tokenRange(11, 4))).isEqualTo(tokenRange(11, 9)); | |
| 80 | + | |
| 81 | + assertThat(tokenRange(3, 9).mergeWith(tokenRange(4, 8))).isEqualTo(tokenRange(3, 9)); | |
| 82 | + assertThat(tokenRange(3, 9).mergeWith(tokenRange(3, 9))).isEqualTo(tokenRange(3, 9)); | |
| 83 | + assertThat(tokenRange(3, 9).mergeWith(tokenRange(3, 3))).isEqualTo(tokenRange(3, 9)); | |
| 84 | + assertThat(tokenRange(3, 3).mergeWith(tokenRange(3, 9))).isEqualTo(tokenRange(3, 9)); | |
| 85 | + | |
| 86 | + assertThat(tokenRange(3, 9).mergeWith(tokenRange(9, 11))).isEqualTo(tokenRange(3, 11)); | |
| 87 | + assertThat(tokenRange(3, 9).mergeWith(tokenRange(8, 11))).isEqualTo(tokenRange(3, 11)); | |
| 88 | + assertThat(tokenRange(3, 9).mergeWith(tokenRange(9, 1))).isEqualTo(tokenRange(3, 1)); | |
| 89 | + assertThat(tokenRange(3, 9).mergeWith(tokenRange(8, 1))).isEqualTo(tokenRange(3, 1)); | |
| 90 | + | |
| 91 | + assertThat(tokenRange(3, 9).mergeWith(tokenRange(9, 3))).isEqualTo(tokenRange(minToken, minToken)); | |
| 92 | + assertThat(tokenRange(3, 9).mergeWith(tokenRange(9, 4))).isEqualTo(tokenRange(minToken, minToken)); | |
| 93 | + assertThat(tokenRange(3, 10).mergeWith(tokenRange(9, 4))).isEqualTo(tokenRange(minToken, minToken)); | |
| 94 | + | |
| 95 | + assertThat(tokenRange(9, 3).mergeWith(tokenRange(8, 9))).isEqualTo(tokenRange(8, 3)); | |
| 96 | + assertThat(tokenRange(9, 3).mergeWith(tokenRange(8, 10))).isEqualTo(tokenRange(8, 3)); | |
| 97 | + assertThat(tokenRange(9, 3).mergeWith(tokenRange(4, 9))).isEqualTo(tokenRange(4, 3)); | |
| 98 | + assertThat(tokenRange(9, 3).mergeWith(tokenRange(4, 10))).isEqualTo(tokenRange(4, 3)); | |
| 99 | + | |
| 100 | + assertThat(tokenRange(9, 3).mergeWith(tokenRange(10, 2))).isEqualTo(tokenRange(9, 3)); | |
| 101 | + assertThat(tokenRange(9, 3).mergeWith(tokenRange(9, 3))).isEqualTo(tokenRange(9, 3)); | |
| 102 | + assertThat(tokenRange(9, 3).mergeWith(tokenRange(9, 9))).isEqualTo(tokenRange(9, 3)); | |
| 103 | + assertThat(tokenRange(9, 9).mergeWith(tokenRange(9, 3))).isEqualTo(tokenRange(9, 3)); | |
| 104 | + | |
| 105 | + assertThat(tokenRange(9, 3).mergeWith(tokenRange(3, 5))).isEqualTo(tokenRange(9, 5)); | |
| 106 | + assertThat(tokenRange(9, 3).mergeWith(tokenRange(2, 5))).isEqualTo(tokenRange(9, 5)); | |
| 107 | + assertThat(tokenRange(9, 3).mergeWith(tokenRange(3, 7))).isEqualTo(tokenRange(9, 7)); | |
| 108 | + assertThat(tokenRange(9, 3).mergeWith(tokenRange(2, 7))).isEqualTo(tokenRange(9, 7)); | |
| 109 | + | |
| 110 | + assertThat(tokenRange(9, 3).mergeWith(tokenRange(3, 9))).isEqualTo(tokenRange(minToken, minToken)); | |
| 111 | + assertThat(tokenRange(9, 3).mergeWith(tokenRange(3, 10))).isEqualTo(tokenRange(minToken, minToken)); | |
| 112 | + | |
| 113 | + assertThat(tokenRange(3, 3).mergeWith(tokenRange(3, 3))).isEqualTo(tokenRange(3, 3)); | |
| 114 | + | |
| 115 | + assertThat(tokenRange(5, minToken).mergeWith(tokenRange(6, 7))).isEqualTo(tokenRange(5, minToken)); | |
| 116 | + assertThat(tokenRange(5, minToken).mergeWith(tokenRange(minToken, 3))).isEqualTo(tokenRange(5, 3)); | |
| 117 | + assertThat(tokenRange(5, minToken).mergeWith(tokenRange(3, 5))).isEqualTo(tokenRange(3, minToken)); | |
| 118 | + | |
| 119 | + assertThat(tokenRange(minToken, 5).mergeWith(tokenRange(2, 3))).isEqualTo(tokenRange(minToken, 5)); | |
| 120 | + assertThat(tokenRange(minToken, 5).mergeWith(tokenRange(7, minToken))).isEqualTo(tokenRange(7, 5)); | |
| 121 | + assertThat(tokenRange(minToken, 5).mergeWith(tokenRange(5, 7))).isEqualTo(tokenRange(minToken, 7)); | |
| 122 | + } | |
| 123 | + | |
| 124 | + @Test(groups = "unit") | |
| 125 | + public void should_unwrap_to_non_wrapping_ranges() { | |
| 126 | + assertThat(tokenRange(9, 3)).unwrapsTo(tokenRange(9, minToken), tokenRange(minToken, 3)); | |
| 127 | + assertThat(tokenRange(3, 9)).unwrapsToItself(); | |
| 128 | + assertThat(tokenRange(3, minToken)).unwrapsToItself(); | |
| 129 | + assertThat(tokenRange(minToken, 3)).unwrapsToItself(); | |
| 130 | + assertThat(tokenRange(3, 3)).unwrapsToItself(); | |
| 131 | + assertThat(tokenRange(minToken, minToken)).unwrapsToItself(); | |
| 132 | + } | |
| 133 | + | |
| 134 | + private TokenRange tokenRange(long start, long end) { | |
| 135 | + return new TokenRange(factory.newToken(BigInteger.valueOf(start)), factory.newToken(BigInteger.valueOf(end)), factory); | |
| 136 | + } | |
| 137 | + | |
| 138 | + private TokenRange tokenRange(Token start, long end) { | |
| 139 | + return new TokenRange(start, factory.newToken(BigInteger.valueOf(end)), factory); | |
| 140 | + } | |
| 141 | + | |
| 142 | + private TokenRange tokenRange(long start, Token end) { | |
| 143 | + return new TokenRange(factory.newToken(BigInteger.valueOf(start)), end, factory); | |
| 144 | + } | |
| 145 | + | |
| 146 | + private TokenRange tokenRange(Token start, Token end) { | |
| 147 | + return new TokenRange(start, end, factory); | |
| 148 | + } | |
| 149 | +} | |
| No newline at the end of the file |