Elffuss BraidHub

kikocis/java-driver public

JAVA-1263: Move Compressors into own files, separate direct & heap code

- Move compressors into their own source files
- Separate out direct and heap compression code
- Change LZ4Compressor to use byte[] if not direct.  This is needed
  until JAVA-1306 is implemented.
- Use inputNioBuffer and outputNioBuffer for having a standard way of
  accessing internalNioBuffer (if possible).
- Add isolated tests for heap compression path.
Changeseta8c1832766ee80393060ad1a27958c2eb8bce816cb3f7d45c7173a54b84191f4
AuthorAndrew Tolbert <andrew.tolbert@datastax.com> · 2016-08-31 14:48 -05:00
CommitterAndrew Tolbert <andrew.tolbert@datastax.com> · 2016-09-20 18:39 -05:00
Parentsea1eb34ee440

Browse the files at this changeset

12 files changed

modified changelog/README.md +1 −0
@@ -15,6 +15,7 @@
1515 - [bug] JAVA-1292: 'Adjusted frame length' error breaks driver's ability to read data.
1616 - [improvement] JAVA-1293: Make DecoderForStreamIdSize.MAX_FRAME_LENGTH configurable.
1717 - [improvement] JAVA-1053: Add a metric for authentication errors
18+- [improvement] JAVA-1263: Eliminate unnecessary memory copies in FrameCompressor implementations.
1819
1920
2021 ### 3.0.3
modified clirr-ignores.xml +12 −0
@@ -56,4 +56,16 @@
5656 <justification>This class is only present if the project was compiled with JDK 8+</justification>
5757 </difference>
5858
59+ <difference>
60+ <differenceType>8001</differenceType> <!-- class removed -->
61+ <className>com/datastax/driver/core/FrameCompressor$SnappyCompressor</className>
62+ <justification>False positive, the enclosing class is package-private so this was never exposed</justification>
63+ </difference>
64+
65+ <difference>
66+ <differenceType>8001</differenceType> <!-- class removed -->
67+ <className>com/datastax/driver/core/FrameCompressor$LZ4Compressor</className>
68+ <justification>False positive, the enclosing class is package-private so this was never exposed</justification>
69+ </difference>
70+
5971 </differences>
modified driver-core/pom.xml +1 −0
@@ -324,6 +324,7 @@
324324 <include>**/ControlConnectionTest.java</include>
325325 <include>**/ExtendedPeerCheckDisabledTest.java</include>
326326 <include>**/FrameLengthTest.java</include>
327+ <include>**/HeapCompressionTest.java</include>
327328 </includes>
328329 </configuration>
329330 </plugin>
modified driver-core/src/main/java/com/datastax/driver/core/FrameCompressor.java +12 −233
@@ -15,249 +15,28 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import com.datastax.driver.core.exceptions.DriverInternalError;
1918 import io.netty.buffer.ByteBuf;
20-import io.netty.buffer.Unpooled;
21-import net.jpountz.lz4.LZ4Factory;
22-import org.slf4j.Logger;
23-import org.slf4j.LoggerFactory;
24-import org.xerial.snappy.Snappy;
2519
2620 import java.io.IOException;
2721 import java.nio.ByteBuffer;
2822
2923 abstract class FrameCompressor {
3024
31- private static final Logger logger = LoggerFactory.getLogger(FrameCompressor.class);
25+ abstract Frame compress(Frame frame) throws IOException;
3226
33- public abstract Frame compress(Frame frame) throws IOException;
27+ abstract Frame decompress(Frame frame) throws IOException;
3428
35- public abstract Frame decompress(Frame frame) throws IOException;
36-
37- public static class SnappyCompressor extends FrameCompressor {
38-
39- public static final SnappyCompressor instance;
40-
41- static {
42- SnappyCompressor i;
43- try {
44- i = new SnappyCompressor();
45- } catch (NoClassDefFoundError e) {
46- i = null;
47- logger.warn("Cannot find Snappy class, you should make sure the Snappy library is in the classpath if you intend to use it. Snappy compression will not be available for the protocol.");
48- } catch (Throwable e) {
49- i = null;
50- logger.warn("Error loading Snappy library ({}). Snappy compression will not be available for the protocol.", e.toString());
51- }
52- instance = i;
53- }
54-
55- private SnappyCompressor() {
56- // this would throw java.lang.NoClassDefFoundError if Snappy class
57- // wasn't found at runtime which should be processed by the calling method
58- Snappy.getNativeLibraryVersion();
59- }
60-
61- @Override
62- public Frame compress(Frame frame) throws IOException {
63- ByteBuf input = frame.body;
64- int maxCompressedLength = Snappy.maxCompressedLength(input.readableBytes());
65-
66- final ByteBuf frameBody;
67- if (input.isDirect()) {
68- // If the input is direct we will allocate a direct output buffer as well as this will allow us to use
69- // Snappy.compress(ByteBuffer, ByteBuffer) and so eliminate memory copies.
70- ByteBuf output = input.alloc().directBuffer(maxCompressedLength);
71- try {
72- // Using internalNioBuffer(...) as we only hold the reference in this method and so can
73- // reduce Object allocations.
74- ByteBuffer in = input.internalNioBuffer(input.readerIndex(), input.readableBytes());
75- // Increase reader index.
76- input.readerIndex(input.writerIndex());
77-
78- ByteBuffer out = output.internalNioBuffer(output.writerIndex(), output.writableBytes());
79- int written = Snappy.compress(in, out);
80- // Set the writer index so the amount of written bytes is reflected
81- output.writerIndex(output.writerIndex() + written);
82- frameBody = output;
83- } catch (IOException e) {
84- // release output buffer so we not leak and rethrow exception.
85- output.release();
86- throw e;
87- }
88- } else {
89- int inOffset = input.arrayOffset() + input.readerIndex();
90- byte[] in = input.array();
91- int len = input.readableBytes();
92- // Increase reader index.
93- input.readerIndex(input.writerIndex());
94-
95- // Allocate a heap buffer from the ByteBufAllocator as we may use a PooledByteBufAllocator and so
96- // can eliminate the overhead of allocate a new byte[].
97- ByteBuf output = input.alloc().heapBuffer(maxCompressedLength);
98- try {
99- // Calculate the correct offset.
100- int offset = output.arrayOffset() + output.writerIndex();
101- byte[] out = output.array();
102- int written = Snappy.compress(in, inOffset, len, out, offset);
103-
104- // Increase the writerIndex with the written bytes.
105- output.writerIndex(output.writerIndex() + written);
106- frameBody = output;
107- } catch (IOException e) {
108- // release output buffer so we not leak and rethrow exception.
109- output.release();
110- throw e;
111- }
112- }
113- return frame.with(frameBody);
114- }
115-
116- @Override
117- public Frame decompress(Frame frame) throws IOException {
118- ByteBuf input = frame.body;
119- final ByteBuf frameBody;
120-
121- if (input.isDirect()) {
122- // Using internalNioBuffer(...) as we only hold the reference in this method and so can
123- // reduce Object allocations.
124- ByteBuffer in = input.internalNioBuffer(input.readerIndex(), input.readableBytes());
125- // Increase reader index.
126- input.readerIndex(input.writerIndex());
127-
128- if (!Snappy.isValidCompressedBuffer(in))
129- throw new DriverInternalError("Provided frame does not appear to be Snappy compressed");
130-
131- // If the input is direct we will allocate a direct output buffer as well as this will allow us to use
132- // Snappy.compress(ByteBuffer, ByteBuffer) and so eliminate memory copies.
133- ByteBuf output = frame.body.alloc().directBuffer(Snappy.uncompressedLength(in));
134- try {
135- ByteBuffer out = output.internalNioBuffer(output.writerIndex(), output.writableBytes());
136-
137- int size = Snappy.uncompress(in, out);
138- // Set the writer index so the amount of written bytes is reflected
139- output.writerIndex(output.writerIndex() + size);
140- frameBody = output;
141- } catch (IOException e) {
142- // release output buffer so we not leak and rethrow exception.
143- output.release();
144- throw e;
145- }
146- } else {
147- // Not a direct buffer so use byte arrays...
148- int inOffset = input.arrayOffset() + input.readerIndex();
149- byte[] in = input.array();
150- int len = input.readableBytes();
151- // Increase reader index.
152- input.readerIndex(input.writerIndex());
153-
154- if (!Snappy.isValidCompressedBuffer(in, inOffset, len))
155- throw new DriverInternalError("Provided frame does not appear to be Snappy compressed");
156-
157- // Allocate a heap buffer from the ByteBufAllocator as we may use a PooledByteBufAllocator and so
158- // can eliminate the overhead of allocate a new byte[].
159- ByteBuf output = input.alloc().heapBuffer(Snappy.uncompressedLength(in, inOffset, len));
160- try {
161- // Calculate the correct offset.
162- int offset = output.arrayOffset() + output.writerIndex();
163- byte[] out = output.array();
164- int written = Snappy.uncompress(in, inOffset, len, out, offset);
165-
166- // Increase the writerIndex with the written bytes.
167- output.writerIndex(output.writerIndex() + written);
168- frameBody = output;
169- } catch (IOException e) {
170- // release output buffer so we not leak and rethrow exception.
171- output.release();
172- throw e;
173- }
174- }
175- return frame.with(frameBody);
176- }
29+ protected static ByteBuffer inputNioBuffer(ByteBuf buf) {
30+ // Using internalNioBuffer(...) as we only hold the reference in this method and so can
31+ // reduce Object allocations.
32+ int index = buf.readerIndex();
33+ int len = buf.readableBytes();
34+ return buf.nioBufferCount() == 1 ? buf.internalNioBuffer(index, len) : buf.nioBuffer(index, len);
17735 }
17836
179- public static class LZ4Compressor extends FrameCompressor {
180-
181- public static final LZ4Compressor instance;
182-
183- static {
184- LZ4Compressor i;
185- try {
186- i = new LZ4Compressor();
187- } catch (NoClassDefFoundError e) {
188- i = null;
189- logger.warn("Cannot find LZ4 class, you should make sure the LZ4 library is in the classpath if you intend to use it. LZ4 compression will not be available for the protocol.");
190- } catch (Throwable e) {
191- i = null;
192- logger.warn("Error loading LZ4 library ({}). LZ4 compression will not be available for the protocol.", e.toString());
193- }
194- instance = i;
195- }
196-
197- private static final int INTEGER_BYTES = 4;
198- private final net.jpountz.lz4.LZ4Compressor compressor;
199- private final net.jpountz.lz4.LZ4FastDecompressor decompressor;
200-
201- private LZ4Compressor() {
202- final LZ4Factory lz4Factory = LZ4Factory.fastestInstance();
203- logger.info("Using {}", lz4Factory.toString());
204- compressor = lz4Factory.fastCompressor();
205- decompressor = lz4Factory.fastDecompressor();
206- }
207-
208- @Override
209- public Frame compress(Frame frame) throws IOException {
210- ByteBuf input = frame.body;
211- // Using internalNioBuffer(...) as we only hold the reference in this method and so can
212- // reduce Object allocations.
213- ByteBuffer in = inputNioBuffer(input, input.readerIndex(), input.readableBytes());
214-
215- int maxCompressedLength = compressor.maxCompressedLength(in.remaining());
216- ByteBuf output = input.alloc().directBuffer(INTEGER_BYTES + maxCompressedLength);
217- try {
218- output.writeInt(in.remaining());
219- // Using internalNioBuffer(...) as we only hold the reference in this method and so can
220- // reduce Object allocations.
221- ByteBuffer out = output.internalNioBuffer(output.writerIndex(), output.writableBytes());
222- int written = compressor.compress(in, in.position(), in.remaining(), out, out.position(), out.remaining());
223- // Set the writer index so the amount of written bytes is reflected
224- output.writerIndex(output.writerIndex() + written);
225- return frame.with(output);
226- } catch (Exception e) {
227- // release output buffer so we not leak and rethrow exception.
228- output.release();
229- throw new IOException(e);
230- }
231- }
232-
233- @Override
234- public Frame decompress(Frame frame) throws IOException {
235- ByteBuf input = frame.body;
236- int readable = input.readableBytes();
237- int uncompressedLength = input.readInt();
238- ByteBuffer in = inputNioBuffer(input, input.readerIndex(), input.readableBytes());
239- input.readerIndex(input.writerIndex());
240- ByteBuf output = input.alloc().directBuffer(uncompressedLength);
241- try {
242- ByteBuffer out = output.internalNioBuffer(output.writerIndex(), output.writableBytes());
243- int read = decompressor.decompress(in, in.position(), out, out.position(), out.remaining());
244- if (read != readable - INTEGER_BYTES)
245- throw new IOException("Compressed lengths mismatch");
246-
247- // Set the writer index so the amount of written bytes is reflected
248- output.writerIndex(output.writerIndex() + uncompressedLength);
249- return frame.with(output);
250- } catch (Exception e) {
251- // release output buffer so we not leak and rethrow exception.
252- output.release();
253- throw new IOException(e);
254- }
255- }
256-
257- private static ByteBuffer inputNioBuffer(ByteBuf buf, int index, int len) {
258- // Using internalNioBuffer(...) as we only hold the reference in this method and so can
259- // reduce Object allocations.
260- return buf.nioBufferCount() == 1 ? buf.internalNioBuffer(index, len) : buf.nioBuffer(index, len);
261- }
37+ protected static ByteBuffer outputNioBuffer(ByteBuf buf) {
38+ int index = buf.writerIndex();
39+ int len = buf.writableBytes();
40+ return buf.nioBufferCount() == 1 ? buf.internalNioBuffer(index, len) : buf.nioBuffer(index, len);
26241 }
26342 }
added driver-core/src/main/java/com/datastax/driver/core/LZ4Compressor.java +182 −0
@@ -0,0 +1,182 @@
1+/*
2+ * Copyright (C) 2012-2015 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 io.netty.buffer.ByteBuf;
19+import net.jpountz.lz4.LZ4Factory;
20+import org.slf4j.Logger;
21+import org.slf4j.LoggerFactory;
22+
23+import java.io.IOException;
24+import java.nio.ByteBuffer;
25+
26+class LZ4Compressor extends FrameCompressor {
27+
28+ private static final Logger logger = LoggerFactory.getLogger(LZ4Compressor.class);
29+
30+ static final LZ4Compressor instance;
31+
32+ static {
33+ LZ4Compressor i;
34+ try {
35+ i = new LZ4Compressor();
36+ } catch (NoClassDefFoundError e) {
37+ i = null;
38+ logger.warn("Cannot find LZ4 class, you should make sure the LZ4 library is in the classpath if you intend to use it. LZ4 compression will not be available for the protocol.");
39+ } catch (Throwable e) {
40+ i = null;
41+ logger.warn("Error loading LZ4 library ({}). LZ4 compression will not be available for the protocol.", e.toString());
42+ }
43+ instance = i;
44+ }
45+
46+ private static final int INTEGER_BYTES = 4;
47+ private final net.jpountz.lz4.LZ4Compressor compressor;
48+ private final net.jpountz.lz4.LZ4FastDecompressor decompressor;
49+
50+ private LZ4Compressor() {
51+ final LZ4Factory lz4Factory = LZ4Factory.fastestInstance();
52+ logger.info("Using {}", lz4Factory.toString());
53+ compressor = lz4Factory.fastCompressor();
54+ decompressor = lz4Factory.fastDecompressor();
55+ }
56+
57+ @Override
58+ Frame compress(Frame frame) throws IOException {
59+ ByteBuf input = frame.body;
60+
61+ // TODO: JAVA-1306: Use the same API calls for direct and heap buffers when LZ4 updated.
62+ ByteBuf frameBody = input.isDirect() ? compressDirect(input) : compressHeap(input);
63+ return frame.with(frameBody);
64+ }
65+
66+ private ByteBuf compressDirect(ByteBuf input) throws IOException {
67+ int maxCompressedLength = compressor.maxCompressedLength(input.readableBytes());
68+ // If the input is direct we will allocate a direct output buffer as well as this will allow us to use
69+ // LZ4Compressor.compress and so eliminate memory copies.
70+ ByteBuf output = input.alloc().directBuffer(INTEGER_BYTES + maxCompressedLength);
71+ try {
72+ ByteBuffer in = inputNioBuffer(input);
73+ // Increase reader index.
74+ input.readerIndex(input.writerIndex());
75+
76+ output.writeInt(in.remaining());
77+
78+ ByteBuffer out = outputNioBuffer(output);
79+ int written = compressor.compress(in, in.position(), in.remaining(), out, out.position(), out.remaining());
80+ // Set the writer index so the amount of written bytes is reflected
81+ output.writerIndex(output.writerIndex() + written);
82+ } catch (Exception e) {
83+ // release output buffer so we not leak and rethrow exception.
84+ output.release();
85+ throw new IOException(e);
86+ }
87+ return output;
88+ }
89+
90+ private ByteBuf compressHeap(ByteBuf input) throws IOException {
91+ int maxCompressedLength = compressor.maxCompressedLength(input.readableBytes());
92+
93+ // Not a direct buffer so use byte arrays...
94+ int inOffset = input.arrayOffset() + input.readerIndex();
95+ byte[] in = input.array();
96+ int len = input.readableBytes();
97+ // Increase reader index.
98+ input.readerIndex(input.writerIndex());
99+
100+ // Allocate a heap buffer from the ByteBufAllocator as we may use a PooledByteBufAllocator and so
101+ // can eliminate the overhead of allocate a new byte[].
102+ ByteBuf output = input.alloc().heapBuffer(INTEGER_BYTES + maxCompressedLength);
103+ try {
104+ output.writeInt(len);
105+ // calculate the correct offset.
106+ int offset = output.arrayOffset() + output.writerIndex();
107+ byte[] out = output.array();
108+ int written = compressor.compress(in, inOffset, len, out, offset);
109+
110+ // Set the writer index so the amount of written bytes is reflected
111+ output.writerIndex(output.writerIndex() + written);
112+ } catch (Exception e) {
113+ // release output buffer so we not leak and rethrow exception.
114+ output.release();
115+ throw new IOException(e);
116+ }
117+ return output;
118+ }
119+
120+ @Override
121+ Frame decompress(Frame frame) throws IOException {
122+ ByteBuf input = frame.body;
123+
124+ // TODO: JAVA-1306: Use the same API calls for direct and heap buffers when LZ4 updated.
125+ ByteBuf frameBody = input.isDirect() ? decompressDirect(input) : decompressHeap(input);
126+ return frame.with(frameBody);
127+ }
128+
129+ private ByteBuf decompressDirect(ByteBuf input) throws IOException {
130+ // If the input is direct we will allocate a direct output buffer as well as this will allow us to use
131+ // LZ4Compressor.decompress and so eliminate memory copies.
132+ int readable = input.readableBytes();
133+ int uncompressedLength = input.readInt();
134+ ByteBuffer in = inputNioBuffer(input);
135+ // Increase reader index.
136+ input.readerIndex(input.writerIndex());
137+ ByteBuf output = input.alloc().directBuffer(uncompressedLength);
138+ try {
139+ ByteBuffer out = outputNioBuffer(output);
140+ int read = decompressor.decompress(in, in.position(), out, out.position(), out.remaining());
141+ if (read != readable - INTEGER_BYTES)
142+ throw new IOException("Compressed lengths mismatch");
143+
144+ // Set the writer index so the amount of written bytes is reflected
145+ output.writerIndex(output.writerIndex() + uncompressedLength);
146+ } catch (Exception e) {
147+ // release output buffer so we not leak and rethrow exception.
148+ output.release();
149+ throw new IOException(e);
150+ }
151+ return output;
152+ }
153+
154+ private ByteBuf decompressHeap(ByteBuf input) throws IOException {
155+ // Not a direct buffer so use byte arrays...
156+ byte[] in = input.array();
157+ int len = input.readableBytes();
158+ int uncompressedLength = input.readInt();
159+ int inOffset = input.arrayOffset() + input.readerIndex();
160+ // Increase reader index.
161+ input.readerIndex(input.writerIndex());
162+
163+ // Allocate a heap buffer from the ByteBufAllocator as we may use a PooledByteBufAllocator and so
164+ // can eliminate the overhead of allocate a new byte[].
165+ ByteBuf output = input.alloc().heapBuffer(uncompressedLength);
166+ try {
167+ int offset = output.arrayOffset() + output.writerIndex();
168+ byte out[] = output.array();
169+ int read = decompressor.decompress(in, inOffset, out, offset, uncompressedLength);
170+ if (read != len - INTEGER_BYTES)
171+ throw new IOException("Compressed lengths mismatch");
172+
173+ // Set the writer index so the amount of written bytes is reflected
174+ output.writerIndex(output.writerIndex() + uncompressedLength);
175+ } catch (Exception e) {
176+ // release output buffer so we not leak and rethrow exception.
177+ output.release();
178+ throw new IOException(e);
179+ }
180+ return output;
181+ }
182+}
modified driver-core/src/main/java/com/datastax/driver/core/ProtocolOptions.java +2 −2
@@ -41,7 +41,7 @@
4141 SNAPPY("snappy") {
4242 @Override
4343 FrameCompressor compressor() {
44- return FrameCompressor.SnappyCompressor.instance;
44+ return SnappyCompressor.instance;
4545 }
4646 },
4747 /**
@@ -50,7 +50,7 @@
5050 LZ4("lz4") {
5151 @Override
5252 FrameCompressor compressor() {
53- return FrameCompressor.LZ4Compressor.instance;
53+ return LZ4Compressor.instance;
5454 }
5555 };
5656
added driver-core/src/main/java/com/datastax/driver/core/SnappyCompressor.java +170 −0
@@ -0,0 +1,170 @@
1+/*
2+ * Copyright (C) 2012-2015 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 com.datastax.driver.core.exceptions.DriverInternalError;
19+import io.netty.buffer.ByteBuf;
20+import org.slf4j.Logger;
21+import org.slf4j.LoggerFactory;
22+import org.xerial.snappy.Snappy;
23+
24+import java.io.IOException;
25+import java.nio.ByteBuffer;
26+
27+class SnappyCompressor extends FrameCompressor {
28+
29+ private static final Logger logger = LoggerFactory.getLogger(SnappyCompressor.class);
30+
31+ static final SnappyCompressor instance;
32+
33+ static {
34+ SnappyCompressor i;
35+ try {
36+ i = new SnappyCompressor();
37+ } catch (NoClassDefFoundError e) {
38+ i = null;
39+ logger.warn("Cannot find Snappy class, you should make sure the Snappy library is in the classpath if you intend to use it. Snappy compression will not be available for the protocol.");
40+ } catch (Throwable e) {
41+ i = null;
42+ logger.warn("Error loading Snappy library ({}). Snappy compression will not be available for the protocol.", e.toString());
43+ }
44+ instance = i;
45+ }
46+
47+ private SnappyCompressor() {
48+ // this would throw java.lang.NoClassDefFoundError if Snappy class
49+ // wasn't found at runtime which should be processed by the calling method
50+ Snappy.getNativeLibraryVersion();
51+ }
52+
53+ @Override
54+ Frame compress(Frame frame) throws IOException {
55+ ByteBuf input = frame.body;
56+ ByteBuf frameBody = input.isDirect() ? compressDirect(input) : compressHeap(input);
57+ return frame.with(frameBody);
58+ }
59+
60+ private ByteBuf compressDirect(ByteBuf input) throws IOException {
61+ int maxCompressedLength = Snappy.maxCompressedLength(input.readableBytes());
62+ // If the input is direct we will allocate a direct output buffer as well as this will allow us to use
63+ // Snappy.compress(ByteBuffer, ByteBuffer) and so eliminate memory copies.
64+ ByteBuf output = input.alloc().directBuffer(maxCompressedLength);
65+ try {
66+ ByteBuffer in = inputNioBuffer(input);
67+ // Increase reader index.
68+ input.readerIndex(input.writerIndex());
69+
70+ ByteBuffer out = outputNioBuffer(output);
71+ int written = Snappy.compress(in, out);
72+ // Set the writer index so the amount of written bytes is reflected
73+ output.writerIndex(output.writerIndex() + written);
74+ } catch (IOException e) {
75+ // release output buffer so we not leak and rethrow exception.
76+ output.release();
77+ throw e;
78+ }
79+ return output;
80+ }
81+
82+ private ByteBuf compressHeap(ByteBuf input) throws IOException {
83+ int maxCompressedLength = Snappy.maxCompressedLength(input.readableBytes());
84+ int inOffset = input.arrayOffset() + input.readerIndex();
85+ byte[] in = input.array();
86+ int len = input.readableBytes();
87+ // Increase reader index.
88+ input.readerIndex(input.writerIndex());
89+
90+ // Allocate a heap buffer from the ByteBufAllocator as we may use a PooledByteBufAllocator and so
91+ // can eliminate the overhead of allocate a new byte[].
92+ ByteBuf output = input.alloc().heapBuffer(maxCompressedLength);
93+ try {
94+ // Calculate the correct offset.
95+ int offset = output.arrayOffset() + output.writerIndex();
96+ byte[] out = output.array();
97+ int written = Snappy.compress(in, inOffset, len, out, offset);
98+
99+ // Increase the writerIndex with the written bytes.
100+ output.writerIndex(output.writerIndex() + written);
101+ } catch (IOException e) {
102+ // release output buffer so we not leak and rethrow exception.
103+ output.release();
104+ throw e;
105+ }
106+ return output;
107+ }
108+
109+ @Override
110+ Frame decompress(Frame frame) throws IOException {
111+ ByteBuf input = frame.body;
112+ ByteBuf frameBody = input.isDirect() ? decompressDirect(input) : decompressHeap(input);
113+ return frame.with(frameBody);
114+ }
115+
116+ private ByteBuf decompressDirect(ByteBuf input) throws IOException {
117+ ByteBuffer in = inputNioBuffer(input);
118+ // Increase reader index.
119+ input.readerIndex(input.writerIndex());
120+
121+ if (!Snappy.isValidCompressedBuffer(in))
122+ throw new DriverInternalError("Provided frame does not appear to be Snappy compressed");
123+
124+ // If the input is direct we will allocate a direct output buffer as well as this will allow us to use
125+ // Snappy.compress(ByteBuffer, ByteBuffer) and so eliminate memory copies.
126+ ByteBuf output = input.alloc().directBuffer(Snappy.uncompressedLength(in));
127+ try {
128+ ByteBuffer out = outputNioBuffer(output);
129+
130+ int size = Snappy.uncompress(in, out);
131+ // Set the writer index so the amount of written bytes is reflected
132+ output.writerIndex(output.writerIndex() + size);
133+ } catch (IOException e) {
134+ // release output buffer so we not leak and rethrow exception.
135+ output.release();
136+ throw e;
137+ }
138+ return output;
139+ }
140+
141+ private ByteBuf decompressHeap(ByteBuf input) throws IOException {
142+ // Not a direct buffer so use byte arrays...
143+ int inOffset = input.arrayOffset() + input.readerIndex();
144+ byte[] in = input.array();
145+ int len = input.readableBytes();
146+ // Increase reader index.
147+ input.readerIndex(input.writerIndex());
148+
149+ if (!Snappy.isValidCompressedBuffer(in, inOffset, len))
150+ throw new DriverInternalError("Provided frame does not appear to be Snappy compressed");
151+
152+ // Allocate a heap buffer from the ByteBufAllocator as we may use a PooledByteBufAllocator and so
153+ // can eliminate the overhead of allocate a new byte[].
154+ ByteBuf output = input.alloc().heapBuffer(Snappy.uncompressedLength(in, inOffset, len));
155+ try {
156+ // Calculate the correct offset.
157+ int offset = output.arrayOffset() + output.writerIndex();
158+ byte[] out = output.array();
159+ int written = Snappy.uncompress(in, inOffset, len, out, offset);
160+
161+ // Increase the writerIndex with the written bytes.
162+ output.writerIndex(output.writerIndex() + written);
163+ } catch (IOException e) {
164+ // release output buffer so we not leak and rethrow exception.
165+ output.release();
166+ throw e;
167+ }
168+ return output;
169+ }
170+}
added driver-core/src/test/java/com/datastax/driver/core/CompressionTest.java +55 −0
@@ -0,0 +1,55 @@
1+/*
2+ * Copyright (C) 2012-2015 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.Locale;
19+
20+import static com.datastax.driver.core.SessionTest.checkExecuteResultSet;
21+import static org.assertj.core.api.Assertions.assertThat;
22+
23+public class CompressionTest extends CCMTestsSupport {
24+
25+ private static String TABLE = "test";
26+
27+ public void onTestContextInitialized() {
28+ execute(String.format("CREATE TABLE %s (k text PRIMARY KEY, t text, i int, f float)", TABLE));
29+ }
30+
31+ void compressionTest(ProtocolOptions.Compression compression) {
32+ cluster().getConfiguration().getProtocolOptions().setCompression(compression);
33+ try {
34+ Session compressedSession = cluster().connect(keyspace);
35+
36+ // Simple calls to all versions of the execute/executeAsync methods
37+ String key = "execute_compressed_test_" + compression;
38+ ResultSet rs = compressedSession.execute(String.format(Locale.US, "INSERT INTO %s (k, t, i, f) VALUES ('%s', '%s', %d, %f)", TABLE, key, "foo", 42, 24.03f));
39+ assertThat(rs.isExhausted()).isTrue();
40+
41+ String SELECT_ALL = String.format(TestUtils.SELECT_ALL_FORMAT + " WHERE k = '%s'", TABLE, key);
42+
43+ // execute
44+ checkExecuteResultSet(compressedSession.execute(SELECT_ALL), key);
45+ checkExecuteResultSet(compressedSession.execute(new SimpleStatement(SELECT_ALL).setConsistencyLevel(ConsistencyLevel.ONE)), key);
46+
47+ // executeAsync
48+ checkExecuteResultSet(compressedSession.executeAsync(SELECT_ALL).getUninterruptibly(), key);
49+ checkExecuteResultSet(compressedSession.executeAsync(new SimpleStatement(SELECT_ALL).setConsistencyLevel(ConsistencyLevel.ONE)).getUninterruptibly(), key);
50+
51+ } finally {
52+ cluster().getConfiguration().getProtocolOptions().setCompression(ProtocolOptions.Compression.NONE);
53+ }
54+ }
55+}
added driver-core/src/test/java/com/datastax/driver/core/DirectCompressionTest.java +47 −0
@@ -0,0 +1,47 @@
1+/*
2+ * Copyright (C) 2012-2015 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 com.datastax.driver.core.utils.CassandraVersion;
19+import org.testng.annotations.Test;
20+
21+public class DirectCompressionTest extends CompressionTest {
22+
23+ /**
24+ * Validates that a session can be established using snappy compression and executes some queries that inserts and
25+ * retrieves data using that session().
26+ *
27+ * @test_category connection:compression
28+ * @expected_result session established and queries made successfully using it.
29+ */
30+ @Test(groups = "short")
31+ public void should_function_with_snappy_compression() throws Exception {
32+ compressionTest(ProtocolOptions.Compression.SNAPPY);
33+ }
34+
35+ /**
36+ * Validates that a session can be established using lz4 compression and executes some queries that inserts and
37+ * retrieves data using that session().
38+ *
39+ * @test_category connection:compression
40+ * @expected_result session established and queries made successfully using it.
41+ */
42+ @Test(groups = "short")
43+ @CassandraVersion(major = 2.0)
44+ public void should_function_with_lz4_compression() throws Exception {
45+ compressionTest(ProtocolOptions.Compression.LZ4);
46+ }
47+}
added driver-core/src/test/java/com/datastax/driver/core/HeapCompressionTest.java +54 −0
@@ -0,0 +1,54 @@
1+/*
2+ * Copyright (C) 2012-2015 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 com.datastax.driver.core.utils.CassandraVersion;
19+import org.testng.annotations.BeforeClass;
20+import org.testng.annotations.Test;
21+
22+public class HeapCompressionTest extends CompressionTest {
23+
24+ @BeforeClass(groups = "isolated")
25+ public void beforeTestClass() throws Exception {
26+ // Configure with noPreferDirect and noUnsafe to force heap buffers.
27+ System.setProperty("io.netty.noPreferDirect", "true");
28+ System.setProperty("io.netty.noUnsafe", "true");
29+ super.beforeTestClass();
30+ }
31+
32+ /**
33+ * Validates that snappy compression still works when using heap buffers.
34+ *
35+ * @test_category connection:compression
36+ * @expected_result session established and queries made successfully using it.
37+ */
38+ @Test(groups = "isolated")
39+ public void should_function_with_snappy_compression() throws Exception {
40+ compressionTest(ProtocolOptions.Compression.SNAPPY);
41+ }
42+
43+ /**
44+ * Validates that lz4 compression still works when using heap buffers.
45+ *
46+ * @test_category connection:compression
47+ * @expected_result session established and queries made successfully using it.
48+ */
49+ @Test(groups = "isolated")
50+ @CassandraVersion(major = 2.0)
51+ public void should_function_with_lz4_compression() throws Exception {
52+ compressionTest(ProtocolOptions.Compression.LZ4);
53+ }
54+}
modified driver-core/src/test/java/com/datastax/driver/core/SessionTest.java +1 −52
@@ -16,7 +16,6 @@
1616 package com.datastax.driver.core;
1717
1818 import com.datastax.driver.core.exceptions.SyntaxError;
19-import com.datastax.driver.core.utils.CassandraVersion;
2019 import com.google.common.util.concurrent.ListenableFuture;
2120 import org.testng.annotations.Test;
2221
@@ -81,7 +80,7 @@
8180 checkExecuteResultSet(session().executeAsync(bs.setConsistencyLevel(ConsistencyLevel.ONE)).getUninterruptibly(), key);
8281 }
8382
84- private static void checkExecuteResultSet(ResultSet rs, String key) {
83+ static void checkExecuteResultSet(ResultSet rs, String key) {
8584 assertThat(rs.isExhausted()).isFalse();
8685 Row row = rs.one();
8786 assertThat(rs.isExhausted()).isTrue();
@@ -104,56 +103,6 @@
104103 assertThat(rows.get(0).getLong("c")).isEqualTo(2L);
105104 }
106105
107- /**
108- * Validates that a session can be established using snappy compression and executes some queries that inserts and
109- * retrieves data using that session().
110- *
111- * @test_category connection:compression
112- * @expected_result session established and queries made successfully using it.
113- */
114- @Test(groups = "short")
115- public void should_function_with_snappy_compression() throws Exception {
116- compressionTest(ProtocolOptions.Compression.SNAPPY);
117- }
118-
119- /**
120- * Validates that a session can be established using lz4 compression and executes some queries that inserts and
121- * retrieves data using that session().
122- *
123- * @test_category connection:compression
124- * @expected_result session established and queries made successfully using it.
125- */
126- @Test(groups = "short")
127- @CassandraVersion(major = 2.0)
128- public void should_function_with_lz4_compression() throws Exception {
129- compressionTest(ProtocolOptions.Compression.LZ4);
130- }
131-
132- public void compressionTest(ProtocolOptions.Compression compression) {
133- cluster().getConfiguration().getProtocolOptions().setCompression(compression);
134- try {
135- Session compressedSession = cluster().connect(keyspace);
136-
137- // Simple calls to all versions of the execute/executeAsync methods
138- String key = "execute_compressed_test_" + compression;
139- ResultSet rs = compressedSession.execute(String.format(Locale.US, "INSERT INTO %s (k, t, i, f) VALUES ('%s', '%s', %d, %f)", TABLE3, key, "foo", 42, 24.03f));
140- assertThat(rs.isExhausted()).isTrue();
141-
142- String SELECT_ALL = String.format(TestUtils.SELECT_ALL_FORMAT + " WHERE k = '%s'", TABLE3, key);
143-
144- // execute
145- checkExecuteResultSet(compressedSession.execute(SELECT_ALL), key);
146- checkExecuteResultSet(compressedSession.execute(new SimpleStatement(SELECT_ALL).setConsistencyLevel(ConsistencyLevel.ONE)), key);
147-
148- // executeAsync
149- checkExecuteResultSet(compressedSession.executeAsync(SELECT_ALL).getUninterruptibly(), key);
150- checkExecuteResultSet(compressedSession.executeAsync(new SimpleStatement(SELECT_ALL).setConsistencyLevel(ConsistencyLevel.ONE)).getUninterruptibly(), key);
151-
152- } finally {
153- cluster().getConfiguration().getProtocolOptions().setCompression(ProtocolOptions.Compression.NONE);
154- }
155- }
156-
157106 /**
158107 * Checks for deadlocks when a session shutdown races with the initialization of the cluster (JAVA-418).
159108 */
modified pom.xml +1 −1
@@ -285,7 +285,7 @@
285285 </execution>
286286 </executions>
287287 <configuration>
288- <comparisonVersion>3.0.2</comparisonVersion>
288+ <comparisonVersion>3.0.3</comparisonVersion>
289289 <ignoredDifferencesFile>../clirr-ignores.xml</ignoredDifferencesFile>
290290 </configuration>
291291 <!--