summaryrefslogtreecommitdiffstats
path: root/container-search/src/main/java/com/yahoo/fs4/BasicPacket.java
blob: f9fce278d9e93b7694f3611bc6a61db4eb5cca88 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.fs4;

import com.yahoo.compress.CompressionType;
import com.yahoo.compress.Compressor;
import com.yahoo.log.LogLevel;
import net.jpountz.lz4.LZ4Compressor;
import net.jpountz.lz4.LZ4Factory;

import java.nio.ByteBuffer;
import java.util.Optional;
import java.util.logging.Logger;

/**
 * Superclass of fs4 packets
 *
 * @author bratseth
 */
public abstract class BasicPacket {

    private final Compressor compressor = new Compressor();

    private static Logger log = Logger.getLogger(QueryResultPacket.class.getName());
    private static int DEFAULT_WRITE_BUFFER_SIZE = (10 * 1024);
    public static final int CODE_MASK = 0x00ff_ffff;  // Reserve upper byte for flags.

    protected byte[] encodedBody;

    protected ByteBuffer encodingBuffer;

    /**
     * The length of this packet in bytes or -1 if not known
     */
    protected int length=-1;

    /**
     * A timestamp which can be set or inspected by clients of this class
     * but which is never updated by the class itself.  This is mostly
     * a convenience for when you need to queue packets or retain them
     * in some structure where their validity is limited by a timeout
     * or similar.
     */
    private long timeStamp = -1;

    private int compressionLimit = 0;

    private CompressionType compressionType;

    /**
     * Sets the number of bytes the package must be before activating compression.
     * A value of 0 means no compression.
     * @param limit smallest package size that triggers compression.
     */
    public void setCompressionLimit(int limit) { compressionLimit = limit; }

    public void setCompressionType(String type) {
        compressionType = CompressionType.valueOf(type);
    }

    /**
     * Fills this package from a byte buffer positioned at the first byte of the package
     *
     * @return this for convenience
     * @throws UnsupportedOperationException if not implemented in the subclass
     */
    public BasicPacket decode(ByteBuffer buffer) {
        length=buffer.getInt()+4; // Streamed packet length is the length-4
        int code=buffer.getInt();

        decodeAndDecompressBody(buffer, code, length - 2*4);
        return this;
    }

    protected void decodeAndDecompressBody(ByteBuffer buffer, int code, int packetLength) {
        byte compressionType = (byte)((code & ~CODE_MASK) >> 24);
        boolean isCompressed = compressionType != 0;
        codeDecodedHook(code & CODE_MASK);
        if (isCompressed) {
            int uncompressedSize = buffer.getInt();
            int compressedSize = packetLength - 4;
            int offset = 0;
            byte[] compressedData;
            if (buffer.hasArray()) {
                compressedData = buffer.array();
                offset = buffer.arrayOffset() + buffer.position();
                buffer.position(buffer.position() + compressedSize);
            } else {
                compressedData = new byte[compressedSize];
                buffer.get(compressedData);
            }
            byte[] body = compressor.decompress(CompressionType.valueOf(compressionType), compressedData, offset, uncompressedSize, Optional.of(compressedSize));
            ByteBuffer bodyBuffer = ByteBuffer.wrap(body);
            length += uncompressedSize - (compressedSize + 4);
            decodeBody(bodyBuffer);
        } else {
            decodeBody(buffer);
        }
    }

    /**
     * Decodes the body of this package from a byte buffer
     * positioned at the first byte of the package.
     *
     * @throws UnsupportedOperationException if not implemented in the subclass
     */
    public void decodeBody(ByteBuffer buffer) {
        throw new UnsupportedOperationException("Decoding of " + this +
                                                " is not implemented");
    }

    /**
     * Called when the packet code is decoded.
     * This default implementation just throws an exception if the code
     * is not the code of this packet. Packets which has several possible codes
     * will use this method to store the code.
     */
    protected void codeDecodedHook(int code) {
        if (code!=getCode())
            throw new RuntimeException("Can not decode " + code + " into " + this);
    }

    /**
     * <p>Encodes this package onto the given buffer at the current position.
     * The position of the buffer after encoding is the byte following
     * the last encoded byte.</p>
     *
     * <p>This method will ensure that everything is written provided
     * sufficient capacity regardless of the buffer limit.
     * When returning, the limit is at the end of the package (qual to the
     * position).</p>
     *
     * @return this for convenience
     * @throws UnsupportedOperationException if not implemented in the subclass
     */
    public BasicPacket encode(ByteBuffer buffer)
        throws BufferTooSmallException
    {
        int oldLimit = buffer.limit();
        int startPosition = buffer.position();

        buffer.limit(buffer.capacity());
        try {
            buffer.putInt(4); // Real length written later, when we know it
            buffer.putInt(getCode());

            encodeAndCompressBody(buffer, startPosition);
        }
        catch (java.nio.BufferOverflowException e) {
            // reset buffer to expected state
            buffer.position(startPosition);
            buffer.limit(oldLimit);
            throw new BufferTooSmallException("Destination buffer too small while encoding packet");
        }

        return this;
    }

