Elffuss BraidHub

kikocis/java-driver public

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