Debian Codegraph @

src/main/org/h2/mvstore/StreamStore.java

raw
1 /*
2 * Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0,
3 * and the EPL 1.0 (https://h2database.com/html/license.html).
4 * Initial Developer: H2 Group
5 */
6 package org.h2.mvstore;
7
8 import java.io.ByteArrayInputStream;
9 import java.io.ByteArrayOutputStream;
10 import java.io.IOException;
11 import java.io.InputStream;
12 import java.nio.ByteBuffer;
13 import java.util.Arrays;
14 import java.util.Map;
15 import java.util.concurrent.atomic.AtomicLong;
16 import java.util.concurrent.atomic.AtomicReference;
17 import java.util.function.IntConsumer;
18
19 /**
20 * A facility to store streams in a map. Streams are split into blocks, which
21 * are stored in a map. Very small streams are inlined in the stream id.
22 * <p>
23 * The key of the map is a long (incremented for each stored block). The default
24 * initial value is 0. Before storing blocks into the map, the stream store
25 * checks if there is already a block with the next key, and if necessary
26 * searches the next free entry using a binary search (0 to Long.MAX_VALUE).
27 * <p>
28 * Before storing
29 * <p>
30 * The format of the binary id is: An empty id represents 0 bytes of data.
31 * In-place data is encoded as 0, the size (a variable size int), then the data.
32 * A stored block is encoded as 1, the length of the block (a variable size
33 * int), then the key (a variable size long). Multiple ids can be concatenated
34 * to concatenate the data. If the id is large, it is stored itself, which is
35 * encoded as 2, the total length (a variable size long), and the key of the
36 * block that contains the id (a variable size long).
37 */
38 public final class StreamStore
39 {
40 private final Map<Long, byte[]> map;
41 private final int minBlockSize;
42 private final int maxBlockSize;
43 private final AtomicLong nextKey = new AtomicLong();
44 private final AtomicReference<byte[]> nextBuffer = new AtomicReference<>();
45 private final IntConsumer onStoreCallback;
46
47 /**
48 * Create a stream store instance.
49 *
50 * @param map the map to store blocks of data
51 */
52 public StreamStore(Map<Long, byte[]> map) {
53 this(map, 256, 256 * 1024, null);
54 }
55
56 public StreamStore(Map<Long, byte[]> map, int minBlockSize, int maxBlockSize) {
57 this(map, minBlockSize, maxBlockSize, null);
58 }
59
60 public StreamStore(Map<Long, byte[]> map, IntConsumer onStoreCallback) {
61 this(map, 256, 256 * 1024, onStoreCallback);
62 }
63
64 public StreamStore(Map<Long, byte[]> map, int minBlockSize, int maxBlockSize, IntConsumer onStoreCallback) {
65 this.map = map;
66 this.minBlockSize = minBlockSize;
67 this.maxBlockSize = maxBlockSize;
68 this.onStoreCallback = onStoreCallback;
69 }
70
71 public Map<Long, byte[]> getMap() {
72 return map;
73 }
74
75 public void setNextKey(long nextKey) {
76 this.nextKey.set(nextKey);
77 }
78
79 public long getNextKey() {
80 return nextKey.get();
81 }
82
83 public int getMinBlockSize() {
84 return minBlockSize;
85 }
86
87 public long getMaxBlockSize() {
88 return maxBlockSize;
89 }
90
91 /**
92 * Store the stream, and return the id. The stream is not closed.
93 *
94 * @param in the stream
95 * @return the id (potentially an empty array)
96 * @throws IOException If an I/O error occurs
97 */
98 public byte[] put(InputStream in) throws IOException {
99 ByteArrayOutputStream id = new ByteArrayOutputStream();
100 int level = 0;
101 try {
102 while (!put(id, in, level)) {
103 if (id.size() > maxBlockSize / 2) {
104 id = putIndirectId(id);
105 level++;
106 }
107 }
108 } catch (IOException e) {
109 remove(id.toByteArray());
110 throw e;
111 }
112 if (id.size() > minBlockSize * 2) {
113 id = putIndirectId(id);
114 }
115 return id.toByteArray();
116 }
117
118 private boolean put(ByteArrayOutputStream id, InputStream in, int level)
119 throws IOException {
120 if (level > 0) {
121 ByteArrayOutputStream id2 = new ByteArrayOutputStream();
122 while (true) {
123 boolean eof = put(id2, in, level - 1);
124 if (id2.size() > maxBlockSize / 2) {
125 id2 = putIndirectId(id2);
126 id2.writeTo(id);
127 return eof;
128 } else if (eof) {
129 id2.writeTo(id);
130 return true;
131 }
132 }
133 }
134 byte[] readBuffer = nextBuffer.getAndSet(null);
135 if (readBuffer == null) {
136 readBuffer = new byte[maxBlockSize];
137 }
138 byte[] buff = read(in, readBuffer);
139 if (buff != readBuffer) {
140 // re-use the buffer if the result was shorter
141 nextBuffer.set(readBuffer);
142 }
143 int len = buff.length;
144 if (len == 0) {
145 return true;
146 }
147 boolean eof = len < maxBlockSize;
148 if (len < minBlockSize) {
149 // in-place: 0, len (int), data
150 id.write(0);
151 DataUtils.writeVarInt(id, len);
152 id.write(buff);
153 } else {
154 // block: 1, len (int), blockId (long)
155 id.write(1);
156 DataUtils.writeVarInt(id, len);
157 DataUtils.writeVarLong(id, writeBlock(buff));
158 }
159 return eof;
160 }
161
162 private static byte[] read(InputStream in, byte[] target)
163 throws IOException {
164 int copied = 0;
165 int remaining = target.length;
166 while (remaining > 0) {
167 try {
168 int len = in.read(target, copied, remaining);
169 if (len < 0) {
170 return Arrays.copyOf(target, copied);
171 }
172 copied += len;
173 remaining -= len;
174 } catch (RuntimeException e) {
175 throw new IOException(e);
176 }
177 }
178 return target;
179 }
180
181 private ByteArrayOutputStream putIndirectId(ByteArrayOutputStream id)
182 throws IOException {
183 byte[] data = id.toByteArray();
184 id = new ByteArrayOutputStream();
185 // indirect: 2, total len (long), blockId (long)
186 id.write(2);
187 DataUtils.writeVarLong(id, length(data));
188 DataUtils.writeVarLong(id, writeBlock(data));
189 return id;
190 }
191
192 private long writeBlock(byte[] data) {
193 long key = getAndIncrementNextKey();
194 map.put(key, data);
195 if (onStoreCallback != null) {
196 onStoreCallback.accept(data.length);
197 }
198 return key;
199 }
200
201 /**
202 * Generate a new key.
203 *
204 * @return the new key
205 */
206 private long getAndIncrementNextKey() {
207 long key = nextKey.getAndIncrement();
208 if (!map.containsKey(key)) {
209 return key;
210 }
211 // search the next free id using binary search
212 synchronized (this) {
213 long low = key, high = Long.MAX_VALUE;
214 while (low < high) {
215 long x = (low + high) >>> 1;
216 if (map.containsKey(x)) {
217 low = x + 1;
218 } else {
219 high = x;
220 }
221 }
222 key = low;
223 nextKey.set(key + 1);
224 return key;
225 }
226 }
227
228 /**
229 * Get the key of the biggest block, of -1 for inline data.
230 * This method is used to garbage collect orphaned blocks.
231 *
232 * @param id the id
233 * @return the key, or -1
234 */
235 public long getMaxBlockKey(byte[] id) {
236 long maxKey = -1;
237 ByteBuffer idBuffer = ByteBuffer.wrap(id);
238 while (idBuffer.hasRemaining()) {
239 switch (idBuffer.get()) {
240 case 0:
241 // in-place: 0, len (int), data
242 int len = DataUtils.readVarInt(idBuffer);
243 idBuffer.position(idBuffer.position() + len);
244 break;
245 case 1:
246 // block: 1, len (int), blockId (long)
247 DataUtils.readVarInt(idBuffer);
248 long k = DataUtils.readVarLong(idBuffer);
249 maxKey = Math.max(maxKey, k);
250 break;
251 case 2:
252 // indirect: 2, total len (long), blockId (long)
253 DataUtils.readVarLong(idBuffer);
254 long k2 = DataUtils.readVarLong(idBuffer);
255 maxKey = k2;
256 byte[] r = map.get(k2);
257 // recurse
258 long m = getMaxBlockKey(r);
259 if (m >= 0) {
260 maxKey = Math.max(maxKey, m);
261 }
262 break;
263 default:
264 throw DataUtils.newIllegalArgumentException(
265 "Unsupported id {0}", Arrays.toString(id));
266 }
267 }
268 return maxKey;
269 }
270
271 /**
272 * Remove all stored blocks for the given id.
273 *
274 * @param id the id
275 */
276 public void remove(byte[] id) {
277 ByteBuffer idBuffer = ByteBuffer.wrap(id);
278 while (idBuffer.hasRemaining()) {
279 switch (idBuffer.get()) {
280 case 0:
281 // in-place: 0, len (int), data
282 int len = DataUtils.readVarInt(idBuffer);
283 idBuffer.position(idBuffer.position() + len);
284 break;
285 case 1:
286 // block: 1, len (int), blockId (long)
287 DataUtils.readVarInt(idBuffer);
288 long k = DataUtils.readVarLong(idBuffer);
289 map.remove(k);
290 break;
291 case 2:
292 // indirect: 2, total len (long), blockId (long)
293 DataUtils.readVarLong(idBuffer);
294 long k2 = DataUtils.readVarLong(idBuffer);
295 // recurse
296 remove(map.get(k2));
297 map.remove(k2);
298 break;
299 default:
300 throw DataUtils.newIllegalArgumentException(
301 "Unsupported id {0}", Arrays.toString(id));
302 }
303 }
304 }
305
306 /**
307 * Convert the id to a human readable string.
308 *
309 * @param id the stream id
310 * @return the string
311 */
312 public static String toString(byte[] id) {
313 StringBuilder buff = new StringBuilder();
314 ByteBuffer idBuffer = ByteBuffer.wrap(id);
315 long length = 0;
316 while (idBuffer.hasRemaining()) {
317 long block;
318 int len;
319 switch (idBuffer.get()) {
320 case 0:
321 // in-place: 0, len (int), data
322 len = DataUtils.readVarInt(idBuffer);
323 idBuffer.position(idBuffer.position() + len);
324 buff.append("data len=").append(len);
325 length += len;
326 break;
327 case 1:
328 // block: 1, len (int), blockId (long)
329 len = DataUtils.readVarInt(idBuffer);
330 length += len;
331 block = DataUtils.readVarLong(idBuffer);
332 buff.append("block ").append(block).append(" len=").append(len);
333 break;
334 case 2:
335 // indirect: 2, total len (long), blockId (long)
336 len = DataUtils.readVarInt(idBuffer);
337 length += DataUtils.readVarLong(idBuffer);
338 block = DataUtils.readVarLong(idBuffer);
339 buff.append("indirect block ").append(block).append(" len=").append(len);
340 break;
341 default:
342 buff.append("error");
343 }
344 buff.append(", ");
345 }
346 buff.append("length=").append(length);
347 return buff.toString();
348 }
349
350 /**
351 * Calculate the number of data bytes for the given id. As the length is
352 * encoded in the id, this operation does not cause any reads in the map.
353 *
354 * @param id the id
355 * @return the length
356 */
357 public long length(byte[] id) {
358 ByteBuffer idBuffer = ByteBuffer.wrap(id);
359 long length = 0;
360 while (idBuffer.hasRemaining()) {
361 switch (idBuffer.get()) {
362 case 0:
363 // in-place: 0, len (int), data
364 int len = DataUtils.readVarInt(idBuffer);
365 idBuffer.position(idBuffer.position() + len);
366 length += len;
367 break;
368 case 1:
369 // block: 1, len (int), blockId (long)
370 length += DataUtils.readVarInt(idBuffer);
371 DataUtils.readVarLong(idBuffer);
372 break;
373 case 2:
374 // indirect: 2, total len (long), blockId (long)
375 length += DataUtils.readVarLong(idBuffer);
376 DataUtils.readVarLong(idBuffer);
377 break;
378 default:
379 throw DataUtils.newIllegalArgumentException(
380 "Unsupported id {0}", Arrays.toString(id));
381 }
382 }
383 return length;
384 }
385
386 /**
387 * Check whether the id itself contains all the data. This operation does
388 * not cause any reads in the map.
389 *
390 * @param id the id
391 * @return if the id contains the data
392 */
393 public boolean isInPlace(byte[] id) {
394 ByteBuffer idBuffer = ByteBuffer.wrap(id);
395 while (idBuffer.hasRemaining()) {
396 if (idBuffer.get() != 0) {
397 return false;
398 }
399 int len = DataUtils.readVarInt(idBuffer);
400 idBuffer.position(idBuffer.position() + len);
401 }
402 return true;
403 }
404
405 /**
406 * Open an input stream to read data.
407 *
408 * @param id the id
409 * @return the stream
410 */
411 public InputStream get(byte[] id) {
412 return new Stream(this, id);
413 }
414
415 /**
416 * Get the block.
417 *
418 * @param key the key
419 * @return the block
420 */
421 byte[] getBlock(long key) {
422 byte[] data = map.get(key);
423 if (data == null) {
424 throw DataUtils.newMVStoreException(
425 DataUtils.ERROR_BLOCK_NOT_FOUND,
426 "Block {0} not found", key);
427 }
428 return data;
429 }
430
431 /**
432 * A stream backed by a map.
433 */
434 static class Stream extends InputStream {
435
436 private final StreamStore store;
437 private byte[] oneByteBuffer;
438 private ByteBuffer idBuffer;
439 private ByteArrayInputStream buffer;
440 private long skip;
441 private final long length;
442 private long pos;
443
444 Stream(StreamStore store, byte[] id) {
445 this.store = store;
446 this.length = store.length(id);
447 this.idBuffer = ByteBuffer.wrap(id);
448 }
449
450 @Override
451 public int read() throws IOException {
452 byte[] buffer = oneByteBuffer;
453 if (buffer == null) {
454 buffer = oneByteBuffer = new byte[1];
455 }
456 int len = read(buffer, 0, 1);
457 return len == -1 ? -1 : (buffer[0] & 255);
458 }
459
460 @Override
461 public long skip(long n) {
462 n = Math.min(length - pos, n);
463 if (n == 0) {
464 return 0;
465 }
466 if (buffer != null) {
467 long s = buffer.skip(n);
468 if (s > 0) {
469 n = s;
470 } else {
471 buffer = null;
472 skip += n;
473 }
474 } else {
475 skip += n;
476 }
477 pos += n;
478 return n;
479 }
480
481 @Override
482 public void close() {
483 buffer = null;
484 idBuffer.position(idBuffer.limit());
485 pos = length;
486 }
487
488 @Override
489 public int read(byte[] b, int off, int len) throws IOException {
490 if (len <= 0) {
491 return 0;
492 }
493 while (true) {
494 if (buffer == null) {
495 try {
496 buffer = nextBuffer();
497 } catch (MVStoreException e) {
498 String msg = DataUtils.formatMessage(
499 DataUtils.ERROR_BLOCK_NOT_FOUND,
500 "Block not found in id {0}",
501 Arrays.toString(idBuffer.array()));
502 throw new IOException(msg, e);
503 }
504 if (buffer == null) {
505 return -1;
506 }
507 }
508 int result = buffer.read(b, off, len);
509 if (result > 0) {
510 pos += result;
511 return result;
512 }
513 buffer = null;
514 }
515 }
516
517 private ByteArrayInputStream nextBuffer() {
518 while (idBuffer.hasRemaining()) {
519 switch (idBuffer.get()) {
520 case 0: {
521 int len = DataUtils.readVarInt(idBuffer);
522 if (skip >= len) {
523 skip -= len;
524 idBuffer.position(idBuffer.position() + len);
525 continue;
526 }
527 int p = (int) (idBuffer.position() + skip);
528 int l = (int) (len - skip);
529 idBuffer.position(p + l);
530 return new ByteArrayInputStream(idBuffer.array(), p, l);
531 }
532 case 1: {
533 int len = DataUtils.readVarInt(idBuffer);
534 long key = DataUtils.readVarLong(idBuffer);
535 if (skip >= len) {
536 skip -= len;
537 continue;
538 }
539 byte[] data = store.getBlock(key);
540 int s = (int) skip;
541 skip = 0;
542 return new ByteArrayInputStream(data, s, data.length - s);
543 }
544 case 2: {
545 long len = DataUtils.readVarLong(idBuffer);
546 long key = DataUtils.readVarLong(idBuffer);
547 if (skip >= len) {
548 skip -= len;
549 continue;
550 }
551 byte[] k = store.getBlock(key);
552 ByteBuffer newBuffer = ByteBuffer.allocate(k.length
553 + idBuffer.limit() - idBuffer.position());
554 newBuffer.put(k);
555 newBuffer.put(idBuffer);
556 newBuffer.flip();
557 idBuffer = newBuffer;
558 return nextBuffer();
559 }
560 default:
561 throw DataUtils.newIllegalArgumentException(
562 "Unsupported id {0}",
563 Arrays.toString(idBuffer.array()));
564 }
565 }
566 return null;
567 }
568
569 }
570
571 }