package it.cavallium.dbengine.database.disk; import static it.cavallium.dbengine.database.disk.LLLocalDictionary.getRocksIterator; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufAllocator; import it.cavallium.dbengine.database.LLRange; import it.cavallium.dbengine.database.LLUtils; import org.rocksdb.ColumnFamilyHandle; import org.rocksdb.ReadOptions; import org.rocksdb.RocksDB; import org.rocksdb.RocksMutableObject; import reactor.core.publisher.Flux; import static io.netty.buffer.Unpooled.*; public abstract class LLLocalReactiveRocksIterator { private final RocksDB db; private final ByteBufAllocator alloc; private final ColumnFamilyHandle cfh; private final LLRange range; private final ReadOptions readOptions; private final boolean readValues; public LLLocalReactiveRocksIterator(RocksDB db, ByteBufAllocator alloc, ColumnFamilyHandle cfh, LLRange range, ReadOptions readOptions, boolean readValues) { this.db = db; this.alloc = alloc; this.cfh = cfh; this.range = range; this.readOptions = readOptions; this.readValues = readValues; } public Flux flux() { return Flux .generate(() -> { var readOptions = new ReadOptions(this.readOptions); if (!range.hasMin() || !range.hasMax()) { readOptions.setReadaheadSize(2 * 1024 * 1024); readOptions.setFillCache(false); } return getRocksIterator(readOptions, range.retain(), db, cfh); }, (tuple, sink) -> { var rocksIterator = tuple.getT1(); if (rocksIterator.isValid()) { ByteBuf key = LLUtils.readDirectNioBuffer(alloc, rocksIterator::key); try { ByteBuf value = readValues ? LLUtils.readDirectNioBuffer(alloc, rocksIterator::value) : EMPTY_BUFFER; try { rocksIterator.next(); sink.next(getEntry(key.retain(), value.retain())); } finally { value.release(); } } finally { key.release(); } } else { sink.complete(); } return tuple; }, tuple -> { var rocksIterator = tuple.getT1(); rocksIterator.close(); tuple.getT2().release(); tuple.getT3().release(); }); } public abstract T getEntry(ByteBuf key, ByteBuf value); }