| 1 | ## Custom Payloads |
| 2 | |
| 3 | The [native protocol](../native_protocol/) version 4 introduces a new feature called [Custom Payloads][CASSANDRA-8553]. |
| 4 | |
| 5 | According to the [protocol V4 specification][v4spec], custom payloads are generic key-value maps |
| 6 | where keys are strings and each value is an arbitrary sequence of bytes. Currently payloads |
| 7 | can be sent by clients along with all `QUERY`, `PREPARE`, `EXECUTE` and `BATCH` requests. |
| 8 | |
| 9 | Custom payloads can be used to convey user-specific information from clients to servers and vice versa. |
| 10 | _Please note that this is an advanced feature that requires specific server-side configuration (see below)._ |
| 11 | |
| 12 | ### Enabling custom payloads on C* nodes |
| 13 | |
| 14 | What the server is supposed to do with a payload depends on the [QueryHandler][qh] used server-side |
| 15 | to decode requests. Unsurprisingly, the default `QueryHandler` implementation used by Cassandra |
| 16 | simply ignores all payloads. However, users can replace it with their own implementation, |
| 17 | thus being able to to process user-specific payloads; the payload format as well as |
| 18 | the serialization and deserialization logic is entirely left for clients to implement. |
| 19 | Needless to say, the same encoding and decoding logic should be applied on both client |
| 20 | and server endpoints. |
| 21 | |
| 22 | This section is a small how-to to help driver users getting started with |
| 23 | custom payload processing server-side. For more detailed information, |
| 24 | please refer to the Cassandra documentation itself. |
| 25 | |
| 26 | To enable a custom `QueryHandler` for a Cassandra node, its JVM should be |
| 27 | started with the system property `cassandra.custom_query_handler_class` set |
| 28 | to a fully qualified name of a class implementing `org.apache.cassandra.cql3.QueryHandler`. |
| 29 | This class should be of course available on the node's classpath. |
| 30 | |
| 31 | This can be achieved with the following steps: |
| 32 | |
| 33 | 1. Add your implementation jar to the `CLASSPATH` environment variable; |
| 34 | 2. Add the following to `$CASSANDRA_CONF/cassandra-env.sh`: |
| 35 | |
| 36 | ``` |
| 37 | JVM_EXTRA_OPTS="-Dcassandra.custom_query_handler_class=fully.qualified.name.of.MyQueryHandler" |
| 38 | ``` |
| 39 | |
| 40 | Of course, all nodes in the cluster *must* be started with the same QueryHandler, otherwise |
| 41 | payloads sent by the driver could get lost. |
| 42 | |
| 43 | ### Implementation Notes |
| 44 | |
| 45 | Payloads in the Java driver are represented as `Map<String,ByteBuffer>` instances. |
| 46 | It is safe to use any `Map` implementation, including unsynchronized implementations |
| 47 | such as `java.util.HashMap`; the driver will create defensive, thread-safe copies of |
| 48 | user-supplied maps. However, `ByteBuffer` instances are inherently mutable, |
| 49 | so callers should take care not to modify the `ByteBuffer` values in a payload map *after* submitting it |
| 50 | to the driver as it could lead to unexpected results. |
| 51 | |
| 52 | #### Null values |
| 53 | |
| 54 | Note that, for thread safety reasons, the Java driver does not permit `null` keys nor `null` values in a payload map; |
| 55 | including a `null` in your payload will result in a `NullPointerException` being immediately thrown. |
| 56 | |
| 57 | However, the protocol specification *does* allow `null` values. If you need to include |
| 58 | a `null` value in your payload map, this can be achieved with the Java driver |
| 59 | by using the special value `Statement.NULL_PAYLOAD_VALUE`. |
| 60 | |
| 61 | ##### Payload length limitations |
| 62 | |
| 63 | 1. Payload maps cannot have more than 65,535 entries. |
| 64 | 2. Payload map values are limited to a maximum length of `Integer.MAX_VALUE` (2<sup><small>31</small></sup> − 1) bytes each. |
| 65 | |
| 66 | ### Sending custom payloads |
| 67 | |
| 68 | A custom payload can be attached to any `Statement` via `Statement.setOutgoingPayload()`. |
| 69 | |
| 70 | Once the payload is set, you can either prepare the statement or execute it; |
| 71 | in both cases, the payload will be sent along with the `PREPARE` or `QUERY` request respectively: |
| 72 | |
| 73 | ```java |
| 74 | Statement statement = new SimpleStatement("SELECT foo FROM bar WHERE qix = 1"); |
| 75 | statement.setOutgoingPayload(myCustomPayload); |
| 76 | session.execute(statement); // myCustomPayload will be sent with QUERY request |
| 77 | session.prepare(statement); // myCustomPayload will be sent with PREPARE request |
| 78 | ``` |
| 79 | |
| 80 | Naturally, you can also set a payload when using the `QueryBuilder` API: |
| 81 | |
| 82 | ```java |
| 83 | Statement statement = QueryBuilder.select("c2").from("t1").where(eq("c1", 1)).setOutgoingPayload(myCustomPayload); |
| 84 | session.execute(statement); // myCustomPayload will be sent with EXECUTE request |
| 85 | ``` |
| 86 | |
| 87 | When sending payloads with batches, please note that payloads must be attached to the |
| 88 | `BatchStatement` itself, *not* to internal statements: |
| 89 | |
| 90 | ```java |
| 91 | Statement statement = new SimpleStatement("INSERT INTO t1 (c1, c2) values ('foo', 'bar')") |
| 92 | // correct |
| 93 | Statement batch = new BatchStatement().add(statement); |
| 94 | batch.setOutgoingPayload(myCustomPayload); |
| 95 | session.execute(batch); // myCustomPayload will be sent with BATCH request |
| 96 | // wrong |
| 97 | statement.setOutgoingPayload(myCustomPayload); |
| 98 | Statement batch = new BatchStatement().add(statement); |
| 99 | session.execute(batch); // myCustomPayload will NOT be sent with BATCH request |
| 100 | ``` |
| 101 | |
| 102 | One important note about paging requests: if your query needs to paginate, |
| 103 | any outgoing payload set on the executed statement *will be transparently |
| 104 | sent over and over for every new page request*. |
| 105 | |
| 106 | ```java |
| 107 | Statement statement = new SimpleStatement("..."); |
| 108 | statement.setOutgoingPayload(myCustomPayload); |
| 109 | ResultSet rows = session.execute(...); // myCustomPayload will be sent with first QUERY request |
| 110 | for (Row row : rows) { |
| 111 | // if additional QUERY requests are sent, all of them will send the same payload |
| 112 | } |
| 113 | ``` |
| 114 | |
| 115 | And finally, note that custom payloads can only be used with protocol versions >= 4; |
| 116 | trying to set a payload under lower protocol versions will result in |
| 117 | an [UnsupportedFeatureException][ufe] (wrapped in a [NoHostAvailableException][nhae]) |
| 118 | when the request is encoded. |
| 119 | |
| 120 | If you want to defensively protect your code against these errors, you can either: |
| 121 | |
| 122 | 1) Force the protocol version when creating your `Cluster` instance: |
| 123 | |
| 124 | ```java |
| 125 | Cluster cluster = Cluster.builder() |
| 126 | .addContactPoint("...") |
| 127 | .withProtocolVersion(ProtocolVersion.V4) |
| 128 | .build(); |
| 129 | ``` |
| 130 | |
| 131 | 2) Inspect the current negotiated protocol version, and only send payloads if version is equal to or |
| 132 | greater than 4: |
| 133 | |
| 134 | ```java |
| 135 | ProtocolVersion myCurrentVersion = cluster.getConfiguration() |
| 136 | .getProtocolOptions() |
| 137 | .getProtocolVersion(); |
| 138 | if (myCurrentVersion.compareTo(ProtocolVersion.V4) >= 0) { |
| 139 | // only send custom payloads if current protocol version supports it |
| 140 | statement.setOutgoingPayload(myCustomPayload); |
| 141 | } |
| 142 | ``` |
| 143 | |
| 144 | ### Receiving custom payloads |
| 145 | |
| 146 | Custom payloads sent back by the server can be retrieved in the following ways: |
| 147 | |
| 148 | 1) From a `ResultSet`: use the `ExecutionInfo` class to retrieve the payload sent by the server. |
| 149 | |
| 150 | ```java |
| 151 | Statement statement = new SimpleStatement("..."); |
| 152 | ResultSet rows = session.execute(...); |
| 153 | // last payload sent by the server |
| 154 | Map<String,ByteBuffer> serverPayload = rows.getExecutionInfo().getIncomingPayload(); |
| 155 | ``` |
| 156 | |
| 157 | If your query required pagination (multiple `QUERY` requests), |
| 158 | the above method would only return the last payload sent by server |
| 159 | with its last `RESULT` response. If you need to retrieve all the |
| 160 | payloads for all `RESULT` responses, use the following method instead: |
| 161 | |
| 162 | ```java |
| 163 | Statement statement = new SimpleStatement("..."); |
| 164 | ResultSet rows = session.execute(...); |
| 165 | //all payloads sent by the server |
| 166 | for (ExecutionInfo info : rows.getAllExecutionInfo()) { |
| 167 | Map<String,ByteBuffer> serverPayload = info.getIncomingPayload(); |
| 168 | } |
| 169 | ``` |
| 170 | |
| 171 | 2) From a `PreparedStatement`: to retrieve the payload that the server sent back |
| 172 | with its `PREPARED` response, use the following method: |
| 173 | |
| 174 | ```java |
| 175 | PreparedStatement ps = session.prepare(...); |
| 176 | Map<String,ByteBuffer> serverPayload = ps.getIncomingPayload(); |
| 177 | ``` |
| 178 | |
| 179 | ### Custom Payloads and Prepared Statements |
| 180 | |
| 181 | If you use either `Session.prepare(RegularStatement)` or `Session.prepareAsync(RegularStatement)` |
| 182 | to prepare a statement, as with all other properties in the given statement, its outgoing |
| 183 | payload, if any, will become the default outgoing payload for the prepared statement. |
| 184 | |
| 185 | ```java |
| 186 | Statement statement = new SimpleStatement("..."); |
| 187 | statement.setOutgoingPayload(myCustomPayload) |
| 188 | PreparedStatement ps = session.prepare(...); // myCustomPayload will be sent with PREPARE request |
| 189 | // AND become the default outgoing payload |
| 190 | ``` |
| 191 | |
| 192 | Naturally, you can also set a default outgoing payload on the `PreparedStatement` instance itself. |
| 193 | The code below is roughly equivalent to the one above - except that the payload is not sent |
| 194 | with the `PREPARE` request: |
| 195 | |
| 196 | ```java |
| 197 | Statement statement = new SimpleStatement("..."); |
| 198 | PreparedStatement ps = session.prepare(...); // no payload sent with PREPARE request |
| 199 | ps.setOutgoingPayload(myCustomPayload) // default outgoing payload is now myCustomPayload |
| 200 | ``` |
| 201 | |
| 202 | But `PreparedStatement` has also a `getIncomingPayload()` method, which, as we already know, |
| 203 | can be used to retrieve incoming payloads sent back by the server that prepared the request. |
| 204 | |
| 205 | When binding a statement - with either `PreparedStatement.bind()` or `PreparedStatement.bind(Object...)`) - |
| 206 | `BoundStatement` instances will also inherit payloads. |
| 207 | |
| 208 | To determine which payload is going to be used as outgoing payload for a bound statement, |
| 209 | the following rules apply: |
| 210 | |
| 211 | 1. If the prepared statement has a non-null outgoing payload, all instances of `BoundStatement` |
| 212 | created out of it will inherit that payload as their outgoing payload; |
| 213 | 2. Otherwise, if the prepared statement has a non-null incoming payload, all instances of `BoundStatement` |
| 214 | created out of it will inherit that payload as their outgoing payload; |
| 215 | 3. Otherwise, all instances of `BoundStatement` created out of it |
| 216 | won't have any outgoing payload set by default; users can however set an outgoing payload on |
| 217 | individual `BoundStatement` instances by calling their `setOutgoingPayload()` method, |
| 218 | like in the example below: |
| 219 | |
| 220 | ```java |
| 221 | Statement statement = new SimpleStatement("..."); |
| 222 | PreparedStatement ps = session.prepare(...); // no payload sent with PREPARE request |
| 223 | BoundStatement bs = ps.bind(1); // no outgoing payload by default |
| 224 | bs.setOutgoingPayload(myCustomPayload); // outgoing payload for this specific statement |
| 225 | session.execute(statement); // myCustomPayload will be sent with EXECUTE request for this bound statement only |
| 226 | ``` |
| 227 | |
| 228 | ### Debugging custom payloads |
| 229 | |
| 230 | When debugging custom payloads, set the `com.datastax.driver.core.Message` logger to the `TRACE` level, e.g. with Log4J: |
| 231 | |
| 232 | ```xml |
| 233 | <logger name="com.datastax.driver.core.Message"> |
| 234 | <level value="TRACE"/> |
| 235 | </logger> |
| 236 | ``` |
| 237 | |
| 238 | This will log a message for every request and every response that contains a non-null payload. |
| 239 | The log message contains a pretty-printed version of the payload itself, and its total length in bytes. |
| 240 | |
| 241 | [CASSANDRA-8553]: https://issues.apache.org/jira/browse/CASSANDRA-8553 |
| 242 | [v4spec]: https://github.com/apache/cassandra/blob/trunk/doc/native_protocol_v4.spec |
| 243 | [qh]: https://issues.apache.org/jira/browse/CASSANDRA-6659 |
| 244 | [nhae]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/exceptions/NoHostAvailableException.html |
| 245 | [chm]: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentHashMap.html |
| 246 | [immutablemap]: http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/ImmutableMap.html |
| 247 | [ufe]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/exceptions/UnsupportedFeatureException.html |
| 248 | |