    protected void encodeAndCompressBody(ByteBuffer buffer, int startPosition) {
        int startOfBody = buffer.position();
        encodeBody(buffer);
        setEncodedBody(buffer, startOfBody, buffer.position() - startOfBody);
        length = buffer.position() - startPosition;

        if (compressionLimit != 0 && length-4 > compressionLimit) {
            byte[] compressedBody;
            compressionType = CompressionType.LZ4;
            LZ4Factory factory = LZ4Factory.fastestInstance();
            LZ4Compressor compressor = factory.fastCompressor();
            compressedBody = compressor.compress(encodedBody);

            log.log(LogLevel.DEBUG, "Uncompressed size: " + encodedBody.length + ", Compressed size: " + compressedBody.length);
            if (compressedBody.length + 4 < encodedBody.length) {
                buffer.position(startPosition);
                buffer.putInt(compressedBody.length + startOfBody - startPosition + 4 - 4);  // +4 for compressed size
                buffer.putInt(getCompressedCode(compressionType));
                buffer.position(startOfBody);
                buffer.putInt(encodedBody.length);
                buffer.put(compressedBody);
                buffer.limit(buffer.position());
                return;
            }
        }
        buffer.putInt(startPosition, length - 4); // Encoded length 4 less than actual length
        buffer.limit(buffer.position());
    }

    private int getCompressedCode(CompressionType compression) {
        int code = compression.getCode();
        return getCode() | (code << 24);
    }

    /**
     * Encodes the body of this package onto the given buffer at the current position.
     * The position of the buffer after encoding is the byte following
     * the last encoded byte.
     *
     * @throws UnsupportedOperationException if not implemented in the subclass
     */
    protected void encodeBody(ByteBuffer buffer) {
        throw new UnsupportedOperationException("Encoding of " + this + " is not implemented");
    }

    protected void setEncodedBody(ByteBuffer b, int start, int length) {
        encodedBody = new byte[length];
        b.position(start);
        b.get(encodedBody);
    }

    public boolean isEncoded() {
        return encodedBody != null;
    }

    /**
     * Just a place holder to make the APIs simpler.
     */
    public Packet encode(ByteBuffer buffer, int channel) throws BufferTooSmallException {
        throw new UnsupportedOperationException("This class does not support a channel ID");
    }

    /**
     * Allocate the needed buffers and encode the packet using the given
     * channel ID (if pertinent).
     *
     * If this packet does not use a channel ID, the ID will be ignored.
     */
    public final void allocateAndEncode(int channelId) {
        allocateAndEncode(channelId, DEFAULT_WRITE_BUFFER_SIZE);
    }

    private final void allocateAndEncode(int channelId, int initialSize) {
        if (encodingBuffer != null) {
            patchChannelId(encodingBuffer, channelId);
            return;
        }

        int size = initialSize;
        ByteBuffer buffer = ByteBuffer.allocate(size);
        while (true) {
            try {
                if (hasChannelId()) {
                    encode(buffer, channelId);
                } else {
                    encode(buffer);
                }
                buffer.flip();
                encodingBuffer = buffer;
                break;
            }
            catch (BufferTooSmallException e) {
                size *= 2;
                buffer = ByteBuffer.allocate(size);
            }
        }
    }

    // No channel ID for BasicPacket instances, so it's a NOP
    protected void patchChannelId(ByteBuffer buf, int channelId) {}

    /**
     * Return buffer containing the encoded form of this package and
     * remove internal reference to it.
     */
    public final ByteBuffer grantEncodingBuffer(int channelId) {
        ByteBuffer b;
        if (encodingBuffer == null) {
            allocateAndEncode(channelId);
        } else {
            patchChannelId(encodingBuffer, channelId);
        }
        b = encodingBuffer;
        encodingBuffer = null;
        return b;
    }

    public final ByteBuffer grantEncodingBuffer(int channelId, int initialSize) {
        ByteBuffer b;
        if (encodingBuffer == null) {
            allocateAndEncode(channelId, initialSize);
        } else {
            patchChannelId(encodingBuffer, channelId);
        }
        b = encodingBuffer;
        encodingBuffer = null;
        return b;
    }

    /** Returns the code of this package */
    public abstract int getCode();

    /**
     * Returns the length of this body (including header (8 bytes) and body),
     * or -1 if not known.
     * Note that the streamed packet format length is 4 bytes less than this length,
     * for unknown reasons.
     * The length is always known when decodeBody is called.
     */
    public int getLength() {
        return length;
    }

    /**
     * Set the timestamp field of the packet.
     *
     * A timestamp which can be set or inspected by clients of this class
     * but which is never updated by the class itself.  This is mostly
     * a convenience for when you need to queue packets or retain them
     * in some structure where their validity is limited by a timeout
     * or similar.
     */
    public void setTimestamp (long timeStamp) {
        this.timeStamp = timeStamp;
    }

    /**
     * Get the timestamp field of this packet.  Note that this is
     * <b>not</b> part of the FS4 protocol.  @see #setTimestamp for
     * more information
     *
     */
    public long getTimestamp () {
        return timeStamp;
    }

    public String toString() {
        return "packet with code " + getCode();
    }

    /** Whether this is a packets which can encode a channel ID. */
    public boolean hasChannelId() {
        return false;
    }

}