/
SingleChronicleQueueExcerpts.java
executable file
·1490 lines (1266 loc) · 55.3 KB
/
SingleChronicleQueueExcerpts.java
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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2016 higherfrequencytrading.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.openhft.chronicle.queue.impl.single;
import net.openhft.chronicle.bytes.Bytes;
import net.openhft.chronicle.bytes.BytesStore;
import net.openhft.chronicle.bytes.MappedBytes;
import net.openhft.chronicle.bytes.WriteBytesMarshallable;
import net.openhft.chronicle.core.Jvm;
import net.openhft.chronicle.core.Maths;
import net.openhft.chronicle.core.annotation.UsedViaReflection;
import net.openhft.chronicle.core.io.IORuntimeException;
import net.openhft.chronicle.core.util.StringUtils;
import net.openhft.chronicle.queue.*;
import net.openhft.chronicle.queue.impl.ExcerptContext;
import net.openhft.chronicle.queue.impl.RollingChronicleQueue;
import net.openhft.chronicle.queue.impl.WireStore;
import net.openhft.chronicle.wire.*;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.EOFException;
import java.io.IOException;
import java.io.StreamCorruptedException;
import java.nio.BufferOverflowException;
import java.text.ParseException;
import java.util.concurrent.TimeoutException;
import static net.openhft.chronicle.queue.TailerDirection.BACKWARD;
import static net.openhft.chronicle.queue.TailerDirection.FORWARD;
import static net.openhft.chronicle.queue.TailerState.*;
import static net.openhft.chronicle.queue.impl.single.ScanResult.FOUND;
import static net.openhft.chronicle.queue.impl.single.ScanResult.NOT_FOUND;
public class SingleChronicleQueueExcerpts {
private static final Logger LOG = LoggerFactory.getLogger(SingleChronicleQueueExcerpts.class);
@FunctionalInterface
interface WireWriter<T> {
void write(T message, WireOut wireOut);
}
// *************************************************************************
//
// APPENDERS
//
// *************************************************************************
public interface InternalAppender {
void writeBytes(long index, BytesStore bytes);
}
/**
* // StoreAppender
*/
static class StoreAppender implements ExcerptAppender, ExcerptContext, InternalAppender {
static final int HEAD_ROOM = 1 << 20;
@NotNull
private final SingleChronicleQueue queue;
private final StoreAppenderContext context;
WireStore store;
private int cycle = Integer.MIN_VALUE;
private Wire wire;
private Wire bufferWire; // if you have a buffered write.
private Wire wireForIndex;
private long position = 0;
private volatile Thread appendingThread = null;
private long lastIndex = Long.MIN_VALUE;
private boolean lazyIndexing = false;
private long lastPosition;
private int lastCycle;
private Pretoucher pretoucher = null;
private Padding padToCacheLines = Padding.SMART;
StoreAppender(@NotNull SingleChronicleQueue queue) {
this.queue = queue;
queue.addCloseListener(StoreAppender.this::close);
context = new StoreAppenderContext();
}
public Padding padToCacheAlign() {
return padToCacheLines;
}
/**
* @param padToCacheLines the default for chronicle queue is Padding.SMART, which
* automatically pads all method calls other than {@link
* StoreAppender#writeBytes(net.openhft.chronicle.bytes.WriteBytesMarshallable)}
* and {@link StoreAppender#writeText(java.lang.CharSequence)}.
* Which can not be padded with out changing the message format, The
* reason we pad is to ensure that a message header does not straggle
* a cache line.
*/
public void padToCacheAlign(Padding padToCacheLines) {
this.padToCacheLines = padToCacheLines;
}
/**
* @param marshallable to write to excerpt.
*/
public void writeBytes(@NotNull WriteBytesMarshallable marshallable) throws UnrecoverableTimeoutException {
try (DocumentContext dc = writingDocument()) {
marshallable.writeMarshallable(dc.wire().bytes());
if (padToCacheAlign() != Padding.ALWAYS)
((StoreAppenderContext) dc).padToCacheAlign = false;
}
}
@Override
public void writeText(CharSequence text) throws UnrecoverableTimeoutException {
try (DocumentContext dc = writingDocument()) {
dc.wire().bytes().append8bit(text);
if (padToCacheAlign() != Padding.ALWAYS)
((StoreAppenderContext) dc).padToCacheAlign = false;
}
}
private void close() {
Wire w0 = wireForIndex;
wireForIndex = null;
if (w0 != null)
w0.bytes().release();
Wire w = wire;
wire = null;
if (w != null)
w.bytes().release();
}
@Override
public void pretouch() {
setCycle(queue.cycle(), true);
if (pretoucher == null)
pretoucher = new Pretoucher(() -> this.store.writePosition());
pretoucher.pretouch((MappedBytes) wire.bytes());
}
@Override
public Wire wire() {
return wire;
}
@Override
public Wire wireForIndex() {
return wireForIndex;
}
@Override
public long timeoutMS() {
return queue.timeoutMS;
}
void lastIndex(long index) {
this.lastIndex = index;
}
@Override
public ExcerptAppender lazyIndexing(boolean lazyIndexing) {
this.lazyIndexing = lazyIndexing;
resetPosition();
return this;
}
@Override
public boolean lazyIndexing() {
return lazyIndexing;
}
@Override
public boolean recordHistory() {
return sourceId() != 0;
}
private void setCycle(int cycle, boolean createIfAbsent) {
if (cycle != this.cycle)
setCycle2(cycle, createIfAbsent);
}
private void setCycle2(int cycle, boolean createIfAbsent) {
if (cycle < 0)
throw new IllegalArgumentException("You can not have a cycle that starts " +
"before Epoch. cycle=" + cycle);
SingleChronicleQueue queue = this.queue;
if (this.store != null)
queue.release(this.store);
this.store = queue.storeForCycle(cycle, queue.epoch(), createIfAbsent);
resetWires(queue);
// only set the cycle after the wire is set.
this.cycle = cycle;
assert wire.startUse();
wire.parent(this);
wire.pauser(queue.pauserSupplier.get());
resetPosition();
queue.onRoll(cycle);
}
private void resetWires(SingleChronicleQueue queue) {
WireType wireType = queue.wireType();
{
Wire oldw = this.wire;
this.wire = wireType.apply(store.bytes());
if (oldw != null)
oldw.bytes().release();
}
{
Wire old = this.wireForIndex;
this.wireForIndex = wireType.apply(store.bytes());
if (old != null)
old.bytes().release();
}
}
private void resetPosition() throws UnrecoverableTimeoutException {
try {
if (store == null || wire == null)
return;
position(store.writePosition());
Bytes<?> bytes = wire.bytes();
int header = bytes.readVolatileInt(position);
assert position == 0 || Wires.isReadyData(header);
bytes.writePosition(position + 4 + Wires.lengthOf(header));
if (lazyIndexing) {
wire.headerNumber(Long.MIN_VALUE);
return;
}
final long headerNumber = store.sequenceForPosition(this, position, true);
wire.headerNumber(queue.rollCycle().toIndex(cycle, headerNumber + 1) - 1);
assert lazyIndexing || wire.headerNumber() != -1 || checkIndex(wire.headerNumber(), position);
} catch (EOFException e) {
// todo improve this
// you can't index a file that has an EOF marker, sequenceForPosition can do
// indexing and also would not want to set a headerNumber on a file with a
// EOF, so lets just ignore this exception
Jvm.debug().on(SingleChronicleQueue.class, e);
} catch (BufferOverflowException | StreamCorruptedException e) {
throw new AssertionError(e);
}
assert checkWritePositionHeaderNumber();
}
@Override
public DocumentContext writingDocument() throws UnrecoverableTimeoutException {
assert checkAppendingThread();
assert checkWritePositionHeaderNumber();
boolean ok = false;
try {
int cycle = queue.cycle();
if (this.cycle != cycle || wire == null)
rollCycleTo(cycle);
for (int i = 0; i <= 100; i++) {
try {
assert wire != null;
long pos = store.writeHeader(wire, Wires.UNKNOWN_LENGTH, timeoutMS());
position(pos);
context.metaData = false;
context.wire = wire;
context.padToCacheAlign = padToCacheAlign() != Padding.NEVER;
break;
} catch (EOFException theySeeMeRolling) {
assert !((AbstractWire) wire).isInsideHeader();
int qCycle = queue.cycle();
if (cycle < queue.cycle()) {
setCycle2(cycle = qCycle, true);
} else if (cycle == qCycle) {
// for the rare case where the qCycle has just changed in the last
// few milliseconds since
setCycle2(++cycle, true);
} else
throw new IllegalStateException("Found an EOF on the next cycle file," +
" this next file, should not have an EOF as its cycle " +
"number is greater than the current cycle (based on the " +
"current time), this should only happen " +
"if it " +
"was written by a different appender set with a different " +
"EPOC or different roll cycle." +
"All your appenders ( that write to a given directory ) " +
"should have the same EPOCH and roll cycle" +
" qCycle=" + qCycle + ", cycle=" + cycle);
}
if (i == 100)
throw new IllegalStateException("Unable to roll to the current cycle");
}
ok = true;
} finally {
if (!ok)
assert resetAppendingThread();
}
return context;
}
boolean checkWritePositionHeaderNumber() {
if (wire == null || wire.headerNumber() == Long.MIN_VALUE) return true;
try {
long pos1 = position;
/*
long posMax = store.writePosition();
if (pos1 > posMax+4) {
System.out.println(queue.dump());
String message = "########### " +
"thread: " + Thread.currentThread().getName() +
" pos1: " + pos1 +
" posMax: " + posMax;
System.err.println(message);
throw new AssertionError(message);
}*/
long seq1 = queue.rollCycle().toSequenceNumber(wire.headerNumber() + 1) - 1;
long seq2 = store.sequenceForPosition(this, pos1, true);
if (seq1 != seq2) {
// System.out.println(queue.dump());
String message = "~~~~~~~~~~~~~~ " +
"thread: " + Thread.currentThread().getName() +
" pos1: " + pos1 +
" seq1: " + seq1 +
" seq2: " + seq2;
System.err.println(message);
throw new AssertionError(message);
}
} catch (EOFException e) {
} catch (IOException e) {
Jvm.fatal().on(getClass(), e);
throw Jvm.rethrow(e);
}
return true;
}
@Override
public DocumentContext writingDocument(long index) {
assert checkAppendingThread();
context.wire = acquireBufferWire();
context.wire.headerNumber(index);
return context;
}
@Override
public int sourceId() {
return queue.sourceId;
}
@Override
public void writeBytes(@NotNull Bytes bytes) throws UnrecoverableTimeoutException {
// still uses append as it has a known length.
append(Maths.toUInt31(bytes.readRemaining()), (m, w) -> w.bytes().write(m), bytes);
}
Wire acquireBufferWire() {
if (bufferWire == null) {
bufferWire = queue.wireType().apply(Bytes.elasticByteBuffer());
} else {
bufferWire.clear();
}
return bufferWire;
}
@Override
public void writeBytes(long index, BytesStore bytes) {
if (index < 0)
throw new IllegalArgumentException("index: " + index);
if (bytes.isEmpty())
throw new UnsupportedOperationException("Cannot append a zero length message");
assert checkAppendingThread();
try {
moveToIndexForWrite(index);
// only get the bytes after moveToIndex
Bytes<?> wireBytes = wire.bytes();
try {
// wire.bytes().writePosition(store.writePosition());
int length = bytes.length();
// sets the position
wire.headerNumber(index);
position(store.writeHeader(wire, length, timeoutMS()));
wireBytes.write(bytes);
wire.updateHeader(length, position, false);
writeIndexForPosition(index, position);
lastIndex(index);
lastPosition = position;
lastCycle = cycle;
store.writePosition(position);
} catch (EOFException theySeeMeRolling) {
if (wireBytes.compareAndSwapInt(wireBytes.writePosition(), Wires.END_OF_DATA, Wires.NOT_COMPLETE)) {
wireBytes.write(bytes);
wire.updateHeader(0, position, false);
}
}
} catch (IllegalStateException ise) {
if (!ise.getMessage().contains("index already exists")) {
Jvm.warn().on(getClass(), "Ignoring duplicate", ise);
throw ise;
}
} catch (StreamCorruptedException | EOFException e) {
throw Jvm.rethrow(e);
} finally {
if (wire != null) {
Bytes<?> wireBytes = wire.bytes();
assert resetAppendingThread();
}
}
}
private void position(long position) {
if (position > store.writePosition() + queue.blockSize())
throw new IllegalArgumentException("pos: " + position + ", store.writePosition()=" +
store.writePosition() + " queue.blockSize()=" + queue.blockSize());
// System.err.println("----- "+Thread.currentThread().getName()+" pos: "+position);
this.position = position;
}
// only called for writeBytes(long index, BytesStore)
private void moveToIndexForWrite(long index) throws EOFException {
if (wire != null && wire.headerNumber() == index)
return;
int cycle = queue.rollCycle().toCycle(index);
ScanResult scanResult = moveToIndex(cycle, queue.rollCycle().toSequenceNumber(index));
switch (scanResult) {
case FOUND:
throw new IllegalStateException("Unable to move to index " + Long.toHexString(index) + " as the index already exists");
case NOT_REACHED:
throw new IllegalStateException("Unable to move to index " + Long.toHexString(index) + " beyond the end of the queue");
case NOT_FOUND:
break;
}
}
ScanResult moveToIndex(int cycle, long sequenceNumber) throws UnrecoverableTimeoutException {
if (LOG.isDebugEnabled()) {
Jvm.debug().on(getClass(), "moveToIndex: " + Long.toHexString(cycle) + " " + Long.toHexString(sequenceNumber));
}
if (this.cycle != cycle) {
if (cycle > this.cycle)
rollCycleTo(cycle);
else
setCycle2(cycle, true);
}
ScanResult scanResult = this.store.moveToIndexForRead(this, sequenceNumber);
Bytes<?> bytes = wire.bytes();
if (scanResult == NOT_FOUND) {
// so you won't read any if it ran out of data.
bytes.writePosition(bytes.readPosition());
return scanResult;
}
bytes.readLimit(bytes.readPosition());
return scanResult;
}
@Override
public long lastIndexAppended() {
if (lastIndex != Long.MIN_VALUE)
return lastIndex;
if (lastPosition == Long.MIN_VALUE || wire == null) {
throw new IllegalStateException("nothing has been appended, so there is no last index");
}
try {
long sequenceNumber = store.sequenceForPosition(this, lastPosition, true);
long index = queue.rollCycle().toIndex(lastCycle, sequenceNumber);
lastIndex(index);
return index;
} catch (Exception e) {
throw Jvm.rethrow(e);
}
}
@Override
public int cycle() {
if (cycle == Integer.MIN_VALUE) {
int cycle = this.queue.lastCycle();
if (cycle < 0)
cycle = queue.cycle();
setCycle2(cycle, true);
}
return cycle;
}
public SingleChronicleQueue queue() {
return queue;
}
/**
* overwritten in delta wire
*
* @param wire
* @param index
*/
void beforeAppend(Wire wire, long index) {
}
private <T> void append(int length, WireWriter<T> wireWriter, T writer) throws
UnrecoverableTimeoutException {
assert checkAppendingThread();
try {
int cycle = queue.cycle();
if (this.cycle != cycle || wire == null)
rollCycleTo(cycle);
try {
position(store.writeHeader(wire, length, timeoutMS()));
assert ((AbstractWire) wire).isInsideHeader();
beforeAppend(wire, wire.headerNumber() + 1);
wireWriter.write(writer, wire);
wire.updateHeader(length, position, false);
lastIndex(wire.headerNumber());
lastPosition = position;
lastCycle = cycle;
store.writePosition(position);
writeIndexForPosition(lastIndex, position);
} catch (EOFException theySeeMeRolling) {
try {
append2(length, wireWriter, writer);
} catch (EOFException e) {
throw new AssertionError(e);
}
}
} catch (StreamCorruptedException e) {
throw new AssertionError(e);
} finally {
assert resetAppendingThread();
}
}
private void rollCycleTo(int cycle) throws UnrecoverableTimeoutException {
if (this.cycle == cycle)
throw new AssertionError();
if (wire != null) {
try {
store.writeEOF(wire, timeoutMS());
} catch (TimeoutException e) {
Jvm.warn().on(SingleChronicleQueueExcerpts.class, "Unable to terminate the previous cycle, continuing", e);
}
}
setCycle2(cycle, true);
}
/**
* Write an EOF marker on the current cycle if it is about to roll. It would do this any way
* if a new message wis written, but this doesn't create a new cycle or add a message.
*/
public void writeEndOfCycleIfRequired() {
if (wire != null && queue.cycle() != cycle) {
try {
store.writeEOF(wire, timeoutMS());
} catch (TimeoutException e) {
Jvm.warn().on(SingleChronicleQueueExcerpts.class, "Unable to terminate the previous cycle, continuing", e);
}
}
}
<T> void append2(int length, WireWriter<T> wireWriter, T writer) throws
UnrecoverableTimeoutException, EOFException, StreamCorruptedException {
setCycle(Math.max(queue.cycle(), cycle + 1), true);
position(store.writeHeader(wire, length, timeoutMS()));
beforeAppend(wire, wire.headerNumber() + 1);
wireWriter.write(writer, wire);
wire.updateHeader(length, position, false);
}
private boolean checkAppendingThread() {
Thread appendingThread = this.appendingThread;
Thread currentThread = Thread.currentThread();
if (appendingThread != null) {
if (appendingThread == currentThread)
throw new IllegalStateException("Nested blocks of writingDocument() not supported");
throw new IllegalStateException("Attempting to use Appender in " + currentThread + " while used by " + appendingThread);
}
this.appendingThread = currentThread;
return true;
}
private boolean resetAppendingThread() {
if (this.appendingThread == null)
throw new IllegalStateException("Attempting to release Appender in " + Thread.currentThread() + " but already released");
this.appendingThread = null;
return true;
}
void writeIndexForPosition(long index, long position) throws UnrecoverableTimeoutException, StreamCorruptedException {
if (!lazyIndexing) {
long sequenceNumber = queue.rollCycle().toSequenceNumber(index);
store.setPositionForSequenceNumber(this, sequenceNumber, position);
}
}
boolean checkIndex(long index, long position) {
try {
final long seq1 = queue.rollCycle().toSequenceNumber(index + 1) - 1;
final long seq2 = store.sequenceForPosition(this, position, true);
if (seq1 != seq2) {
final long seq3 = ((SingleChronicleQueueStore) store).indexing
.linearScanByPosition(wireForIndex(), position, 0, 0, true);
System.out.println("Thread=" + Thread.currentThread().getName() +
" pos: " + position +
" seq1: " + Long.toHexString(seq1) +
" seq2: " + Long.toHexString(seq2) +
" seq3: " + Long.toHexString(seq3));
System.out.println(store.dump());
assert seq1 == seq3 : "seq1=" + seq1 + ", seq3=" + seq3;
assert seq1 == seq2 : "seq1=" + seq1 + ", seq2=" + seq2;
} else {
/* System.out.println("checked Thread=" + Thread.currentThread().getName() +
" pos: " + position +
" seq1: " + seq1);*/
}
} catch (EOFException | UnrecoverableTimeoutException | StreamCorruptedException e) {
throw new AssertionError(e);
}
return true;
}
class StoreAppenderContext implements DocumentContext {
boolean isClosed;
boolean padToCacheAlign = true;
private boolean metaData = false;
private Wire wire;
@Override
public int sourceId() {
return StoreAppender.this.sourceId();
}
@Override
public boolean isPresent() {
return false;
}
@Override
public Wire wire() {
return wire;
}
@Override
public boolean isMetaData() {
return metaData;
}
@Override
public void metaData(boolean metaData) {
this.metaData = metaData;
}
@Override
public boolean isClosed() {
return isClosed;
}
@Override
public void close() {
if (isClosed) {
LOG.warn("Already Closed, close was called twice.");
return;
}
try {
if (wire == StoreAppender.this.wire) {
if (padToCacheAlign)
wire.padToCacheAlign();
wire.updateHeader(position, metaData);
lastPosition = position;
lastCycle = cycle;
if (!metaData) {
lastIndex(wire.headerNumber());
store.writePosition(position);
if (lastIndex != Long.MIN_VALUE)
writeIndexForPosition(lastIndex, position);
else
assert lazyIndexing || lastIndex == Long.MIN_VALUE || checkIndex(lastIndex, position);
}
assert checkWritePositionHeaderNumber();
} else if (wire != null) {
isClosed = true;
assert resetAppendingThread();
writeBytes(wire.headerNumber(), wire.bytes());
wire = StoreAppender.this.wire;
}
} catch (StreamCorruptedException | UnrecoverableTimeoutException e) {
throw new IllegalStateException(e);
} finally {
assert isClosed || resetAppendingThread();
}
}
@Override
public long index() throws IORuntimeException {
if (this.wire.headerNumber() == Long.MIN_VALUE) {
try {
long headerNumber0 = queue.rollCycle().toIndex(cycle, store
.sequenceForPosition(StoreAppender.this, position, false));
assert (((AbstractWire) this.wire).isInsideHeader());
return isMetaData() ? headerNumber0 : headerNumber0 + 1;
} catch (IOException e) {
throw new IORuntimeException(e);
}
}
return isMetaData() ? Long.MIN_VALUE : this.wire.headerNumber() + 1;
}
@Override
public boolean isNotComplete() {
throw new UnsupportedOperationException();
}
}
}
// *************************************************************************
//
// TAILERS
//
// *************************************************************************
/**
* Tailer
*/
public static class StoreTailer implements ExcerptTailer, SourceContext, ExcerptContext {
@NotNull
private final SingleChronicleQueue queue;
private final StoreTailerContext context = new StoreTailerContext();
private final int indexSpacingMask;
long index; // index of the next read.
WireStore store;
private int cycle;
private TailerDirection direction = TailerDirection.FORWARD;
private boolean lazyIndexing = false;
private Wire wireForIndex;
private boolean readAfterReplicaAcknowledged;
private TailerState state = UNINTIALISED;
public StoreTailer(@NotNull final SingleChronicleQueue queue) {
this.queue = queue;
this.cycle = Integer.MIN_VALUE;
this.index = 0;
queue.addCloseListener(StoreTailer.this::close);
indexSpacingMask = queue.rollCycle().defaultIndexSpacing() - 1;
toStart();
}
private static boolean isReadOnly(Bytes bytes) {
return bytes instanceof MappedBytes &&
!((MappedBytes) bytes).mappedFile().file().canWrite();
}
private void close() {
context.wire(null);
Wire w0 = wireForIndex;
if (w0 != null)
w0.bytes().release();
if (store != null)
queue.release(store);
store = null;
}
@Override
public Wire wire() {
return context.wire();
}
@Override
public Wire wireForIndex() {
return wireForIndex;
}
@Override
public long timeoutMS() {
return queue.timeoutMS;
}
@Override
public ExcerptTailer lazyIndexing(boolean lazyIndexing) {
this.lazyIndexing = lazyIndexing;
return this;
}
@Override
public boolean lazyIndexing() {
return lazyIndexing;
}
@Override
public int sourceId() {
return queue.sourceId;
}
@Override
public String toString() {
return "StoreTailer{" +
"index sequence=" + queue.rollCycle().toSequenceNumber(index) +
", index cycle=" + queue.rollCycle().toCycle(index) +
", store=" + store + ", queue=" + queue + '}';
}
@Override
public DocumentContext readingDocument(boolean includeMetaData) {
try {
if (context.present(next(includeMetaData))) {
assert wire().startUse();
return context;
}
} catch (StreamCorruptedException e) {
throw new IllegalStateException(e);
} catch (UnrecoverableTimeoutException notComplete) {
// so treat as empty.
}
return NoDocumentContext.INSTANCE;
}
private boolean next(boolean includeMetaData) throws UnrecoverableTimeoutException, StreamCorruptedException {
for (int i = 0; i < 1000; i++) {
switch (state) {
case UNINTIALISED:
final long firstIndex = queue.firstIndex();
if (firstIndex == Long.MAX_VALUE)
return false;
if (!moveToIndex(firstIndex))
return false;
break;
case FOUND_CYCLE: {
try {
return inAnCycle(includeMetaData);
} catch (EOFException eof) {
state = TailerState.END_OF_CYCLE;
}
break;
}
case END_OF_CYCLE: {
long oldIndex = this.index;
int currentCycle = queue.rollCycle().toCycle(oldIndex);
long nextIndex = nextIndexWithNextAvailableCycle(currentCycle);
if (nextIndex != Long.MIN_VALUE) {
if (moveToIndex(nextIndex)) {
state = FOUND_CYCLE;
continue;
}
}
moveToIndex(oldIndex);
state = END_OF_CYCLE;
return false;
}
case BEHOND_START_OF_CYCLE: {
if (direction == FORWARD) {
state = UNINTIALISED;
continue;
}
if (direction == BACKWARD) {
// give the position of the last entry and
// flag we want to count it even though we don't know if it will be meta data or not.
try {
boolean foundCycle = cycle(queue.rollCycle().toCycle(index), false);
if (foundCycle) {
long lastSequenceNumberInThisCycle = store.sequenceForPosition(this, Long.MAX_VALUE, false);
long nextIndex = queue.rollCycle().toIndex(this.cycle,
lastSequenceNumberInThisCycle);
moveToIndex(nextIndex);
state = FOUND_CYCLE;
continue;
}
int cycle = queue.rollCycle().toCycle(index);
long nextIndex = nextIndexWithNextAvailableCycle(cycle);
if (nextIndex != Long.MIN_VALUE) {
moveToIndex(nextIndex);
state = FOUND_CYCLE;
continue;
}
state = BEHOND_START_OF_CYCLE;
return false;
} catch (EOFException e) {
throw new AssertionError(e);
}
}
}
throw new AssertionError("direction not set, direction=" + direction);
case CYCLE_NOT_FOUND:
if (index == Long.MIN_VALUE) {
if (this.store != null)
queue.release(this.store);
this.store = null;
return false;
}
if (moveToIndex(index)) {
state = FOUND_CYCLE;
continue;
} else
return false;
default:
throw new AssertionError("state=" + state);
}
}
throw new IllegalStateException("Unable to progress to the next cycle, state=" + state);
}
private boolean inAnCycle(boolean includeMetaData) throws EOFException,
StreamCorruptedException {
Bytes<?> bytes = wire().bytes();
bytes.readLimit(bytes.capacity());
if (readAfterReplicaAcknowledged) {
long lastSequenceAck = store.lastAcknowledgedIndexReplicated();
long seq = queue.rollCycle().toSequenceNumber(index);
if (seq > lastSequenceAck)
return false;
}
if (direction != TailerDirection.FORWARD)
if (!moveToIndex(index))
return false;
switch (wire().readDataHeader(includeMetaData)) {
case NONE: {
// if current time is not the current cycle, then write an EOF marker and
// re-read from here, you may find that in the mean time an appender writes
// another message, however the EOF marker will always be at the end.
if (cycle != queue.cycle() && !isReadOnly(bytes)) {
long pos = bytes.readPosition();
long lim = bytes.readLimit();
long wlim = bytes.writeLimit();
try {
bytes.writePosition(pos);
store.writeEOF(wire(), timeoutMS());
} catch (TimeoutException e) {
Jvm.warn().on(getClass(), "Unable to append EOF, skipping", e);
} finally {
bytes.writeLimit(wlim);
bytes.readLimit(lim);
bytes.readPosition(pos);
}
return inAnCycle(includeMetaData);
}