World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#617] improvement(core): Use general 2pc to replace transaction mechanism provided by underlying storage (#710)
Qi Yu3fd2e2d6f347
diff --git a/core/src/main/java/com/datastrato/gravitino/Configs.java b/core/src/main/java/com/datastrato/gravitino/Configs.javaindex db829cd68c..d75bbb018c 100644--- a/core/src/main/java/com/datastrato/gravitino/Configs.java+++ b/core/src/main/java/com/datastrato/gravitino/Configs.java@@ -70,4 +70,11 @@ public interface Configs {.version("0.3.0").stringConf().createWithDefault("simple");++ ConfigEntry<Long> STORE_TRANSACTION_MAX_SKEW_TIME =+ new ConfigBuilder("gravitino.entity.store.maxTransactionSkewTimeMs")+ .doc("Max time skew allowed for transaction, Unit: millisecond")+ .version("0.3.0")+ .longConf()+ .createWithDefault(2000L);}diff --git a/core/src/main/java/com/datastrato/gravitino/catalog/CatalogManager.java b/core/src/main/java/com/datastrato/gravitino/catalog/CatalogManager.javaindex c197c68aed..3c6476c931 100644--- a/core/src/main/java/com/datastrato/gravitino/catalog/CatalogManager.java+++ b/core/src/main/java/com/datastrato/gravitino/catalog/CatalogManager.java@@ -267,17 +267,13 @@ public class CatalogManager implements SupportsCatalogs, Closeable {.build();try {- store.executeInTransaction(- () -> {- NameIdentifier metalakeIdent = NameIdentifier.of(ident.namespace().levels());- if (!store.exists(metalakeIdent, EntityType.METALAKE)) {- LOG.warn("Metalake {} does not exist", metalakeIdent);- throw new NoSuchMetalakeException("Metalake " + metalakeIdent + " does not exist");- }+ NameIdentifier metalakeIdent = NameIdentifier.of(ident.namespace().levels());+ if (!store.exists(metalakeIdent, EntityType.METALAKE)) {+ LOG.warn("Metalake {} does not exist", metalakeIdent);+ throw new NoSuchMetalakeException("Metalake " + metalakeIdent + " does not exist");+ }- store.put(e, false /* overwrite */);- return null;- });+ store.put(e, false /* overwrite */);CatalogWrapper wrapper = catalogCache.get(ident, id -> createCatalogWrapper(e));return wrapper.catalog;} catch (EntityAlreadyExistsException e1) {diff --git a/core/src/main/java/com/datastrato/gravitino/storage/BiPredicate.java b/core/src/main/java/com/datastrato/gravitino/storage/BiPredicate.javanew file mode 100644index 0000000000..63a746ace3--- /dev/null+++ b/core/src/main/java/com/datastrato/gravitino/storage/BiPredicate.java@@ -0,0 +1,17 @@+/*+ * Copyright 2023 Datastrato.+ * This software is licensed under the Apache License version 2.+ */++package com.datastrato.gravitino.storage;++import java.io.IOException;++/**+ * Predicate for two parameters. It's a little like {@link java.util.function.Predicate}, but it+ * throws {@link IOException} and has two parameters v1 and v2.+ */+@FunctionalInterface+public interface BiPredicate<T1, T2> {+ boolean test(T1 v1, T2 value) throws IOException;+}diff --git a/core/src/main/java/com/datastrato/gravitino/storage/FunctionUtils.java b/core/src/main/java/com/datastrato/gravitino/storage/FunctionUtils.javanew file mode 100644index 0000000000..675bee6faf--- /dev/null+++ b/core/src/main/java/com/datastrato/gravitino/storage/FunctionUtils.java@@ -0,0 +1,63 @@+/*+ * Copyright 2023 Datastrato.+ * This software is licensed under the Apache License version 2.+ */++package com.datastrato.gravitino.storage;++import com.datastrato.gravitino.storage.kv.TransactionalKvBackend;+import com.datastrato.gravitino.utils.Executable;+import java.io.IOException;+import java.util.concurrent.locks.ReentrantReadWriteLock;++/** Tools for executing functions with locks and transaction. */+public class FunctionUtils {++ private FunctionUtils() {}++ @FunctionalInterface+ public interface IOExecutable<R> {++ R execute() throws IOException;+ }++ public static <R> R executeWithReadLock(IOExecutable<R> executable, ReentrantReadWriteLock lock)+ throws IOException {+ // It already held the write lock+ if (lock.isWriteLockedByCurrentThread()) {+ return executable.execute();+ }++ lock.readLock().lock();+ try {+ return executable.execute();+ } finally {+ lock.readLock().unlock();+ }+ }++ public static <R> R executeWithWriteLock(IOExecutable<R> executable, ReentrantReadWriteLock lock)+ throws IOException {+ lock.writeLock().lock();+ try {+ return executable.execute();+ } finally {+ lock.writeLock().unlock();+ }+ }++ public static <R, E extends Exception> R executeInTransaction(+ Executable<R, E> executable, TransactionalKvBackend transactionalKvBackend)+ throws E, IOException {++ transactionalKvBackend.begin();+ try {+ R r = executable.execute();+ transactionalKvBackend.commit();+ return r;+ } finally {+ // Let GC do the roll-back work+ transactionalKvBackend.closeTransaction();+ }+ }+}diff --git a/core/src/main/java/com/datastrato/gravitino/storage/TransactionIdGenerator.java b/core/src/main/java/com/datastrato/gravitino/storage/TransactionIdGenerator.javanew file mode 100644index 0000000000..b6712e876a--- /dev/null+++ b/core/src/main/java/com/datastrato/gravitino/storage/TransactionIdGenerator.java@@ -0,0 +1,21 @@+/*+ * Copyright 2023 Datastrato.+ * This software is licensed under the Apache License version 2.+ */++package com.datastrato.gravitino.storage;++import java.io.Closeable;++/** Generator id number as transaction, which will be used as MVCC version. */+public interface TransactionIdGenerator extends Closeable {++ /**+ * Next transaction id. The transaction id is a monotonically increasing number, which is used as+ * MVCC version.+ */+ long nextId();++ /** Start the generator. */+ void start();+}diff --git a/core/src/main/java/com/datastrato/gravitino/storage/kv/KvEntityStore.java b/core/src/main/java/com/datastrato/gravitino/storage/kv/KvEntityStore.javaindex b6c068c968..7b6c37cf67 100644--- a/core/src/main/java/com/datastrato/gravitino/storage/kv/KvEntityStore.java+++ b/core/src/main/java/com/datastrato/gravitino/storage/kv/KvEntityStore.java@@ -25,8 +25,10 @@ import com.datastrato.gravitino.exceptions.AlreadyExistsException;import com.datastrato.gravitino.exceptions.NoSuchEntityException;import com.datastrato.gravitino.exceptions.NonEmptyEntityException;import com.datastrato.gravitino.storage.EntityKeyEncoder;+import com.datastrato.gravitino.storage.FunctionUtils;import com.datastrato.gravitino.storage.NameMappingService;import com.datastrato.gravitino.storage.StorageLayoutVersion;+import com.datastrato.gravitino.storage.TransactionIdGenerator;import com.datastrato.gravitino.utils.Bytes;import com.datastrato.gravitino.utils.Executable;import com.google.common.annotations.VisibleForTesting;@@ -66,8 +68,8 @@ public class KvEntityStore implements EntityStore {// Lock to control the concurrency of the entity store, to be more exact, the concurrency of// accessing the underlying kv store.private ReentrantReadWriteLock reentrantReadWriteLock;- private EntityKeyEncoder<byte[]> entityKeyEncoder;- private NameMappingService nameMappingService;+ @VisibleForTesting EntityKeyEncoder<byte[]> entityKeyEncoder;+ @VisibleForTesting NameMappingService nameMappingService;private EntitySerDe serDe;// We will use storageLayoutVersion to check whether the layout of the storage is compatible with// the current version of the code.@@ -75,14 +77,23 @@ public class KvEntityStore implements EntityStore {// storageLayoutVersion if it's necessary.@VisibleForTesting StorageLayoutVersion storageLayoutVersion;+ private TransactionIdGenerator txIdGenerator;+ private TransactionalKvBackend transactionalKvBackend;+@Overridepublic void initialize(Config config) throws RuntimeException {this.backend = createKvEntityBackend(config);// TODO(yuqi) Currently, KvNameMappingService and KvEntityStore shares the same backend// instance, We should make it configurable in the future.- this.nameMappingService = new KvNameMappingService(backend);- this.entityKeyEncoder = new BinaryEntityKeyEncoder(nameMappingService);+ this.txIdGenerator = new TransactionIdGeneratorImpl(backend, config);+ txIdGenerator.start();+ this.transactionalKvBackend = new TransactionalKvBackendImpl(backend, txIdGenerator);+this.reentrantReadWriteLock = new ReentrantReadWriteLock();+ this.nameMappingService =+ new KvNameMappingService(transactionalKvBackend, reentrantReadWriteLock);+ this.entityKeyEncoder = new BinaryEntityKeyEncoder(nameMappingService);+this.storageLayoutVersion = initStorageVersionInfo();}@@ -104,17 +115,19 @@ public class KvEntityStore implements EntityStore {byte[] endKey = Bytes.increment(Bytes.wrap(startKey)).get();List<Pair<byte[], byte[]>> kvs =- executeWithReadLock(+ FunctionUtils.executeWithReadLock(() ->- backend.scan(- new KvRangeScan.KvRangeScanBuilder()- .start(startKey)- .end(endKey)- .startInclusive(true)- .endInclusive(false)- .limit(Integer.MAX_VALUE)- .build()));-+ executeInTransaction(+ () ->+ transactionalKvBackend.scan(+ new KvRangeScan.KvRangeScanBuilder()+ .start(startKey)+ .end(endKey)+ .startInclusive(true)+ .endInclusive(false)+ .limit(Integer.MAX_VALUE)+ .build())),+ reentrantReadWriteLock);for (Pair<byte[], byte[]> pairs : kvs) {entities.add(serDe.deserialize(pairs.getRight(), e));}@@ -124,38 +137,44 @@ public class KvEntityStore implements EntityStore {@Overridepublic boolean exists(NameIdentifier ident, EntityType entityType) throws IOException {- byte[] key = entityKeyEncoder.encode(ident, entityType, true);- if (key == null) {- return false;- }-- return executeWithReadLock(() -> backend.get(key) != null);+ return FunctionUtils.executeWithReadLock(+ () ->+ executeInTransaction(+ () -> {+ byte[] key = entityKeyEncoder.encode(ident, entityType, true);+ if (key == null) {+ return false;+ }+ return transactionalKvBackend.get(key) != null;+ }),+ reentrantReadWriteLock);}@Overridepublic <E extends Entity & HasIdentifier> void put(E e, boolean overwritten)throws IOException, EntityAlreadyExistsException {- byte[] key = entityKeyEncoder.encode(e.nameIdentifier(), e.type());- byte[] value = serDe.serialize(e);-- executeWithWriteLock(- () -> {- backend.put(key, value, overwritten);- return null;- });+ FunctionUtils.executeWithWriteLock(+ () ->+ executeInTransaction(+ () -> {+ byte[] key = entityKeyEncoder.encode(e.nameIdentifier(), e.type());+ byte[] value = serDe.serialize(e);+ transactionalKvBackend.put(key, value, overwritten);+ return null;+ }),+ reentrantReadWriteLock);}@Overridepublic <E extends Entity & HasIdentifier> E update(NameIdentifier ident, Class<E> type, EntityType entityType, Function<E, E> updater)throws IOException, NoSuchEntityException, AlreadyExistsException {- byte[] key = entityKeyEncoder.encode(ident, entityType);-- return executeWithWriteLock(+ return FunctionUtils.executeWithWriteLock(() ->executeInTransaction(() -> {- byte[] value = backend.get(key);+ byte[] key = entityKeyEncoder.encode(ident, entityType);+ byte[] value = transactionalKvBackend.get(key);if (value == null) {throw new NoSuchEntityException(ident.toString());}@@ -163,7 +182,7 @@ public class KvEntityStore implements EntityStore {E e = serDe.deserialize(value, type);E updatedE = updater.apply(e);if (updatedE.nameIdentifier().equals(ident)) {- backend.put(key, serDe.serialize(updatedE), true);+ transactionalKvBackend.put(key, serDe.serialize(updatedE), true);return updatedE;}@@ -183,9 +202,10 @@ public class KvEntityStore implements EntityStore {generateKeyForMapping(updatedE.nameIdentifier()));// Update the entity to store- backend.put(key, serDe.serialize(updatedE), true);+ transactionalKvBackend.put(key, serDe.serialize(updatedE), true);return updatedE;- }));+ }),+ reentrantReadWriteLock);}private String concatIdAndName(long[] namespaceIds, String name) {@@ -249,12 +269,18 @@ public class KvEntityStore implements EntityStore {public <E extends Entity & HasIdentifier> E get(NameIdentifier ident, EntityType entityType, Class<E> e)throws NoSuchEntityException, IOException {- byte[] key = entityKeyEncoder.encode(ident, entityType, true);- if (key == null) {- throw new NoSuchEntityException(ident.toString());- }-- byte[] value = executeWithReadLock(() -> backend.get(key));+ byte[] value =+ FunctionUtils.executeWithReadLock(+ () ->+ executeInTransaction(+ () -> {+ byte[] key = entityKeyEncoder.encode(ident, entityType, true);+ if (key == null) {+ throw new NoSuchEntityException(ident.toString());+ }+ return transactionalKvBackend.get(key);+ }),+ reentrantReadWriteLock);if (value == null) {throw new NoSuchEntityException(ident.toString());}@@ -318,58 +344,63 @@ public class KvEntityStore implements EntityStore {@Overridepublic boolean delete(NameIdentifier ident, EntityType entityType, boolean cascade)throws IOException {- return executeWithWriteLock(- () -> {- if (!exists(ident, entityType)) {- return false;- }-- byte[] dataKey = entityKeyEncoder.encode(ident, entityType, true);- List<byte[]> subEntityPrefix = getSubEntitiesPrefix(ident, entityType);- if (subEntityPrefix.isEmpty()) {- // has no sub-entities- return backend.delete(dataKey);- }-- byte[] directChild = Iterables.getLast(subEntityPrefix);- byte[] endKey = Bytes.increment(Bytes.wrap(directChild)).get();- List<Pair<byte[], byte[]>> kvs =- backend.scan(- new KvRangeScan.KvRangeScanBuilder()- .start(directChild)- .end(endKey)- .startInclusive(true)- .endInclusive(false)- .limit(1)- .build());-- if (!cascade && !kvs.isEmpty()) {- throw new NonEmptyEntityException(- String.format(- "Entity %s has sub-entities, you should remove sub-entities first", ident));- }-- for (byte[] prefix : subEntityPrefix) {- backend.deleteRange(- new KvRangeScan.KvRangeScanBuilder()- .start(prefix)- .startInclusive(true)- .end(Bytes.increment(Bytes.wrap(prefix)).get())- .build());- }-- return backend.delete(dataKey);- });+ return FunctionUtils.executeWithWriteLock(+ () ->+ executeInTransaction(+ () -> {+ if (!exists(ident, entityType)) {+ return false;+ }++ byte[] dataKey = entityKeyEncoder.encode(ident, entityType, true);+ List<byte[]> subEntityPrefix = getSubEntitiesPrefix(ident, entityType);+ if (subEntityPrefix.isEmpty()) {+ // has no sub-entities+ return transactionalKvBackend.delete(dataKey);+ }++ byte[] directChild = Iterables.getLast(subEntityPrefix);+ byte[] endKey = Bytes.increment(Bytes.wrap(directChild)).get();+ List<Pair<byte[], byte[]>> kvs =+ transactionalKvBackend.scan(+ new KvRangeScan.KvRangeScanBuilder()+ .start(directChild)+ .end(endKey)+ .startInclusive(true)+ .endInclusive(false)+ .limit(1)+ .build());++ if (!cascade && !kvs.isEmpty()) {+ throw new NonEmptyEntityException(+ String.format(+ "Entity %s has sub-entities, you should remove sub-entities first",+ ident));+ }++ for (byte[] prefix : subEntityPrefix) {+ transactionalKvBackend.deleteRange(+ new KvRangeScan.KvRangeScanBuilder()+ .start(prefix)+ .startInclusive(true)+ .end(Bytes.increment(Bytes.wrap(prefix)).get())+ .build());+ }++ return transactionalKvBackend.delete(dataKey);+ }),+ reentrantReadWriteLock);}@Overridepublic <R, E extends Exception> R executeInTransaction(Executable<R, E> executable)throws E, IOException {- return backend.executeInTransaction(executable);+ return FunctionUtils.executeInTransaction(executable, transactionalKvBackend);}@Overridepublic void close() throws IOException {+ txIdGenerator.close();backend.close();}@@ -409,27 +440,4 @@ public class KvEntityStore implements EntityStore {throw new IllegalStateException("Failed to get/put layout version information", e);}}-- @FunctionalInterface- interface IOExecutable<R> {- R execute() throws IOException;- }-- private <R> R executeWithReadLock(IOExecutable<R> executable) throws IOException {- reentrantReadWriteLock.readLock().lock();- try {- return executable.execute();- } finally {- reentrantReadWriteLock.readLock().unlock();- }- }-- private <R> R executeWithWriteLock(IOExecutable<R> executable) throws IOException {- reentrantReadWriteLock.writeLock().lock();- try {- return executable.execute();- } finally {- reentrantReadWriteLock.writeLock().unlock();- }- }}diff --git a/core/src/main/java/com/datastrato/gravitino/storage/kv/KvNameMappingService.java b/core/src/main/java/com/datastrato/gravitino/storage/kv/KvNameMappingService.javaindex 0eb81a8191..cc4210920b 100644--- a/core/src/main/java/com/datastrato/gravitino/storage/kv/KvNameMappingService.java+++ b/core/src/main/java/com/datastrato/gravitino/storage/kv/KvNameMappingService.java@@ -5,6 +5,7 @@package com.datastrato.gravitino.storage.kv;+import com.datastrato.gravitino.storage.FunctionUtils;import com.datastrato.gravitino.storage.IdGenerator;import com.datastrato.gravitino.storage.NameMappingService;import com.datastrato.gravitino.storage.RandomIdGenerator;@@ -23,9 +24,7 @@ import javax.annotation.concurrent.ThreadSafe;@ThreadSafepublic class KvNameMappingService implements NameMappingService {- // TODO(yuqi) Make this configurable- @VisibleForTesting final KvBackend backend;- private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();+ @VisibleForTesting final ReentrantReadWriteLock lock;@VisibleForTesting final IdGenerator idGenerator = new RandomIdGenerator();// name prefix of name in name to id mapping,@@ -38,86 +37,99 @@ public class KvNameMappingService implements NameMappingService {// id_2 -> metalake2private static final byte[] ID_PREFIX = "id_".getBytes(StandardCharsets.UTF_8);- public KvNameMappingService(KvBackend backend) {- this.backend = backend;+ @VisibleForTesting final TransactionalKvBackend transactionalKvBackend;++ public KvNameMappingService(+ TransactionalKvBackend transactionalKvBackend,+ ReentrantReadWriteLock reentrantReadWriteLock) {+ this.transactionalKvBackend = transactionalKvBackend;+ this.lock = reentrantReadWriteLock;}@Overridepublic Long getIdByName(String name) throws IOException {- lock.readLock().lock();- try {- byte[] nameByte = Bytes.concat(NAME_PREFIX, name.getBytes(StandardCharsets.UTF_8));- byte[] idByte = backend.get(nameByte);- return idByte == null ? null : ByteUtils.byteToLong(idByte);- } finally {- lock.readLock().unlock();- }+ return FunctionUtils.executeWithReadLock(+ () ->+ FunctionUtils.executeInTransaction(+ () -> {+ byte[] nameByte =+ Bytes.concat(NAME_PREFIX, name.getBytes(StandardCharsets.UTF_8));+ byte[] idByte = transactionalKvBackend.get(nameByte);+ return idByte == null ? null : ByteUtils.byteToLong(idByte);+ },+ transactionalKvBackend),+ lock);}private long bindNameAndId(String name) throws IOException {byte[] nameByte = Bytes.concat(NAME_PREFIX, name.getBytes(StandardCharsets.UTF_8));long id = idGenerator.nextId();- lock.writeLock().lock();- try {- return backend.executeInTransaction(- () -> {- backend.put(nameByte, ByteUtils.longToByte(id), false);- byte[] idByte = Bytes.concat(ID_PREFIX, ByteUtils.longToByte(id));- backend.put(idByte, name.getBytes(StandardCharsets.UTF_8), false);- return id;- });- } finally {- lock.writeLock().unlock();- }++ return FunctionUtils.executeWithWriteLock(+ () ->+ FunctionUtils.executeInTransaction(+ () -> {+ transactionalKvBackend.put(nameByte, ByteUtils.longToByte(id), false);+ byte[] idByte = Bytes.concat(ID_PREFIX, ByteUtils.longToByte(id));+ transactionalKvBackend.put(idByte, name.getBytes(StandardCharsets.UTF_8), false);+ return id;+ },+ transactionalKvBackend),+ lock);}@Overridepublic boolean updateName(String oldName, String newName) throws IOException {- lock.writeLock().lock();- try {- return backend.executeInTransaction(- () -> {- byte[] nameByte = Bytes.concat(NAME_PREFIX, oldName.getBytes(StandardCharsets.UTF_8));- byte[] oldIdValue = backend.get(nameByte);-- // Old mapping has been deleted, no need to do it;- if (oldIdValue == null) {- return false;- }- // Delete old name --> id mapping- backend.delete(nameByte);-- backend.put(- Bytes.concat(NAME_PREFIX, newName.getBytes(StandardCharsets.UTF_8)),- oldIdValue,- false);- backend.put(- Bytes.concat(ID_PREFIX, oldIdValue),- newName.getBytes(StandardCharsets.UTF_8),- true);- return true;- });- } finally {- lock.writeLock().unlock();- }+ return FunctionUtils.executeWithWriteLock(+ () ->+ FunctionUtils.executeInTransaction(+ () -> {+ byte[] nameByte =+ Bytes.concat(NAME_PREFIX, oldName.getBytes(StandardCharsets.UTF_8));+ byte[] oldIdValue = transactionalKvBackend.get(nameByte);++ // Old mapping has been deleted, no need to do it;+ if (oldIdValue == null) {+ return false;+ }+ // Delete old name --> id mapping+ transactionalKvBackend.delete(nameByte);++ transactionalKvBackend.put(+ Bytes.concat(NAME_PREFIX, newName.getBytes(StandardCharsets.UTF_8)),+ oldIdValue,+ false);+ transactionalKvBackend.put(+ Bytes.concat(ID_PREFIX, oldIdValue),+ newName.getBytes(StandardCharsets.UTF_8),+ true);+ return true;+ },+ transactionalKvBackend),+ lock);}@Overridepublic boolean unbindNameAndId(String name) throws IOException {byte[] nameByte = Bytes.concat(NAME_PREFIX, name.getBytes(StandardCharsets.UTF_8));-- lock.writeLock().lock();- try {- return backend.delete(nameByte);- } finally {- lock.writeLock().unlock();- }+ return FunctionUtils.executeWithWriteLock(+ () ->+ FunctionUtils.executeInTransaction(+ () -> {+ byte[] idByte = transactionalKvBackend.get(nameByte);+ if (idByte == null) {+ return false;+ }+ transactionalKvBackend.delete(nameByte);+ transactionalKvBackend.delete(Bytes.concat(ID_PREFIX, idByte));+ return true;+ },+ transactionalKvBackend),+ lock);}@Override- public void close() throws Exception {- backend.close();- }+ public void close() throws Exception {}@Overridepublic long getOrCreateIdFromName(String name) throws IOException {diff --git a/core/src/main/java/com/datastrato/gravitino/storage/kv/KvRangeScan.java b/core/src/main/java/com/datastrato/gravitino/storage/kv/KvRangeScan.javaindex 61dbffddf6..5cad673e50 100644--- a/core/src/main/java/com/datastrato/gravitino/storage/kv/KvRangeScan.java+++ b/core/src/main/java/com/datastrato/gravitino/storage/kv/KvRangeScan.java@@ -5,6 +5,7 @@package com.datastrato.gravitino.storage.kv;+import com.datastrato.gravitino.storage.BiPredicate;import com.datastrato.gravitino.utils.Bytes;import com.google.common.base.Preconditions;import lombok.Builder;@@ -20,6 +21,7 @@ public class KvRangeScan {private boolean endInclusive;private int limit;+ private BiPredicate predicate;/*** Constructs a KvRangeScan instance with the specified parameters.@@ -29,9 +31,15 @@ public class KvRangeScan {* @param startInclusive True if the start key is inclusive, false otherwise.* @param endInclusive True if the end key is inclusive, false otherwise.* @param limit The maximum number of results to retrieve.+ * @param predicate The predicate to use to filter key-value pairs.*/public KvRangeScan(- byte[] start, byte[] end, boolean startInclusive, boolean endInclusive, int limit) {+ byte[] start,+ byte[] end,+ boolean startInclusive,+ boolean endInclusive,+ int limit,+ BiPredicate<byte[], byte[]> predicate) {Preconditions.checkArgument(start != null, "start cannot be null");Preconditions.checkArgument(end != null, "start cannot be null");Preconditions.checkArgument(@@ -47,5 +55,6 @@ public class KvRangeScan {this.startInclusive = startInclusive;this.endInclusive = endInclusive;this.limit = limit;+ this.predicate = predicate == null ? (k, v) -> true : predicate;}}diff --git a/core/src/main/java/com/datastrato/gravitino/storage/kv/RocksDBKvBackend.java b/core/src/main/java/com/datastrato/gravitino/storage/kv/RocksDBKvBackend.javaindex 9274dd92dd..5467109a7d 100644--- a/core/src/main/java/com/datastrato/gravitino/storage/kv/RocksDBKvBackend.java+++ b/core/src/main/java/com/datastrato/gravitino/storage/kv/RocksDBKvBackend.java@@ -10,22 +10,16 @@ import com.datastrato.gravitino.Configs;import com.datastrato.gravitino.EntityAlreadyExistsException;import com.datastrato.gravitino.utils.ByteUtils;import com.datastrato.gravitino.utils.Bytes;-import com.datastrato.gravitino.utils.Executable;-import com.google.common.base.Throwables;import com.google.common.collect.Lists;import java.io.File;import java.io.IOException;import java.util.List;import org.apache.commons.lang3.tuple.Pair;import org.rocksdb.Options;-import org.rocksdb.ReadOptions;import org.rocksdb.RocksDB;import org.rocksdb.RocksDBException;import org.rocksdb.RocksIterator;-import org.rocksdb.Transaction;import org.rocksdb.TransactionDB;-import org.rocksdb.TransactionDBOptions;-import org.rocksdb.WriteOptions;import org.slf4j.Logger;import org.slf4j.LoggerFactory;@@ -36,15 +30,13 @@ import org.slf4j.LoggerFactory;*/public class RocksDBKvBackend implements KvBackend {public static final Logger LOGGER = LoggerFactory.getLogger(RocksDBKvBackend.class);- private TransactionDB db;-- public static final ThreadLocal<Transaction> TX_LOCAL = new ThreadLocal<>();+ private RocksDB db;/*** Initialize the RocksDB backend instance. We have used the {@link TransactionDB} to support* transaction instead of {@link RocksDB} instance.*/- private TransactionDB initRocksDB(Config config) throws RocksDBException {+ private RocksDB initRocksDB(Config config) throws RocksDBException {RocksDB.loadLibrary();final Options options = new Options();options.setCreateIfMissing(true);@@ -57,9 +49,8 @@ public class RocksDBKvBackend implements KvBackend {String.format("Can't create RocksDB path '%s'", dbDir.getAbsolutePath()));}LOGGER.info("Rocksdb storage directory:{}", dbDir);- // TODO (yuqi), make options and transactionDBOptions configurable- TransactionDBOptions transactionDBOptions = new TransactionDBOptions();- return TransactionDB.open(options, transactionDBOptions, dbDir.getAbsolutePath());+ // TODO (yuqi), make options configurable+ return RocksDB.open(options, dbDir.getAbsolutePath());} catch (RocksDBException ex) {LOGGER.error("Error initializing RocksDB, check configurations and permissions, exception: {}, message: {}, stackTrace: {}",@@ -81,16 +72,8 @@ public class RocksDBKvBackend implements KvBackend {@Overridepublic void put(byte[] key, byte[] value, boolean overwrite) throws IOException {- Transaction tx = TX_LOCAL.get();try {- // Do without transaction if not in transaction- if (tx == null) {- handlePutWithoutTransaction(key, value, overwrite);- return;- }-- // Now try with transaction- handlePutWithTransaction(key, value, overwrite, tx);+ handlePut(key, value, overwrite);} catch (EntityAlreadyExistsException e) {throw e;} catch (Exception e) {@@ -98,25 +81,7 @@ public class RocksDBKvBackend implements KvBackend {}}- private void handlePutWithTransaction(byte[] key, byte[] value, boolean overwrite, Transaction tx)- throws RocksDBException {- if (overwrite) {- tx.put(key, value);- return;- }-- byte[] existKey = tx.get(new ReadOptions(), key);- if (existKey != null) {- throw new EntityAlreadyExistsException(- String.format(- "Key %s already exists in the database, please use overwrite option to overwrite it",- ByteUtils.formatByteArray(key)));- }- tx.put(key, value);- }-- private void handlePutWithoutTransaction(byte[] key, byte[] value, boolean overwrite)- throws RocksDBException {+ private void handlePut(byte[] key, byte[] value, boolean overwrite) throws RocksDBException {if (overwrite) {db.put(key, value);return;@@ -134,10 +99,6 @@ public class RocksDBKvBackend implements KvBackend {@Overridepublic byte[] get(byte[] key) throws IOException {try {- if (TX_LOCAL.get() != null) {- return TX_LOCAL.get().get(new ReadOptions(), key);- }-return db.get(key);} catch (RocksDBException e) {throw new IOException(e);@@ -146,9 +107,7 @@ public class RocksDBKvBackend implements KvBackend {@Overridepublic List<Pair<byte[], byte[]>> scan(KvRangeScan scanRange) throws IOException {- Transaction tx = TX_LOCAL.get();- RocksIterator rocksIterator =- TX_LOCAL.get() == null ? db.newIterator() : tx.getIterator(new ReadOptions());+ RocksIterator rocksIterator = db.newIterator();rocksIterator.seek(scanRange.getStart());List<Pair<byte[], byte[]>> result = Lists.newArrayList();@@ -161,6 +120,11 @@ public class RocksDBKvBackend implements KvBackend {break;}+ if (!scanRange.getPredicate().test(key, rocksIterator.value())) {+ rocksIterator.next();+ continue;+ }+if (Bytes.wrap(key).compareTo(scanRange.getStart()) == 0) {if (scanRange.isStartInclusive()) {result.add(Pair.of(key, rocksIterator.value()));@@ -186,10 +150,6 @@ public class RocksDBKvBackend implements KvBackend {@Overridepublic boolean delete(byte[] key) throws IOException {try {- if (TX_LOCAL.get() != null) {- TX_LOCAL.get().delete(key);- return true;- }db.delete(key);return true;} catch (RocksDBException e) {@@ -199,8 +159,7 @@ public class RocksDBKvBackend implements KvBackend {@Overridepublic boolean deleteRange(KvRangeScan deleteRange) throws IOException {- Transaction tx = TX_LOCAL.get();- RocksIterator rocksIterator = tx == null ? db.newIterator() : tx.getIterator(new ReadOptions());+ RocksIterator rocksIterator = db.newIterator();rocksIterator.seek(deleteRange.getStart());while (rocksIterator.isValid()) {@@ -234,54 +193,4 @@ public class RocksDBKvBackend implements KvBackend {public void close() throws IOException {db.close();}-- @Override- public <R, E extends Exception> R executeInTransaction(Executable<R, E> executable)- throws E, IOException {- // TODO (yuqi) Name mapping service and storage should use separately backend, or we should- // handle nested transaction- Transaction tx = TX_LOCAL.get();- if (tx != null) {- return executable.execute();- }-- tx = db.beginTransaction(new WriteOptions());- LOGGER.info("Starting transaction: id: '{}'", tx.getID());- TX_LOCAL.set(tx);- try {- R r = executable.execute();- tx.commit();- return r;- } catch (RocksDBException e) {- rollback(tx, e);- throw new IOException(e);- } catch (Exception e) {- rollback(tx, e);- throw e;- } finally {- LOGGER.info("Transaction close, tx id: '{}', tx state: '{}'", tx.getID(), tx.getState());- tx.close();- TX_LOCAL.remove();- }- }-- private void rollback(Transaction tx, Exception e) {- LOGGER.error(- "Error executing transaction, tx id: '{}', exception: {}, message: {}, stackTrace: \n{}",- tx.getID(),- e.getCause(),- e.getMessage(),- Throwables.getStackTraceAsString(e));-- try {- tx.rollback();- } catch (Exception e1) {- LOGGER.error(- "Error rolling back transaction, tx id: '{}', exception: {}, message: {}, stackTrace: \n{}",- tx.getID(),- e1.getCause(),- e1.getMessage(),- Throwables.getStackTraceAsString(e));- }- }}diff --git a/core/src/main/java/com/datastrato/gravitino/storage/kv/TransactionIdGeneratorImpl.java b/core/src/main/java/com/datastrato/gravitino/storage/kv/TransactionIdGeneratorImpl.javanew file mode 100644index 0000000000..545f09c0f2--- /dev/null+++ b/core/src/main/java/com/datastrato/gravitino/storage/kv/TransactionIdGeneratorImpl.java@@ -0,0 +1,142 @@+/*+ * Copyright 2023 Datastrato.+ * This software is licensed under the Apache License version 2.+ */++package com.datastrato.gravitino.storage.kv;++import com.datastrato.gravitino.Config;+import com.datastrato.gravitino.Configs;+import com.datastrato.gravitino.storage.TransactionIdGenerator;+import com.datastrato.gravitino.utils.ByteUtils;+import com.google.common.annotations.VisibleForTesting;+import com.google.common.util.concurrent.ThreadFactoryBuilder;+import java.io.IOException;+import java.nio.charset.StandardCharsets;+import java.util.concurrent.ScheduledExecutorService;+import java.util.concurrent.ScheduledThreadPoolExecutor;+import java.util.concurrent.TimeUnit;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++public class TransactionIdGeneratorImpl implements TransactionIdGenerator {+ private static final Logger LOGGER = LoggerFactory.getLogger(TransactionIdGeneratorImpl.class);++ private final KvBackend kvBackend;+ @VisibleForTesting static final String LAST_TIMESTAMP = "last_timestamp";+ private volatile long incrementId = 0L;+ private volatile long lastTransactionId = 0L;+ private final Config config;++ private final ScheduledExecutorService scheduledThreadPoolExecutor =+ new ScheduledThreadPoolExecutor(+ 1,+ new ThreadFactoryBuilder()+ .setDaemon(true)+ .setNameFormat("TransactionIdGenerator-thread-%d")+ .setUncaughtExceptionHandler(+ (t, e) -> LOGGER.error("Uncaught exception in thread {}", t, e))+ .build());++ public TransactionIdGeneratorImpl(KvBackend kvBackend, Config config) {+ this.kvBackend = kvBackend;+ this.config = config;+ }++ @Override+ public void start() {+ long maxSkewTime = config.get(Configs.STORE_TRANSACTION_MAX_SKEW_TIME);+ // Why use maxSkewTime + 1? Because we will save the current timestamp to storage layer every+ // maxSkewTime second and the save operation will also take a moment. Usually, it takes less+ // than 1 millisecond, so we'd better wait maxSkewTime + 1000 millisecond to make sure the+ // timestamp is OK.+ checkTimeSkew(maxSkewTime + 1000);++ scheduledThreadPoolExecutor.scheduleAtFixedRate(+ () -> {+ int i = 0;+ while (i++ < 3) {+ try {+ kvBackend.put(+ LAST_TIMESTAMP.getBytes(StandardCharsets.UTF_8),+ ByteUtils.longToByte(System.currentTimeMillis()),+ true);+ return;+ } catch (IOException e) {+ LOGGER.warn("Failed to save current timestamp to storage layer, retrying...", e);+ }+ }++ throw new RuntimeException(+ "Failed to save current timestamp to storage layer after 3 retries, please check"+ + "whether the storage layer is healthy.");+ },+ maxSkewTime * 2,+ maxSkewTime,+ TimeUnit.MILLISECONDS);+ }++ private void checkTimeSkew(long maxSkewTimeInMs) {+ long current = System.currentTimeMillis();+ long old;+ try {+ old = getSavedTs();+ // In case of time skew, we will wait maxSkewTimeInSecond(default 2) seconds.+ int retries = 0;+ while (current <= old + maxSkewTimeInMs && retries++ < maxSkewTimeInMs / 100) {+ Thread.sleep(100);+ current = System.currentTimeMillis();+ }++ if (current <= old + maxSkewTimeInMs) {+ throw new RuntimeException(+ String.format(+ "Failed to initialize transaction id generator after %d milliseconds, time skew is too large",+ maxSkewTimeInMs));+ }+ } catch (IOException | InterruptedException e) {+ throw new RuntimeException(e);+ }+ }++ /**+ * Get the last saved timestamp from the storage layer. We will store the current timestamp to+ * storage layer every 2(default) seconds.+ */+ private long getSavedTs() throws IOException {+ byte[] oldIdBytes = kvBackend.get(LAST_TIMESTAMP.getBytes(StandardCharsets.UTF_8));+ return oldIdBytes == null ? 0 : ByteUtils.byteToLong(oldIdBytes);+ }++ /**+ * We use the timestamp as the high 48 bits and the incrementId as the low 16 bits. The timestamp+ * is always incremental.+ */+ @Override+ public synchronized long nextId() {+ incrementId++;+ if (incrementId >= (1 << 18 - 1)) {+ incrementId = 0;+ }++ while (true) {+ long tmpId = (System.currentTimeMillis() << 18) + incrementId;+ if (tmpId > lastTransactionId) {+ lastTransactionId = tmpId;+ return tmpId;+ }+ }+ }++ @Override+ public void close() throws IOException {+ scheduledThreadPoolExecutor.shutdownNow();+ try {+ scheduledThreadPoolExecutor.awaitTermination(2000, TimeUnit.MILLISECONDS);+ } catch (InterruptedException e) {+ LOGGER.warn(+ "Failed to close thread pool scheduledThreadPoolExecutor in TransactionIdGeneratorImpl with in 2000 milliseconds",+ e);+ }+ }+}diff --git a/core/src/main/java/com/datastrato/gravitino/storage/kv/TransactionalKvBackend.java b/core/src/main/java/com/datastrato/gravitino/storage/kv/TransactionalKvBackend.javanew file mode 100644index 0000000000..a61d0b62d5--- /dev/null+++ b/core/src/main/java/com/datastrato/gravitino/storage/kv/TransactionalKvBackend.java@@ -0,0 +1,23 @@+/*+ * Copyright 2023 Datastrato.+ * This software is licensed under the Apache License version 2.+ */++package com.datastrato.gravitino.storage.kv;++import java.io.IOException;++public interface TransactionalKvBackend extends KvBackend {++ /** Begin the transaction. */+ void begin();++ /** Commit the transaction. */+ void commit() throws IOException;++ /** Rollback the transaction if something goes wrong. */+ void rollback() throws IOException;++ /** Close the current transaction. */+ void closeTransaction();+}diff --git a/core/src/main/java/com/datastrato/gravitino/storage/kv/TransactionalKvBackendImpl.java b/core/src/main/java/com/datastrato/gravitino/storage/kv/TransactionalKvBackendImpl.javanew file mode 100644index 0000000000..98c6da9b9d--- /dev/null+++ b/core/src/main/java/com/datastrato/gravitino/storage/kv/TransactionalKvBackendImpl.java@@ -0,0 +1,343 @@+/*+ * Copyright 2023 Datastrato.+ * This software is licensed under the Apache License version 2.+ */++package com.datastrato.gravitino.storage.kv;++import com.datastrato.gravitino.Config;+import com.datastrato.gravitino.EntityAlreadyExistsException;+import com.datastrato.gravitino.storage.TransactionIdGenerator;+import com.datastrato.gravitino.utils.ByteUtils;+import com.datastrato.gravitino.utils.Bytes;+import com.google.common.annotations.VisibleForTesting;+import com.google.common.collect.Lists;+import java.io.IOException;+import java.nio.charset.StandardCharsets;+import java.util.List;+import javax.annotation.concurrent.ThreadSafe;+import org.apache.commons.lang3.ArrayUtils;+import org.apache.commons.lang3.tuple.Pair;++/**+ * TransactionalKvBackendImpl is an implementation of {@link TransactionalKvBackend} that uses 2PC+ * (Two-Phase Commit) to support transaction.+ *+ * <p>Assuming we have a key-value pair (k1, v1) and a transaction id 1, the key-value pair will be+ * store as+ *+ * <pre>+ * KEY VALUE+ * key1 + separator + 1 --> status_code + v1+ * tx + separator + 1 --> binary that contains all keys involved in this tx+ * </pre>+ *+ * We use '0x1F' as the separator, '______tx' as the value of tx, key1 + separator + 1 as the key of+ * the value, tx + separator + 1 as the flag to indicate that the transaction 1 has been+ * successfully committed and key1 can be visible or not, if transaction 1 fails(fail to write tx ++ * separator + 1) and there is no tx + separator + 1, the key1 is not visible.+ *+ * <p>The status_code is a 20-byte integer that indicates the status of the value. The first four+ * bytes of status code can be one of the following values:+ *+ * <pre>+ * 0x00000000(Metrication: 0) -- NORMAL, the value is visible+ * 0x00000001(Metrication: 1) -- DELETED, the value is deleted and not visible+ * </pre>+ */+@ThreadSafe+public class TransactionalKvBackendImpl implements TransactionalKvBackend {+ private final KvBackend kvBackend;+ private final TransactionIdGenerator transactionIdGenerator;++ @VisibleForTesting+ final ThreadLocal<List<Pair<byte[], byte[]>>> putPairs =+ ThreadLocal.withInitial(() -> Lists.newArrayList());++ private final ThreadLocal<List<byte[]>> originalKeys =+ ThreadLocal.withInitial(() -> Lists.newArrayList());++ private final ThreadLocal<Long> txId = new ThreadLocal<>();++ // 0x1E is control character RS+ private static final byte[] TRANSACTION_PREFIX = {0x1E};++ // Why use 8? We use 8 bytes to represent the status code, the first byte is used to+ // identify the status of the value, the rest 7 bytes are for future use.+ private static final int LENGTH_OF_VALUE_PREFIX = 8;++ // Why use 0x1F, 0x1F is a control character that is used as a delimiter in the text.+ private static final byte[] SEPARATOR = new byte[] {0x1F};++ private static final int LENGTH_OF_TRANSACTION_ID = Long.BYTES;+ private static final int LENGTH_OF_SEPARATOR = SEPARATOR.length;+ private static final int LENGTH_OF_VALUE_STATUS = Byte.BYTES;++ public TransactionalKvBackendImpl(+ KvBackend kvBackend, TransactionIdGenerator transactionIdGenerator) {+ this.kvBackend = kvBackend;+ this.transactionIdGenerator = transactionIdGenerator;+ }++ @Override+ public void begin() {+ if (!putPairs.get().isEmpty()) {+ throw new IllegalStateException(+ "The transaction is has not committed or rollback yet, you should commit or rollback it first");+ }++ txId.set(transactionIdGenerator.nextId());+ }++ @Override+ public void commit() throws IOException {+ try {+ if (putPairs.get().isEmpty()) {+ return;+ }++ // Prepare+ for (Pair<byte[], byte[]> pair : putPairs.get()) {+ kvBackend.put(pair.getKey(), pair.getValue(), true);+ }++ // Commit+ kvBackend.put(+ Bytes.concat(TRANSACTION_PREFIX, SEPARATOR, revert(ByteUtils.longToByte(txId.get()))),+ originalKeys.get().toString().getBytes(StandardCharsets.UTF_8),+ true);+ } finally {+ putPairs.get().clear();+ originalKeys.get().clear();+ }+ }++ @Override+ public void rollback() throws IOException {+ // Delete the update value+ for (Pair<byte[], byte[]> pair : putPairs.get()) {+ kvBackend.delete(pair.getKey());+ }+ }++ @Override+ public void initialize(Config config) throws IOException {}++ @Override+ public void put(byte[] key, byte[] value, boolean overwrite)+ throws IOException, EntityAlreadyExistsException {+ byte[] oldValue = get(key);+ if (oldValue != null && !overwrite) {+ throw new EntityAlreadyExistsException(+ "Key already exists: " + ByteUtils.formatByteArray(key));+ }+ putPairs.get().add(Pair.of(constructKey(key), constructValue(value, ValueStatusEnum.NORMAL)));+ originalKeys.get().add(key);+ }++ @Override+ public byte[] get(byte[] key) throws IOException {+ byte[] rawValue = getNextReadableValue(key);+ if (rawValue == null) {+ return null;+ }++ return getValue(rawValue);+ }++ @Override+ public boolean delete(byte[] key) throws IOException {+ byte[] oldValue = get(key);+ if (oldValue == null) {+ return false;+ }++ byte[] deletedValue = constructValue(oldValue, ValueStatusEnum.DELETED);+ putPairs.get().add(Pair.of(constructKey(key), deletedValue));+ originalKeys.get().add(key);+ return true;+ }++ @Override+ public boolean deleteRange(KvRangeScan kvRangeScan) throws IOException {+ List<Pair<byte[], byte[]>> pairs = scan(kvRangeScan);+ pairs.forEach(+ p ->+ putPairs+ .get()+ .add(+ Pair.of(+ constructKey(p.getKey()),+ constructValue(p.getValue(), ValueStatusEnum.DELETED))));+ return true;+ }++ @Override+ public List<Pair<byte[], byte[]>> scan(KvRangeScan scanRange) throws IOException {+ // Why we need to change the end key? Because we use the transaction id to construct a row key+ // Assuming the end key is 'a' and the value of endInclusive is true, if we want to scan the+ // value of key a, then we need to change the end key to 'b' and set the value of endInclusive+ // to false.+ byte[] end = scanRange.getEnd();+ boolean endInclude = scanRange.isEndInclusive();+ if (endInclude) {+ end = Bytes.increment(Bytes.wrap(end)).get();+ endInclude = false;+ }++ KvRangeScan kvRangeScan =+ new KvRangeScan.KvRangeScanBuilder()+ .start(scanRange.getStart())+ .end(end)+ .startInclusive(scanRange.isStartInclusive())+ .endInclusive(endInclude)+ .predicate(+ (k, v) -> {+ byte[] transactionId = getBinaryTransactionId((byte[]) k);+ return kvBackend.get(Bytes.concat(TRANSACTION_PREFIX, SEPARATOR, transactionId))+ != null;+ })+ .limit(Integer.MAX_VALUE)+ .build();++ List<Pair<byte[], byte[]>> rawPairs = kvBackend.scan(kvRangeScan);+ List<Pair<byte[], byte[]>> result = Lists.newArrayList();+ int i = 0, j = 0;+ while (i < scanRange.getLimit() && j < rawPairs.size()) {+ Pair<byte[], byte[]> pair = rawPairs.get(j);+ byte[] rawKey = pair.getKey();+ byte[] realKey = getRealKey(rawKey);+ Bytes minNextKey = Bytes.increment(Bytes.wrap(Bytes.concat(realKey, SEPARATOR)));++ // If the start key is exclusive and the key is equal to the start key, we need to skip it.+ if (!scanRange.isStartInclusive()+ && Bytes.wrap(realKey).compareTo(scanRange.getStart()) == 0) {+ while (j < rawPairs.size() && minNextKey.compareTo(rawPairs.get(j).getKey()) >= 0) {+ j++;+ }+ continue;+ }++ // If the end key is exclusive and the key is equal to the end key, we need to skip it.+ if (!scanRange.isEndInclusive() && Bytes.wrap(realKey).compareTo(scanRange.getEnd()) == 0) {+ break;+ }++ byte[] value = getValue(pair.getValue());+ if (value != null) {+ result.add(Pair.of(realKey, value));+ i++;+ }++ j++;+ // Skip all versions of the same key.+ while (j < rawPairs.size() && minNextKey.compareTo(rawPairs.get(j).getKey()) >= 0) {+ j++;+ }+ }++ return result;+ }++ @Override+ public void close() throws IOException {}++ @Override+ public void closeTransaction() {+ putPairs.get().clear();+ originalKeys.get().clear();+ }++ private byte[] getValue(byte[] rawValue) {+ byte[] firstType = ArrayUtils.subarray(rawValue, 0, LENGTH_OF_VALUE_STATUS);+ ValueStatusEnum statusEnum = ValueStatusEnum.fromCode(firstType[0]);+ if (statusEnum == ValueStatusEnum.DELETED) {+ // A deleted value is represented by a 4-byte integer with value 1+ return null;+ }+ return ArrayUtils.subarray(rawValue, LENGTH_OF_VALUE_PREFIX, rawValue.length);+ }++ @VisibleForTesting+ byte[] constructValue(byte[] value, ValueStatusEnum status) {+ byte[] statusCode = new byte[] {status.getCode()};+ byte[] prefix = new byte[LENGTH_OF_VALUE_PREFIX];+ System.arraycopy(statusCode, 0, prefix, 0, statusCode.length);+ return Bytes.concat(prefix, value);+ }++ @VisibleForTesting+ byte[] constructKey(byte[] key) {+ return Bytes.concat(key, SEPARATOR, revert(ByteUtils.longToByte(txId.get())));+ }++ /**+ * Get the latest readable value of the key as we support multi-version concurrency control+ * mechanism to keep multiple version data.+ */+ private byte[] getNextReadableValue(byte[] key) throws IOException {+ List<Pair<byte[], byte[]>> pairs =+ kvBackend.scan(+ new KvRangeScan.KvRangeScanBuilder()+ .start(key)+ .startInclusive(false)+ .end(Bytes.increment(Bytes.wrap(key)).get())+ .endInclusive(false)+ .predicate(+ (k, v) -> {+ byte[] transactionId = getBinaryTransactionId((byte[]) k);+ return kvBackend.get(+ Bytes.concat(TRANSACTION_PREFIX, SEPARATOR, transactionId))+ != null;+ })+ .limit(1)+ .build());++ if (pairs.isEmpty()) {+ return null;+ }++ return pairs.get(0).getValue();+ }++ /**+ * Revert the bytes, Why we need to revert the bytes? Because we use the transaction id to+ * construct a row key and need to place the latest version of the same key first. That is to say,+ * the latest version of a key is the smallest one in alphabetical order, in this case, we would+ * quickly locate the latest version of a key as key-value pair databases will sort keys in+ * ascending order.+ *+ * <p>Let's say we have a key "key1" and the transaction id is 1, 2, 3, 4, 5, 6, 7, 8, 9, 10. The+ * key-value pairs are:+ *+ * <pre>+ * key1 10+ * key1 9+ * key1 8+ * ...+ * </pre>+ *+ * Assuming we have two long values, a and b, a >= b, then we always have:+ * revert(ByteUtils.longToByte(a)) <= revert(ByteUtils.longToByte(b))+ *+ * <p>When we try to get the value of key1, we will first the value of key1 10 and can skip old+ * versions quickly.+ */+ private static byte[] revert(byte[] bytes) {+ for (int i = 0; i < bytes.length; i++) {+ bytes[i] = (byte) (bytes[i] ^ (byte) 0xff);+ }++ return bytes;+ }++ static byte[] getRealKey(byte[] rawKey) {+ return ArrayUtils.subarray(+ rawKey, 0, rawKey.length - LENGTH_OF_TRANSACTION_ID - LENGTH_OF_SEPARATOR);+ }++ /** Get the binary transaction id from the raw key. */+ static byte[] getBinaryTransactionId(byte[] rawKey) {+ return ArrayUtils.subarray(rawKey, rawKey.length - LENGTH_OF_TRANSACTION_ID, rawKey.length);+ }+}diff --git a/core/src/main/java/com/datastrato/gravitino/storage/kv/ValueStatusEnum.java b/core/src/main/java/com/datastrato/gravitino/storage/kv/ValueStatusEnum.javanew file mode 100644index 0000000000..5f980d5b13--- /dev/null+++ b/core/src/main/java/com/datastrato/gravitino/storage/kv/ValueStatusEnum.java@@ -0,0 +1,39 @@+/*+ * Copyright 2023 Datastrato.+ * This software is licensed under the Apache License version 2.+ */++package com.datastrato.gravitino.storage.kv;++/**+ * The status of a value. The value can be normal or deleted. The deleted value is not visible to+ * the user and can be garbage collected.+ *+ * <p>In the future, we may add more status, such as tombstone and so on.+ */+public enum ValueStatusEnum {+ // The value is normal.+ NORMAL((byte) 0),++ // The value has been deleted.+ DELETED((byte) 1);++ private final byte code;++ ValueStatusEnum(byte code) {+ this.code = code;+ }++ public byte getCode() {+ return code;+ }++ public static ValueStatusEnum fromCode(byte code) {+ for (ValueStatusEnum valueStatusEnum : ValueStatusEnum.values()) {+ if (valueStatusEnum.getCode() == code) {+ return valueStatusEnum;+ }+ }+ throw new IllegalArgumentException("Invalid code: " + code);+ }+}diff --git a/core/src/test/java/com/datastrato/gravitino/storage/kv/TestEntityKeyEncoding.java b/core/src/test/java/com/datastrato/gravitino/storage/kv/TestEntityKeyEncoding.javaindex d808cddc8e..51b4849448 100644--- a/core/src/test/java/com/datastrato/gravitino/storage/kv/TestEntityKeyEncoding.java+++ b/core/src/test/java/com/datastrato/gravitino/storage/kv/TestEntityKeyEncoding.java@@ -9,6 +9,7 @@ import static com.datastrato.gravitino.Configs.DEFAULT_ENTITY_KV_STORE;import static com.datastrato.gravitino.Configs.ENTITY_KV_STORE;import static com.datastrato.gravitino.Configs.ENTITY_STORE;import static com.datastrato.gravitino.Configs.ENTRY_KV_ROCKSDB_BACKEND_PATH;+import static com.datastrato.gravitino.Configs.STORE_TRANSACTION_MAX_SKEW_TIME;import static com.datastrato.gravitino.storage.kv.BinaryEntityKeyEncoder.BYTABLE_NAMESPACE_SEPARATOR;import static com.datastrato.gravitino.storage.kv.BinaryEntityKeyEncoder.WILD_CARD;@@ -16,22 +17,18 @@ import com.datastrato.gravitino.Config;import com.datastrato.gravitino.Configs;import com.datastrato.gravitino.Entity.EntityType;import com.datastrato.gravitino.EntitySerDeFactory;-import com.datastrato.gravitino.EntityStore;import com.datastrato.gravitino.EntityStoreFactory;import com.datastrato.gravitino.NameIdentifier;import com.datastrato.gravitino.Namespace;import com.datastrato.gravitino.storage.IdGenerator;-import com.datastrato.gravitino.storage.NameMappingService;import com.datastrato.gravitino.utils.ByteUtils;import com.datastrato.gravitino.utils.Bytes;+import com.google.common.io.Files;+import java.io.File;import java.io.IOException;import java.lang.reflect.Field;import java.nio.charset.StandardCharsets;-import org.apache.commons.io.FileUtils;-import org.junit.jupiter.api.AfterEach;import org.junit.jupiter.api.Assertions;-import org.junit.jupiter.api.BeforeAll;-import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.ClassOrderer.OrderAnnotation;import org.junit.jupiter.api.Order;import org.junit.jupiter.api.Test;@@ -43,22 +40,23 @@ import org.mockito.Mockito;@TestInstance(Lifecycle.PER_CLASS)@TestClassOrder(OrderAnnotation.class)public class TestEntityKeyEncoding {- private static final String ROCKS_DB_STORE_PATH = "/tmp/gravitino_test_entity_key_encoding";- private static Config config;-- public static EntityStore ENTITY_STORE_INSTANCE;- private static BinaryEntityKeyEncoder ENCODER;+ private Config getConfig() {+ File file = Files.createTempDir();+ file.deleteOnExit();+ Config config = Mockito.mock(Config.class);+ Mockito.when(config.get(Configs.ENTITY_SERDE)).thenReturn("proto");+ Mockito.when(config.get(ENTRY_KV_ROCKSDB_BACKEND_PATH)).thenReturn(file.getAbsolutePath());+ Mockito.when(config.get(STORE_TRANSACTION_MAX_SKEW_TIME)).thenReturn(3000L);+ Mockito.when(config.get(ENTITY_STORE)).thenReturn("kv");+ Mockito.when(config.get(ENTITY_KV_STORE)).thenReturn(DEFAULT_ENTITY_KV_STORE);+ return config;+ }- @BeforeEach- public void createEntityEncoderInstance() {- ENTITY_STORE_INSTANCE = EntityStoreFactory.createEntityStore(config);- Assertions.assertTrue(ENTITY_STORE_INSTANCE instanceof KvEntityStore);- ENTITY_STORE_INSTANCE.initialize(config);- ENTITY_STORE_INSTANCE.setSerDe(- EntitySerDeFactory.createEntitySerDe(config.get(Configs.ENTITY_SERDE)));- NameMappingService nameMappingService =- new KvNameMappingService(((KvEntityStore) ENTITY_STORE_INSTANCE).getBackend());- ENCODER = new BinaryEntityKeyEncoder(nameMappingService);+ private KvEntityStore getKvEntityStore(Config config) {+ KvEntityStore kvEntityStore = (KvEntityStore) EntityStoreFactory.createEntityStore(config);+ kvEntityStore.initialize(config);+ kvEntityStore.setSerDe(EntitySerDeFactory.createEntitySerDe(config.get(Configs.ENTITY_SERDE)));+ return kvEntityStore;}private IdGenerator getIdGeneratorAndSpy(BinaryEntityKeyEncoder entityKeyEncoder)@@ -74,212 +72,198 @@ public class TestEntityKeyEncoding {return spyIdGenerator;}- @AfterEach- public void cleanEnv() {- try {- if (ENTITY_STORE_INSTANCE != null) {- ENTITY_STORE_INSTANCE.close();+ @Test+ @Order(1)+ public void testIdentifierEncoding()+ throws IOException, IllegalAccessException, NoSuchFieldException {+ Config config = getConfig();+ try (KvEntityStore kvEntityStore = getKvEntityStore(config)) {+ BinaryEntityKeyEncoder encoder = (BinaryEntityKeyEncoder) kvEntityStore.entityKeyEncoder;++ // Metalake+ // metalake1 --> 0+ Namespace namespace = Namespace.of();+ IdGenerator mockIdGenerator = getIdGeneratorAndSpy(encoder);++ Mockito.doReturn(0L).when(mockIdGenerator).nextId();+ NameIdentifier mateLakeIdentifier1 = NameIdentifier.of(namespace, "metalake1");+ byte[] realKey = encoder.encode(mateLakeIdentifier1, EntityType.METALAKE);+ byte[] expectKey =+ Bytes.concat(+ EntityType.METALAKE.getShortName().getBytes(StandardCharsets.UTF_8),+ BYTABLE_NAMESPACE_SEPARATOR,+ ByteUtils.longToByte(0L));+ Assertions.assertArrayEquals(expectKey, realKey);++ // name ---> id+ // catalog1 --> 1+ // catalog2 --> 2+ // catalog3 --> 3+ Namespace catalogNamespace = Namespace.of("metalake1");+ NameIdentifier catalogIdentifier1 = NameIdentifier.of(catalogNamespace, "catalog1");+ NameIdentifier catalogIdentifier2 = NameIdentifier.of(catalogNamespace, "catalog2");+ NameIdentifier catalogIdentifier3 = NameIdentifier.of(catalogNamespace, "catalog3");+ NameIdentifier[] catalogIdentifiers =+ new NameIdentifier[] {catalogIdentifier1, catalogIdentifier2, catalogIdentifier3};++ for (int i = 0; i < catalogIdentifiers.length; i++) {+ Mockito.doReturn(1L + i).when(mockIdGenerator).nextId();+ NameIdentifier identifier = catalogIdentifiers[i];+ realKey = encoder.encode(identifier, EntityType.CATALOG);+ expectKey =+ Bytes.concat(+ EntityType.CATALOG.getShortName().getBytes(StandardCharsets.UTF_8),+ BYTABLE_NAMESPACE_SEPARATOR,+ ByteUtils.longToByte(0L),+ BYTABLE_NAMESPACE_SEPARATOR,+ ByteUtils.longToByte(1L + i));+ Assertions.assertArrayEquals(expectKey, realKey);}- FileUtils.deleteDirectory(FileUtils.getFile(ROCKS_DB_STORE_PATH));+ // name ---> id+ // schema1 --> 4+ // schema2 --> 5+ // schema3 --> 6+ Namespace schemaNameSpace = Namespace.of("metalake1", "catalog2");+ NameIdentifier schemaIdentifier1 = NameIdentifier.of(schemaNameSpace, "schema1");+ NameIdentifier schemaIdentifier2 = NameIdentifier.of(schemaNameSpace, "schema2");+ NameIdentifier schemaIdentifier3 = NameIdentifier.of(schemaNameSpace, "schema3");+ NameIdentifier[] schemaIdentifiers =+ new NameIdentifier[] {schemaIdentifier1, schemaIdentifier2, schemaIdentifier3};- } catch (Exception e) {- // Ignore- }- }+ for (int i = 0; i < schemaIdentifiers.length; i++) {+ NameIdentifier identifier = schemaIdentifiers[i];+ Mockito.doReturn(4L + i).when(mockIdGenerator).nextId();+ realKey = encoder.encode(identifier, EntityType.SCHEMA);+ expectKey =+ Bytes.concat(+ EntityType.SCHEMA.getShortName().getBytes(StandardCharsets.UTF_8),+ BYTABLE_NAMESPACE_SEPARATOR,+ ByteUtils.longToByte(0L),+ BYTABLE_NAMESPACE_SEPARATOR,+ ByteUtils.longToByte(2L),+ BYTABLE_NAMESPACE_SEPARATOR,+ ByteUtils.longToByte(4L + i));+ Assertions.assertArrayEquals(expectKey, realKey);+ }- @BeforeAll- public void prepare() {- config = Mockito.mock(Config.class);- Mockito.when(config.get(ENTITY_STORE)).thenReturn("kv");- Mockito.when(config.get(ENTITY_KV_STORE)).thenReturn(DEFAULT_ENTITY_KV_STORE);- Mockito.when(config.get(Configs.ENTITY_SERDE)).thenReturn("proto");- Mockito.when(config.get(ENTRY_KV_ROCKSDB_BACKEND_PATH)).thenReturn(ROCKS_DB_STORE_PATH);+ // name ---> id+ // table1 --> 7+ // table2 --> 8+ // table3 --> 9+ Namespace tableNameSpace = Namespace.of("metalake1", "catalog2", "schema3");+ NameIdentifier tableIdentifier1 = NameIdentifier.of(tableNameSpace, "table1");+ NameIdentifier tableIdentifier2 = NameIdentifier.of(tableNameSpace, "table2");+ NameIdentifier tableIdentifier3 = NameIdentifier.of(tableNameSpace, "table3");+ NameIdentifier[] tableIdentifiers =+ new NameIdentifier[] {tableIdentifier1, tableIdentifier2, tableIdentifier3};++ for (int i = 0; i < tableIdentifiers.length; i++) {+ NameIdentifier identifier = tableIdentifiers[i];+ Mockito.doReturn(7L + i).when(mockIdGenerator).nextId();+ realKey = encoder.encode(identifier, EntityType.TABLE);+ expectKey =+ Bytes.concat(+ EntityType.TABLE.getShortName().getBytes(StandardCharsets.UTF_8),+ BYTABLE_NAMESPACE_SEPARATOR,+ ByteUtils.longToByte(0L),+ BYTABLE_NAMESPACE_SEPARATOR,+ ByteUtils.longToByte(2L),+ BYTABLE_NAMESPACE_SEPARATOR,+ ByteUtils.longToByte(6L),+ BYTABLE_NAMESPACE_SEPARATOR,+ ByteUtils.longToByte(i + 7L));+ Assertions.assertArrayEquals(expectKey, realKey);+ }++ // Unsupported operation+ Mockito.doReturn(10L).when(mockIdGenerator).nextId();+ Assertions.assertThrows(+ UnsupportedOperationException.class,+ () -> {+ encoder.encode(+ NameIdentifier.of(+ Namespace.of("metalake1", "catalog2", "schema3", "table1"), "column1"),+ EntityType.COLUMN);+ });+ }}@Test- @Order(1)- public void testIdentifierEncoding()+ @Order(10)+ public void testNamespaceEncoding()throws IOException, IllegalAccessException, NoSuchFieldException {- // Metalake- // metalake1 --> 0- Namespace namespace = Namespace.of();- IdGenerator mockIdGenerator = getIdGeneratorAndSpy(ENCODER);+ Config config = getConfig();+ try (KvEntityStore kvEntityStore = getKvEntityStore(config)) {+ BinaryEntityKeyEncoder encoder = (BinaryEntityKeyEncoder) kvEntityStore.entityKeyEncoder;+ // Scan all Metalake+ Namespace namespace = Namespace.of();+ IdGenerator mockIdGenerator = getIdGeneratorAndSpy(encoder);- Mockito.doReturn(0L).when(mockIdGenerator).nextId();- NameIdentifier mateLakeIdentifier1 = NameIdentifier.of(namespace, "metalake1");- byte[] realKey = ENCODER.encode(mateLakeIdentifier1, EntityType.METALAKE);- byte[] expectKey =- Bytes.concat(- EntityType.METALAKE.getShortName().getBytes(StandardCharsets.UTF_8),- BYTABLE_NAMESPACE_SEPARATOR,- ByteUtils.longToByte(0L));- Assertions.assertArrayEquals(expectKey, realKey);-- // name ---> id- // catalog1 --> 1- // catalog2 --> 2- // catalog3 --> 3- Namespace catalogNamespace = Namespace.of("metalake1");- NameIdentifier catalogIdentifier1 = NameIdentifier.of(catalogNamespace, "catalog1");- NameIdentifier catalogIdentifier2 = NameIdentifier.of(catalogNamespace, "catalog2");- NameIdentifier catalogIdentifier3 = NameIdentifier.of(catalogNamespace, "catalog3");- NameIdentifier[] catalogIdentifiers =- new NameIdentifier[] {catalogIdentifier1, catalogIdentifier2, catalogIdentifier3};+ NameIdentifier metalakeIdentifier = NameIdentifier.of(namespace, WILD_CARD);+ byte[] realKey = encoder.encode(metalakeIdentifier, EntityType.METALAKE);+ byte[] expectKey =+ Bytes.concat(+ EntityType.METALAKE.getShortName().getBytes(StandardCharsets.UTF_8),+ BYTABLE_NAMESPACE_SEPARATOR);+ Assertions.assertArrayEquals(expectKey, realKey);- for (int i = 0; i < catalogIdentifiers.length; i++) {- Mockito.doReturn(1L + i).when(mockIdGenerator).nextId();- NameIdentifier identifier = catalogIdentifiers[i];- realKey = ENCODER.encode(identifier, EntityType.CATALOG);+ // Scan all catalog in metalake1+ // metalake1 --> 0L+ Mockito.doReturn(0L).when(mockIdGenerator).nextId();+ Namespace catalogNamespace = Namespace.of("metalake1");+ NameIdentifier catalogIdentifier = NameIdentifier.of(catalogNamespace, WILD_CARD);+ realKey = encoder.encode(catalogIdentifier, EntityType.CATALOG);expectKey =Bytes.concat(EntityType.CATALOG.getShortName().getBytes(StandardCharsets.UTF_8),BYTABLE_NAMESPACE_SEPARATOR,ByteUtils.longToByte(0L),- BYTABLE_NAMESPACE_SEPARATOR,- ByteUtils.longToByte(1L + i));+ BYTABLE_NAMESPACE_SEPARATOR);Assertions.assertArrayEquals(expectKey, realKey);- }-- // name ---> id- // schema1 --> 4- // schema2 --> 5- // schema3 --> 6- Namespace schemaNameSpace = Namespace.of("metalake1", "catalog2");- NameIdentifier schemaIdentifier1 = NameIdentifier.of(schemaNameSpace, "schema1");- NameIdentifier schemaIdentifier2 = NameIdentifier.of(schemaNameSpace, "schema2");- NameIdentifier schemaIdentifier3 = NameIdentifier.of(schemaNameSpace, "schema3");- NameIdentifier[] schemaIdentifiers =- new NameIdentifier[] {schemaIdentifier1, schemaIdentifier2, schemaIdentifier3};- for (int i = 0; i < schemaIdentifiers.length; i++) {- NameIdentifier identifier = schemaIdentifiers[i];- Mockito.doReturn(4L + i).when(mockIdGenerator).nextId();- realKey = ENCODER.encode(identifier, EntityType.SCHEMA);+ // Scan all sc in metalake1.catalog2+ // catalog2 --> 1+ Mockito.doReturn(1L).when(mockIdGenerator).nextId();+ Namespace schemaNameSpace = Namespace.of("metalake1", "catalog2");+ NameIdentifier schemaIdentifier = NameIdentifier.of(schemaNameSpace, WILD_CARD);+ realKey = encoder.encode(schemaIdentifier, EntityType.SCHEMA);expectKey =Bytes.concat(EntityType.SCHEMA.getShortName().getBytes(StandardCharsets.UTF_8),BYTABLE_NAMESPACE_SEPARATOR,ByteUtils.longToByte(0L),BYTABLE_NAMESPACE_SEPARATOR,- ByteUtils.longToByte(2L),- BYTABLE_NAMESPACE_SEPARATOR,- ByteUtils.longToByte(4L + i));+ ByteUtils.longToByte(1L),+ BYTABLE_NAMESPACE_SEPARATOR);Assertions.assertArrayEquals(expectKey, realKey);- }-- // name ---> id- // table1 --> 7- // table2 --> 8- // table3 --> 9- Namespace tableNameSpace = Namespace.of("metalake1", "catalog2", "schema3");- NameIdentifier tableIdentifier1 = NameIdentifier.of(tableNameSpace, "table1");- NameIdentifier tableIdentifier2 = NameIdentifier.of(tableNameSpace, "table2");- NameIdentifier tableIdentifier3 = NameIdentifier.of(tableNameSpace, "table3");- NameIdentifier[] tableIdentifiers =- new NameIdentifier[] {tableIdentifier1, tableIdentifier2, tableIdentifier3};- for (int i = 0; i < tableIdentifiers.length; i++) {- NameIdentifier identifier = tableIdentifiers[i];- Mockito.doReturn(7L + i).when(mockIdGenerator).nextId();- realKey = ENCODER.encode(identifier, EntityType.TABLE);+ // Scan all table in metalake1.catalog2.schema3+ // schema3 --> 2+ Mockito.doReturn(2L).when(mockIdGenerator).nextId();+ Namespace tableNameSpace = Namespace.of("metalake1", "catalog2", "schema3");+ NameIdentifier tableIdentifier = NameIdentifier.of(tableNameSpace, WILD_CARD);+ realKey = encoder.encode(tableIdentifier, EntityType.TABLE);expectKey =Bytes.concat(EntityType.TABLE.getShortName().getBytes(StandardCharsets.UTF_8),BYTABLE_NAMESPACE_SEPARATOR,ByteUtils.longToByte(0L),BYTABLE_NAMESPACE_SEPARATOR,- ByteUtils.longToByte(2L),- BYTABLE_NAMESPACE_SEPARATOR,- ByteUtils.longToByte(6L),+ ByteUtils.longToByte(1L),BYTABLE_NAMESPACE_SEPARATOR,- ByteUtils.longToByte(i + 7L));+ ByteUtils.longToByte(2L),+ BYTABLE_NAMESPACE_SEPARATOR);Assertions.assertArrayEquals(expectKey, realKey);- }-- // Unsupported operation- Mockito.doReturn(10L).when(mockIdGenerator).nextId();- Assertions.assertThrows(- UnsupportedOperationException.class,- () -> {- ENCODER.encode(- NameIdentifier.of(- Namespace.of("metalake1", "catalog2", "schema3", "table1"), "column1"),- EntityType.COLUMN);- });- }-- @Test- @Order(10)- public void testNamespaceEncoding()- throws IOException, IllegalAccessException, NoSuchFieldException {- // Scan all Metalake- Namespace namespace = Namespace.of();- IdGenerator mockIdGenerator = getIdGeneratorAndSpy(ENCODER);-- NameIdentifier metalakeIdentifier = NameIdentifier.of(namespace, WILD_CARD);- byte[] realKey = ENCODER.encode(metalakeIdentifier, EntityType.METALAKE);- byte[] expectKey =- Bytes.concat(- EntityType.METALAKE.getShortName().getBytes(StandardCharsets.UTF_8),- BYTABLE_NAMESPACE_SEPARATOR);- Assertions.assertArrayEquals(expectKey, realKey);-- // Scan all catalog in metalake1- // metalake1 --> 0L- Mockito.doReturn(0L).when(mockIdGenerator).nextId();- Namespace catalogNamespace = Namespace.of("metalake1");- NameIdentifier catalogIdentifier = NameIdentifier.of(catalogNamespace, WILD_CARD);- realKey = ENCODER.encode(catalogIdentifier, EntityType.CATALOG);- expectKey =- Bytes.concat(- EntityType.CATALOG.getShortName().getBytes(StandardCharsets.UTF_8),- BYTABLE_NAMESPACE_SEPARATOR,- ByteUtils.longToByte(0L),- BYTABLE_NAMESPACE_SEPARATOR);- Assertions.assertArrayEquals(expectKey, realKey);-- // Scan all sc in metalake1.catalog2- // catalog2 --> 1- Mockito.doReturn(1L).when(mockIdGenerator).nextId();- Namespace schemaNameSpace = Namespace.of("metalake1", "catalog2");- NameIdentifier schemaIdentifier = NameIdentifier.of(schemaNameSpace, WILD_CARD);- realKey = ENCODER.encode(schemaIdentifier, EntityType.SCHEMA);- expectKey =- Bytes.concat(- EntityType.SCHEMA.getShortName().getBytes(StandardCharsets.UTF_8),- BYTABLE_NAMESPACE_SEPARATOR,- ByteUtils.longToByte(0L),- BYTABLE_NAMESPACE_SEPARATOR,- ByteUtils.longToByte(1L),- BYTABLE_NAMESPACE_SEPARATOR);- Assertions.assertArrayEquals(expectKey, realKey);- // Scan all table in metalake1.catalog2.schema3- // schema3 --> 2- Mockito.doReturn(2L).when(mockIdGenerator).nextId();- Namespace tableNameSpace = Namespace.of("metalake1", "catalog2", "schema3");- NameIdentifier tableIdentifier = NameIdentifier.of(tableNameSpace, WILD_CARD);- realKey = ENCODER.encode(tableIdentifier, EntityType.TABLE);- expectKey =- Bytes.concat(- EntityType.TABLE.getShortName().getBytes(StandardCharsets.UTF_8),- BYTABLE_NAMESPACE_SEPARATOR,- ByteUtils.longToByte(0L),- BYTABLE_NAMESPACE_SEPARATOR,- ByteUtils.longToByte(1L),- BYTABLE_NAMESPACE_SEPARATOR,- ByteUtils.longToByte(2L),- BYTABLE_NAMESPACE_SEPARATOR);- Assertions.assertArrayEquals(expectKey, realKey);-- Mockito.doReturn(3L).when(mockIdGenerator).nextId();- Assertions.assertThrows(- UnsupportedOperationException.class,- () ->- ENCODER.encode(- NameIdentifier.of(- Namespace.of("metalake1", "catalog2", "schema3", "table1"), WILD_CARD),- EntityType.COLUMN));+ Mockito.doReturn(3L).when(mockIdGenerator).nextId();+ Assertions.assertThrows(+ UnsupportedOperationException.class,+ () ->+ encoder.encode(+ NameIdentifier.of(+ Namespace.of("metalake1", "catalog2", "schema3", "table1"), WILD_CARD),+ EntityType.COLUMN));+ }}}diff --git a/core/src/test/java/com/datastrato/gravitino/storage/kv/TestKvEntityStorage.java b/core/src/test/java/com/datastrato/gravitino/storage/kv/TestKvEntityStorage.javaindex 59945fe1cf..48b4f33b2e 100644--- a/core/src/test/java/com/datastrato/gravitino/storage/kv/TestKvEntityStorage.java+++ b/core/src/test/java/com/datastrato/gravitino/storage/kv/TestKvEntityStorage.java@@ -9,6 +9,7 @@ import static com.datastrato.gravitino.Configs.DEFAULT_ENTITY_KV_STORE;import static com.datastrato.gravitino.Configs.ENTITY_KV_STORE;import static com.datastrato.gravitino.Configs.ENTITY_STORE;import static com.datastrato.gravitino.Configs.ENTRY_KV_ROCKSDB_BACKEND_PATH;+import static com.datastrato.gravitino.Configs.STORE_TRANSACTION_MAX_SKEW_TIME;import com.datastrato.gravitino.Catalog.Type;import com.datastrato.gravitino.Config;@@ -112,6 +113,8 @@ public class TestKvEntityStorage {Mockito.when(config.get(ENTRY_KV_ROCKSDB_BACKEND_PATH)).thenReturn(ROCKS_DB_STORE_PATH);Assertions.assertEquals(ROCKS_DB_STORE_PATH, config.get(ENTRY_KV_ROCKSDB_BACKEND_PATH));+ Mockito.when(config.get(STORE_TRANSACTION_MAX_SKEW_TIME)).thenReturn(1000L);+AuditInfo auditInfo =new AuditInfo.Builder().withCreator("creator").withCreateTime(Instant.now()).build();@@ -194,6 +197,7 @@ public class TestKvEntityStorage {Mockito.when(config.get(ENTITY_KV_STORE)).thenReturn(DEFAULT_ENTITY_KV_STORE);Mockito.when(config.get(Configs.ENTITY_SERDE)).thenReturn("proto");Mockito.when(config.get(ENTRY_KV_ROCKSDB_BACKEND_PATH)).thenReturn(ROCKS_DB_STORE_PATH);+ Mockito.when(config.get(STORE_TRANSACTION_MAX_SKEW_TIME)).thenReturn(1000L);Assertions.assertEquals(ROCKS_DB_STORE_PATH, config.get(ENTRY_KV_ROCKSDB_BACKEND_PATH));AuditInfo auditInfo =@@ -475,6 +479,8 @@ public class TestKvEntityStorage {Mockito.when(config.get(ENTITY_KV_STORE)).thenReturn(DEFAULT_ENTITY_KV_STORE);Mockito.when(config.get(Configs.ENTITY_SERDE)).thenReturn("proto");Mockito.when(config.get(ENTRY_KV_ROCKSDB_BACKEND_PATH)).thenReturn("/tmp/gravitino");+ Mockito.when(config.get(STORE_TRANSACTION_MAX_SKEW_TIME)).thenReturn(1000L);+FileUtils.deleteDirectory(FileUtils.getFile("/tmp/gravitino"));AuditInfo auditInfo =@@ -619,7 +625,7 @@ public class TestKvEntityStorage {Assertions.assertThrowsExactly(NoSuchEntityException.class,- () -> store.get(schema2.nameIdentifier(), EntityType.SCHEMA, CatalogEntity.class));+ () -> store.get(schema2.nameIdentifier(), EntityType.SCHEMA, SchemaEntity.class));Assertions.assertTrue(store.delete(metalake.nameIdentifier(), EntityType.METALAKE, true));@@ -637,6 +643,7 @@ public class TestKvEntityStorage {Mockito.when(config.get(ENTITY_KV_STORE)).thenReturn(DEFAULT_ENTITY_KV_STORE);Mockito.when(config.get(Configs.ENTITY_SERDE)).thenReturn("proto");Mockito.when(config.get(ENTRY_KV_ROCKSDB_BACKEND_PATH)).thenReturn("/tmp/gravitino");+ Mockito.when(config.get(STORE_TRANSACTION_MAX_SKEW_TIME)).thenReturn(1000L);FileUtils.deleteDirectory(FileUtils.getFile("/tmp/gravitino"));try (EntityStore store = EntityStoreFactory.createEntityStore(config)) {@@ -655,35 +662,15 @@ public class TestKvEntityStorage {createCatalog(Namespace.of("metalake"), "catalogCopyAgain", auditInfo);// First, we try to test transactional is OK- Assertions.assertThrows(- NoSuchEntityException.class,- () -> store.get(metalake.nameIdentifier(), EntityType.METALAKE, BaseMetalake.class));- try {- store.executeInTransaction(- () -> {- store.put(metalake);- // Try to mock an exception- double a = 1 / 0;- store.put(catalog);- return null;- });- } catch (Exception e) {- Assertions.assertTrue(e instanceof ArithmeticException);- }-Assertions.assertThrows(NoSuchEntityException.class,() -> store.get(metalake.nameIdentifier(), EntityType.METALAKE, BaseMetalake.class));- store.executeInTransaction(- () -> {- store.put(metalake);- store.put(catalog);- store.put(metalakeCopy);- store.put(catalogCopy);- store.put(catalogCopyAgain);- return null;- });+ store.put(metalake);+ store.put(catalog);+ store.put(metalakeCopy);+ store.put(catalogCopy);+ store.put(catalogCopyAgain);Metalake retrievedMetalake =store.get(metalake.nameIdentifier(), EntityType.METALAKE, BaseMetalake.class);@@ -756,6 +743,7 @@ public class TestKvEntityStorage {Mockito.when(config.get(ENTITY_KV_STORE)).thenReturn(DEFAULT_ENTITY_KV_STORE);Mockito.when(config.get(Configs.ENTITY_SERDE)).thenReturn("proto");Mockito.when(config.get(ENTRY_KV_ROCKSDB_BACKEND_PATH)).thenReturn(file.getAbsolutePath());+ Mockito.when(config.get(STORE_TRANSACTION_MAX_SKEW_TIME)).thenReturn(1000L);ThreadPoolExecutor threadPoolExecutor =new ThreadPoolExecutor(10,@@ -868,6 +856,7 @@ public class TestKvEntityStorage {Mockito.when(config.get(ENTITY_KV_STORE)).thenReturn(DEFAULT_ENTITY_KV_STORE);Mockito.when(config.get(Configs.ENTITY_SERDE)).thenReturn("proto");Mockito.when(config.get(ENTRY_KV_ROCKSDB_BACKEND_PATH)).thenReturn(file.getAbsolutePath());+ Mockito.when(config.get(STORE_TRANSACTION_MAX_SKEW_TIME)).thenReturn(1000L);// First time create entity store, the storage layout version should be DEFAULT_LAYOUT_VERSIONtry (EntityStore store = EntityStoreFactory.createEntityStore(config)) {diff --git a/core/src/test/java/com/datastrato/gravitino/storage/kv/TestKvNameMappingService.java b/core/src/test/java/com/datastrato/gravitino/storage/kv/TestKvNameMappingService.javaindex 0f75b12e8d..1a05892f09 100644--- a/core/src/test/java/com/datastrato/gravitino/storage/kv/TestKvNameMappingService.java+++ b/core/src/test/java/com/datastrato/gravitino/storage/kv/TestKvNameMappingService.java@@ -9,17 +9,18 @@ import static com.datastrato.gravitino.Configs.DEFAULT_ENTITY_KV_STORE;import static com.datastrato.gravitino.Configs.ENTITY_KV_STORE;import static com.datastrato.gravitino.Configs.ENTITY_STORE;import static com.datastrato.gravitino.Configs.ENTRY_KV_ROCKSDB_BACKEND_PATH;+import static com.datastrato.gravitino.Configs.STORE_TRANSACTION_MAX_SKEW_TIME;import com.datastrato.gravitino.Config;import com.datastrato.gravitino.Configs;+import com.datastrato.gravitino.EntitySerDeFactory;+import com.datastrato.gravitino.EntityStoreFactory;import com.datastrato.gravitino.storage.IdGenerator;import com.datastrato.gravitino.storage.NameMappingService;-import com.datastrato.gravitino.storage.RandomIdGenerator;-import java.io.IOException;+import com.google.common.io.Files;+import java.io.File;import java.lang.reflect.Field;-import org.apache.commons.io.FileUtils;import org.junit.jupiter.api.Assertions;-import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.ClassOrderer.OrderAnnotation;import org.junit.jupiter.api.Order;import org.junit.jupiter.api.Test;@@ -28,32 +29,26 @@ import org.mockito.Mockito;@TestClassOrder(OrderAnnotation.class)public class TestKvNameMappingService {-- public static final String ROCKS_DB_STORE_PATH = "/tmp/gravitino_name_mapping";- private final IdGenerator idGenerator = new RandomIdGenerator();-- @BeforeEach- public void cleanEnv() {- try {- FileUtils.deleteDirectory(FileUtils.getFile(ROCKS_DB_STORE_PATH));- } catch (Exception e) {- // Ignore- }- }-- private KvNameMappingService createNameMappingService(String kvPath) throws IOException {+ private Config getConfig() {+ File file = Files.createTempDir();+ file.deleteOnExit();Config config = Mockito.mock(Config.class);+ Mockito.when(config.get(Configs.ENTITY_SERDE)).thenReturn("proto");+ Mockito.when(config.get(ENTRY_KV_ROCKSDB_BACKEND_PATH)).thenReturn(file.getAbsolutePath());+ Mockito.when(config.get(STORE_TRANSACTION_MAX_SKEW_TIME)).thenReturn(3000L);Mockito.when(config.get(ENTITY_STORE)).thenReturn("kv");Mockito.when(config.get(ENTITY_KV_STORE)).thenReturn(DEFAULT_ENTITY_KV_STORE);- Mockito.when(config.get(Configs.ENTITY_SERDE)).thenReturn("proto");- Mockito.when(config.get(ENTRY_KV_ROCKSDB_BACKEND_PATH)).thenReturn(kvPath);+ return config;+ }- KvBackend backend = new RocksDBKvBackend();- backend.initialize(config);- return new KvNameMappingService(backend);+ private KvEntityStore getKvEntityStore(Config config) {+ KvEntityStore kvEntityStore = (KvEntityStore) EntityStoreFactory.createEntityStore(config);+ kvEntityStore.initialize(config);+ kvEntityStore.setSerDe(EntitySerDeFactory.createEntitySerDe(config.get(Configs.ENTITY_SERDE)));+ return kvEntityStore;}- private IdGenerator getIdGeneratorByRefection(NameMappingService nameMappingService)+ private IdGenerator getIdGeneratorByReflection(NameMappingService nameMappingService)throws Exception {Field field = nameMappingService.getClass().getDeclaredField("idGenerator");field.setAccessible(true);@@ -66,11 +61,11 @@ public class TestKvNameMappingService {@Test@Order(1)public void testGetIdByName() throws Exception {- try (NameMappingService nameMappingService =- createNameMappingService(ROCKS_DB_STORE_PATH + "/1")) {+ try (KvEntityStore kvEntityStore = getKvEntityStore(getConfig())) {+ NameMappingService nameMappingService = kvEntityStore.nameMappingService;Assertions.assertNull(nameMappingService.getIdByName("name1"));- IdGenerator spyIdGenerator = getIdGeneratorByRefection(nameMappingService);+ IdGenerator spyIdGenerator = getIdGeneratorByReflection(nameMappingService);Mockito.doReturn(1L).when(spyIdGenerator).nextId();long name1Id = nameMappingService.getOrCreateIdFromName("name1");@@ -88,9 +83,9 @@ public class TestKvNameMappingService {@Test@Order(2)public void testUpdateName() throws Exception {- try (NameMappingService nameMappingService =- createNameMappingService(ROCKS_DB_STORE_PATH + "/2")) {- IdGenerator idGenerator = getIdGeneratorByRefection(nameMappingService);+ try (KvEntityStore kvEntityStore = getKvEntityStore(getConfig())) {+ NameMappingService nameMappingService = kvEntityStore.nameMappingService;+ IdGenerator idGenerator = getIdGeneratorByReflection(nameMappingService);Mockito.doReturn(1L).when(idGenerator).nextId();long name1IdRead = nameMappingService.getOrCreateIdFromName("name1");Assertions.assertNotNull(nameMappingService.getIdByName("name1"));@@ -114,29 +109,41 @@ public class TestKvNameMappingService {@Test@Order(3)public void testBindAndUnBind() throws Exception {- idGenerator.nextId();- NameMappingService nameMappingService = createNameMappingService(ROCKS_DB_STORE_PATH + "/3");- IdGenerator idGenerator = getIdGeneratorByRefection(nameMappingService);-- Mockito.doReturn(1L).when(idGenerator).nextId();- nameMappingService.getOrCreateIdFromName("name1");- Assertions.assertNotNull(nameMappingService.getIdByName("name1"));-- boolean result = nameMappingService.unbindNameAndId("name1");- Assertions.assertTrue(result);- Assertions.assertNull(nameMappingService.getIdByName("name1"));-- Mockito.doReturn(2L).when(idGenerator).nextId();- nameMappingService.getOrCreateIdFromName("name2");-- KvBackend spyKvBackend = Mockito.spy(((KvNameMappingService) nameMappingService).backend);- Mockito.doThrow(new ArithmeticException()).when(spyKvBackend).delete(Mockito.any());- final NameMappingService mock = new KvNameMappingService(spyKvBackend);-- // Now we try to use update. It should fail.- Assertions.assertThrowsExactly(- ArithmeticException.class, () -> mock.updateName("name2", "name3"));- Assertions.assertNull(mock.getIdByName("name3"));- Assertions.assertNotNull(mock.getIdByName("name2"));+ try (KvEntityStore kvEntityStore = getKvEntityStore(getConfig())) {+ KvNameMappingService nameMappingService =+ (KvNameMappingService) kvEntityStore.nameMappingService;+ IdGenerator idGenerator = getIdGeneratorByReflection(nameMappingService);++ Mockito.doReturn(1L).when(idGenerator).nextId();+ nameMappingService.getOrCreateIdFromName("name1");+ Assertions.assertNotNull(nameMappingService.getIdByName("name1"));++ boolean result = nameMappingService.unbindNameAndId("name1");+ Assertions.assertTrue(result);+ Assertions.assertNull(nameMappingService.getIdByName("name1"));++ Mockito.doReturn(2L).when(idGenerator).nextId();+ nameMappingService.getOrCreateIdFromName("name2");++ TransactionalKvBackend spyKvBackend =+ Mockito.spy(((KvNameMappingService) nameMappingService).transactionalKvBackend);+ // All deletes && puts will be converted to put operations.+ Mockito.doThrow(new ArithmeticException())+ .when(spyKvBackend)+ .put(Mockito.any(), Mockito.any(), Mockito.anyBoolean());+ Config config = Mockito.mock(Config.class);+ Mockito.when(config.get(STORE_TRANSACTION_MAX_SKEW_TIME)).thenReturn(3000L);+ final NameMappingService mock =+ new KvNameMappingService(spyKvBackend, nameMappingService.lock);++ // Now we try to use update. It should fail.+ Assertions.assertThrowsExactly(+ ArithmeticException.class, () -> mock.updateName("name2", "name3"));+ Mockito.doCallRealMethod()+ .when(spyKvBackend)+ .put(Mockito.any(), Mockito.any(), Mockito.anyBoolean());+ Assertions.assertNull(mock.getIdByName("name3"));+ Assertions.assertNotNull(mock.getIdByName("name2"));+ }}}diff --git a/core/src/test/java/com/datastrato/gravitino/storage/kv/TestTransactionIdGenerator.java b/core/src/test/java/com/datastrato/gravitino/storage/kv/TestTransactionIdGenerator.javanew file mode 100644index 0000000000..6bbb5f0e6f--- /dev/null+++ b/core/src/test/java/com/datastrato/gravitino/storage/kv/TestTransactionIdGenerator.java@@ -0,0 +1,104 @@+/*+ * Copyright 2023 Datastrato.+ * This software is licensed under the Apache License version 2.+ */++package com.datastrato.gravitino.storage.kv;++import static com.datastrato.gravitino.Configs.ENTRY_KV_ROCKSDB_BACKEND_PATH;+import static com.datastrato.gravitino.Configs.STORE_TRANSACTION_MAX_SKEW_TIME;++import com.datastrato.gravitino.Config;+import com.datastrato.gravitino.Configs;+import com.datastrato.gravitino.storage.TransactionIdGenerator;+import com.google.common.io.Files;+import com.google.common.util.concurrent.ThreadFactoryBuilder;+import java.io.File;+import java.io.IOException;+import java.nio.charset.StandardCharsets;+import java.util.concurrent.LinkedBlockingQueue;+import java.util.concurrent.ThreadPoolExecutor;+import java.util.concurrent.TimeUnit;+import java.util.concurrent.atomic.AtomicLong;+import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.Disabled;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.ValueSource;+import org.mockito.Mockito;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++public class TestTransactionIdGenerator {++ private static final Logger LOGGER = LoggerFactory.getLogger(TestTransactionalKvBackend.class);++ private Config getConfig() {+ File file = Files.createTempDir();+ file.deleteOnExit();+ Config config = Mockito.mock(Config.class);+ Mockito.when(config.get(Configs.ENTITY_SERDE)).thenReturn("proto");+ Mockito.when(config.get(ENTRY_KV_ROCKSDB_BACKEND_PATH)).thenReturn(file.getAbsolutePath());+ Mockito.when(config.get(STORE_TRANSACTION_MAX_SKEW_TIME)).thenReturn(3000L);+ return config;+ }++ private KvBackend getKvBackEnd(Config config) throws IOException {+ KvBackend kvBackend = new RocksDBKvBackend();+ kvBackend.initialize(config);+ return kvBackend;+ }++ @Test+ void testSchedulerAndSkewTime() throws IOException, InterruptedException {+ Config config = getConfig();+ Mockito.when(config.get(STORE_TRANSACTION_MAX_SKEW_TIME)).thenReturn(1000L);+ KvBackend kvBackend = getKvBackEnd(config);+ TransactionIdGenerator transactionIdGenerator =+ new TransactionIdGeneratorImpl(kvBackend, config);+ transactionIdGenerator.start();+ // Make sure the scheduler has schedule once+ Thread.sleep(2000 + 500);+ Assertions.assertNotNull(+ kvBackend.get(TransactionIdGeneratorImpl.LAST_TIMESTAMP.getBytes(StandardCharsets.UTF_8)));+ }++ @ParameterizedTest+ @ValueSource(ints = {16})+ @Disabled("It's very time-consuming, so we disable it by default.")+ void testTransactionIdGeneratorQPS(int threadNum) throws IOException, InterruptedException {+ Config config = getConfig();+ String path = config.get(ENTRY_KV_ROCKSDB_BACKEND_PATH);+ LOGGER.info("testTransactionIdGeneratorQPS path: {}", path);+ KvBackend kvBackend = getKvBackEnd(config);+ TransactionIdGenerator transactionIdGenerator =+ new TransactionIdGeneratorImpl(kvBackend, config);+ ThreadPoolExecutor threadPoolExecutor =+ new ThreadPoolExecutor(+ threadNum,+ threadNum,+ 1,+ TimeUnit.MINUTES,+ new LinkedBlockingQueue<>(1000),+ new ThreadFactoryBuilder()+ .setDaemon(false)+ .setNameFormat("testTransactionIdGenerator-%d")+ .build());++ AtomicLong atomicLong = new AtomicLong(0);+ for (int i = 0; i < threadNum; i++) {+ threadPoolExecutor.execute(+ () -> {+ long current = System.currentTimeMillis();+ while (System.currentTimeMillis() - current <= 2000) {+ transactionIdGenerator.nextId();+ atomicLong.getAndIncrement();+ }+ });+ }+ Thread.currentThread().sleep(100);+ threadPoolExecutor.shutdown();+ threadPoolExecutor.awaitTermination(5, TimeUnit.SECONDS);+ LOGGER.info(String.format("%d thread qps is: %d/s", threadNum, atomicLong.get() / 2));+ }+}diff --git a/core/src/test/java/com/datastrato/gravitino/storage/kv/TestTransactionalKvBackend.java b/core/src/test/java/com/datastrato/gravitino/storage/kv/TestTransactionalKvBackend.javanew file mode 100644index 0000000000..702e9c3b3f--- /dev/null+++ b/core/src/test/java/com/datastrato/gravitino/storage/kv/TestTransactionalKvBackend.java@@ -0,0 +1,423 @@+/*+ * Copyright 2023 Datastrato.+ * This software is licensed under the Apache License version 2.+ */++package com.datastrato.gravitino.storage.kv;++import static com.datastrato.gravitino.Configs.ENTRY_KV_ROCKSDB_BACKEND_PATH;+import static com.datastrato.gravitino.Configs.STORE_TRANSACTION_MAX_SKEW_TIME;++import com.datastrato.gravitino.Config;+import com.datastrato.gravitino.Configs;+import com.datastrato.gravitino.storage.TransactionIdGenerator;+import com.google.common.collect.Lists;+import com.google.common.io.Files;+import com.google.common.util.concurrent.ThreadFactoryBuilder;+import java.io.File;+import java.io.IOException;+import java.nio.charset.StandardCharsets;+import java.util.Arrays;+import java.util.HashMap;+import java.util.List;+import java.util.Map;+import java.util.concurrent.LinkedBlockingQueue;+import java.util.concurrent.ThreadLocalRandom;+import java.util.concurrent.ThreadPoolExecutor;+import java.util.concurrent.TimeUnit;+import java.util.concurrent.atomic.AtomicLong;+import java.util.stream.Collectors;+import org.apache.commons.lang3.ArrayUtils;+import org.apache.commons.lang3.tuple.Pair;+import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.Disabled;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.ValueSource;+import org.mockito.Mockito;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++class TestTransactionalKvBackend {++ private static final Logger LOGGER = LoggerFactory.getLogger(TestTransactionalKvBackend.class);++ private Config getConfig() {+ File file = Files.createTempDir();+ file.deleteOnExit();+ Config config = Mockito.mock(Config.class);+ Mockito.when(config.get(Configs.ENTITY_SERDE)).thenReturn("proto");+ Mockito.when(config.get(ENTRY_KV_ROCKSDB_BACKEND_PATH)).thenReturn(file.getAbsolutePath());+ Mockito.when(config.get(STORE_TRANSACTION_MAX_SKEW_TIME)).thenReturn(3000L);+ return config;+ }++ private KvBackend getKvBackEnd(Config config) throws IOException {+ KvBackend kvBackend = new RocksDBKvBackend();+ kvBackend.initialize(config);+ return kvBackend;+ }++ @Test+ void testGet() throws IOException {+ Config config = getConfig();+ KvBackend kvBackend = getKvBackEnd(config);+ TransactionIdGenerator transactionIdGenerator =+ new TransactionIdGeneratorImpl(kvBackend, config);+ TransactionalKvBackend transactionalKvBackend =+ new TransactionalKvBackendImpl(kvBackend, transactionIdGenerator);+ transactionalKvBackend.begin();+ transactionalKvBackend.put("key1".getBytes(), "value1".getBytes(), true);+ transactionalKvBackend.put("key2".getBytes(), "value2".getBytes(), true);+ transactionalKvBackend.commit();++ transactionalKvBackend.begin();+ Assertions.assertEquals("value1", new String(transactionalKvBackend.get("key1".getBytes())));+ Assertions.assertEquals("value2", new String(transactionalKvBackend.get("key2".getBytes())));++ transactionalKvBackend.begin();+ transactionalKvBackend.put("key1".getBytes(), "value3".getBytes(), true);+ transactionalKvBackend.put("key2".getBytes(), "value4".getBytes(), true);+ transactionalKvBackend.commit();+ transactionalKvBackend.close();++ transactionalKvBackend.begin();+ Assertions.assertEquals("value3", new String(transactionalKvBackend.get("key1".getBytes())));+ Assertions.assertEquals("value4", new String(transactionalKvBackend.get("key2".getBytes())));+ transactionalKvBackend.close();+ transactionIdGenerator.close();+ }++ @Test+ void testDelete() throws IOException {+ Config config = getConfig();+ KvBackend kvBackend = getKvBackEnd(config);+ TransactionIdGenerator transactionIdGenerator =+ new TransactionIdGeneratorImpl(kvBackend, config);+ TransactionalKvBackend transactionalKvBackend =+ new TransactionalKvBackendImpl(kvBackend, transactionIdGenerator);+ transactionalKvBackend.begin();+ transactionalKvBackend.put("key1".getBytes(), "value1".getBytes(), true);+ transactionalKvBackend.put("key2".getBytes(), "value2".getBytes(), true);+ transactionalKvBackend.commit();++ transactionalKvBackend.begin();+ transactionalKvBackend.delete("key1".getBytes());+ transactionalKvBackend.commit();++ transactionalKvBackend.begin();+ Assertions.assertNull(transactionalKvBackend.get("key1".getBytes()));+ Assertions.assertNotNull(transactionalKvBackend.get("key2".getBytes()));++ transactionalKvBackend.begin();+ transactionalKvBackend.delete("key2".getBytes());+ transactionalKvBackend.commit();++ Assertions.assertNull(transactionalKvBackend.get("key1".getBytes()));+ Assertions.assertNull(transactionalKvBackend.get("key2".getBytes()));+ transactionalKvBackend.close();+ transactionIdGenerator.close();+ }++ @Test+ void testScan() throws IOException {+ Config config = getConfig();+ KvBackend kvBackend = getKvBackEnd(config);+ TransactionIdGenerator transactionIdGenerator =+ new TransactionIdGeneratorImpl(kvBackend, config);+ TransactionalKvBackend transactionalKvBackend =+ new TransactionalKvBackendImpl(kvBackend, transactionIdGenerator);+ transactionalKvBackend.begin();++ transactionalKvBackend.put("key1".getBytes(), "value1".getBytes(), true);+ transactionalKvBackend.put("key2".getBytes(), "value2".getBytes(), true);+ transactionalKvBackend.put("key3".getBytes(), "value3".getBytes(), true);+ transactionalKvBackend.commit();+ transactionalKvBackend.close();++ Map<String, String> map =+ new HashMap<String, String>() {+ {+ put("key1", "value1");+ put("key2", "value2");+ put("key3", "value3");+ }+ };++ transactionalKvBackend =+ new TransactionalKvBackendImpl(+ kvBackend, new TransactionIdGeneratorImpl(kvBackend, config));+ transactionalKvBackend.begin();+ List<Pair<byte[], byte[]>> pairs =+ transactionalKvBackend.scan(+ new KvRangeScan.KvRangeScanBuilder()+ .start("k".getBytes())+ .end("kez".getBytes())+ .startInclusive(false)+ .endInclusive(false)+ .build());+ Assertions.assertEquals(3, pairs.size());+ for (Pair<byte[], byte[]> pair : pairs) {+ Assertions.assertEquals(map.get(new String(pair.getKey())), new String(pair.getValue()));+ }+ List<String> resultList =+ pairs.stream().map(p -> new String(p.getKey())).collect(Collectors.toList());+ Assertions.assertEquals(Lists.newArrayList("key1", "key2", "key3"), resultList);++ pairs =+ transactionalKvBackend.scan(+ new KvRangeScan.KvRangeScanBuilder()+ .start("key1".getBytes())+ .end("kez".getBytes())+ .startInclusive(false)+ .endInclusive(true)+ .build());+ Assertions.assertEquals(2, pairs.size());+ for (Pair<byte[], byte[]> pair : pairs) {+ Assertions.assertEquals(map.get(new String(pair.getKey())), new String(pair.getValue()));+ }+ resultList = pairs.stream().map(p -> new String(p.getKey())).collect(Collectors.toList());+ Assertions.assertEquals(Lists.newArrayList("key2", "key3"), resultList);++ pairs =+ transactionalKvBackend.scan(+ new KvRangeScan.KvRangeScanBuilder()+ .start("key1".getBytes())+ .end("key3".getBytes())+ .startInclusive(false)+ .endInclusive(false)+ .build());+ Assertions.assertEquals(1, pairs.size());+ for (Pair<byte[], byte[]> pair : pairs) {+ Assertions.assertEquals(map.get(new String(pair.getKey())), new String(pair.getValue()));+ }+ resultList = pairs.stream().map(p -> new String(p.getKey())).collect(Collectors.toList());+ Assertions.assertEquals(Lists.newArrayList("key2"), resultList);++ pairs =+ transactionalKvBackend.scan(+ new KvRangeScan.KvRangeScanBuilder()+ .start("key3".getBytes())+ .end("kez".getBytes())+ .startInclusive(true)+ .endInclusive(true)+ .build());+ Assertions.assertEquals(1, pairs.size());+ for (Pair<byte[], byte[]> pair : pairs) {+ Assertions.assertEquals(map.get(new String(pair.getKey())), new String(pair.getValue()));+ }+ resultList = pairs.stream().map(p -> new String(p.getKey())).collect(Collectors.toList());+ Assertions.assertEquals(Lists.newArrayList("key3"), resultList);++ pairs =+ transactionalKvBackend.scan(+ new KvRangeScan.KvRangeScanBuilder()+ .start("kf".getBytes())+ .end("kg".getBytes())+ .startInclusive(true)+ .endInclusive(true)+ .build());+ Assertions.assertEquals(0, pairs.size());+ transactionIdGenerator.close();+ }++ @Test+ void testDeleteRange() throws IOException {+ Config config = getConfig();+ KvBackend kvBackend = getKvBackEnd(config);+ TransactionIdGenerator transactionIdGenerator =+ new TransactionIdGeneratorImpl(kvBackend, config);+ TransactionalKvBackend transactionalKvBackend =+ new TransactionalKvBackendImpl(kvBackend, transactionIdGenerator);+ transactionalKvBackend.begin();+ transactionalKvBackend.put("key1".getBytes(), "value1".getBytes(), true);+ transactionalKvBackend.put("key2".getBytes(), "value2".getBytes(), true);+ transactionalKvBackend.put("key3".getBytes(), "value3".getBytes(), true);+ transactionalKvBackend.commit();++ transactionalKvBackend.begin();+ transactionalKvBackend.deleteRange(+ new KvRangeScan.KvRangeScanBuilder()+ .start("key1".getBytes())+ .end("key3".getBytes())+ .startInclusive(true)+ .endInclusive(true)+ .build());+ transactionalKvBackend.commit();++ transactionalKvBackend.begin();+ Assertions.assertNull(transactionalKvBackend.get("key1".getBytes()));+ Assertions.assertNull(transactionalKvBackend.get("key2".getBytes()));+ Assertions.assertNull(transactionalKvBackend.get("key3".getBytes()));+ transactionalKvBackend.close();+ transactionIdGenerator.close();+ }++ @Test+ void testException() throws IOException, InterruptedException {+ Config config = getConfig();+ KvBackend kvBackend = getKvBackEnd(config);+ TransactionIdGenerator transactionIdGenerator =+ new TransactionIdGeneratorImpl(kvBackend, config);+ TransactionalKvBackendImpl kvTransactionManager =+ new TransactionalKvBackendImpl(kvBackend, transactionIdGenerator);+ kvTransactionManager.begin();+ List<Pair<byte[], byte[]>> pairs =+ Lists.newArrayList(+ Pair.of(+ kvTransactionManager.constructKey("key1".getBytes()),+ kvTransactionManager.constructValue("value1".getBytes(), ValueStatusEnum.NORMAL)),+ Pair.of(+ kvTransactionManager.constructKey("key2".getBytes()),+ kvTransactionManager.constructValue("value2".getBytes(), ValueStatusEnum.NORMAL)),+ Pair.of(+ kvTransactionManager.constructKey("key3".getBytes()),+ kvTransactionManager.constructValue("value3".getBytes(), ValueStatusEnum.NORMAL)),+ Pair.of(+ kvTransactionManager.constructKey("key4".getBytes()),+ kvTransactionManager.constructValue("value4".getBytes(), ValueStatusEnum.NORMAL)),+ Pair.of(+ kvTransactionManager.constructKey("key5".getBytes()),+ kvTransactionManager.constructValue("value6".getBytes(), ValueStatusEnum.NORMAL)),+ Pair.of(+ kvTransactionManager.constructKey("key6".getBytes()),+ kvTransactionManager.constructValue("value7".getBytes(), ValueStatusEnum.NORMAL)),+ Pair.of(+ kvTransactionManager.constructKey("key7".getBytes()),+ kvTransactionManager.constructValue("value8".getBytes(), ValueStatusEnum.NORMAL)),+ Pair.of(+ kvTransactionManager.constructKey("key8".getBytes()),+ kvTransactionManager.constructValue("value9".getBytes(), ValueStatusEnum.NORMAL)),++ // Will throw NPE to roll back the transaction.+ Pair.of(kvTransactionManager.constructKey("key9".getBytes()), null));++ Pair<byte[], byte[]>[] arrayPair = pairs.toArray(new Pair[0]);++ kvTransactionManager = new TransactionalKvBackendImpl(kvBackend, transactionIdGenerator);+ for (int i = 0; i < 10000; i++) {+ ArrayUtils.shuffle(arrayPair);++ kvTransactionManager+ .putPairs+ .get()+ .addAll(Arrays.stream(arrayPair).collect(Collectors.toList()));+ Assertions.assertThrows(Exception.class, kvTransactionManager::commit);++ kvTransactionManager.begin();+ Assertions.assertNull(kvTransactionManager.get("key1".getBytes()));+ Assertions.assertNull(kvTransactionManager.get("key2".getBytes()));+ Assertions.assertNull(kvTransactionManager.get("key3".getBytes()));+ Assertions.assertNull(kvTransactionManager.get("key4".getBytes()));+ Assertions.assertNull(kvTransactionManager.get("key5".getBytes()));+ Assertions.assertNull(kvTransactionManager.get("key6".getBytes()));+ Assertions.assertNull(kvTransactionManager.get("key7".getBytes()));+ Assertions.assertNull(kvTransactionManager.get("key8".getBytes()));+ Assertions.assertNull(kvTransactionManager.get("key9".getBytes()));+ }+ Thread.sleep(1000);+ transactionIdGenerator.close();+ }++ @ParameterizedTest+ @ValueSource(ints = {16})+ @Disabled("It's very time-consuming, so we disable it by default.")+ void testConcurrentRead(int threadNum) throws IOException, InterruptedException {+ Config config = getConfig();+ KvBackend kvBackend = getKvBackEnd(config);+ TransactionIdGenerator transactionIdGenerator =+ new TransactionIdGeneratorImpl(kvBackend, config);+ TransactionalKvBackend transactionalKvBackend =+ new TransactionalKvBackendImpl(kvBackend, transactionIdGenerator);+ transactionalKvBackend.begin();+ for (int i = 0; i < threadNum; i++) {+ transactionalKvBackend.put(+ ("key" + i).getBytes(StandardCharsets.UTF_8),+ ("value" + i).getBytes(StandardCharsets.UTF_8),+ true);+ }+ transactionalKvBackend.commit();+ transactionalKvBackend.closeTransaction();++ ThreadPoolExecutor threadPoolExecutor =+ new ThreadPoolExecutor(+ threadNum,+ threadNum,+ 1,+ TimeUnit.MINUTES,+ new LinkedBlockingQueue<>(1000),+ new ThreadFactoryBuilder()+ .setDaemon(false)+ .setNameFormat("testTransactionIdGenerator-%d")+ .build());++ ThreadLocalRandom random = ThreadLocalRandom.current();+ long current = System.currentTimeMillis();+ AtomicLong atomicLong = new AtomicLong(0);+ threadPoolExecutor.submit(+ () -> {+ while (System.currentTimeMillis() - current <= 2000) {+ transactionalKvBackend.begin();+ int i = random.nextInt(threadNum) + 1;+ byte[] binaryValue =+ Assertions.assertDoesNotThrow(+ () -> transactionalKvBackend.get(("key" + i).getBytes(StandardCharsets.UTF_8)));+ Assertions.assertEquals(("value" + i).getBytes(StandardCharsets.UTF_8), binaryValue);+ transactionalKvBackend.closeTransaction();+ atomicLong.getAndIncrement();+ }+ });++ Thread.currentThread().sleep(100);+ threadPoolExecutor.shutdown();+ threadPoolExecutor.awaitTermination(5, TimeUnit.SECONDS);+ LOGGER.info(String.format("%d thread qps is: %d/s", threadNum, atomicLong.get() / 2));+ }++ @ParameterizedTest+ @ValueSource(ints = {1, 2, 4, 16, 32})+ @Disabled("It's very time-consuming, so we disable it by default.")+ void testConcurrentWrite(int threadNum) throws IOException, InterruptedException {+ Config config = getConfig();+ KvBackend kvBackend = getKvBackEnd(config);+ TransactionIdGenerator transactionIdGenerator =+ new TransactionIdGeneratorImpl(kvBackend, config);+ TransactionalKvBackend transactionalKvBackend =+ new TransactionalKvBackendImpl(kvBackend, transactionIdGenerator);+ ThreadPoolExecutor threadPoolExecutor =+ new ThreadPoolExecutor(+ threadNum,+ threadNum,+ 1,+ TimeUnit.MINUTES,+ new LinkedBlockingQueue<>(1000),+ new ThreadFactoryBuilder()+ .setDaemon(false)+ .setNameFormat("testTransactionIdGenerator-%d")+ .build());++ ThreadLocalRandom random = ThreadLocalRandom.current();+ long current = System.currentTimeMillis();+ AtomicLong atomicLong = new AtomicLong(0);+ threadPoolExecutor.submit(+ () -> {+ while (System.currentTimeMillis() - current <= 2000) {+ transactionalKvBackend.begin();+ int i = random.nextInt(threadNum) + 1;+ Assertions.assertDoesNotThrow(+ () ->+ transactionalKvBackend.put(+ ("key" + i).getBytes(StandardCharsets.UTF_8),+ ("value" + i).getBytes(StandardCharsets.UTF_8),+ true));+ transactionalKvBackend.closeTransaction();+ atomicLong.getAndIncrement();+ }+ });++ Thread.currentThread().sleep(100);+ threadPoolExecutor.shutdown();+ threadPoolExecutor.awaitTermination(5, TimeUnit.SECONDS);+ LOGGER.info(String.format("%d thread write qps is: %d/s", threadNum, atomicLong.get() / 2));+ }+}diff --git a/docs/gravitino-server-config.md b/docs/gravitino-server-config.mdindex 0208f2afbb..468eed85be 100644--- a/docs/gravitino-server-config.md+++ b/docs/gravitino-server-config.md@@ -35,11 +35,12 @@ The following table lists the configuration items in the `gravitino.conf` file.### Storage configuration-| Configuration item | Description | Default value | Since version |-|-----------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------|---------------|-| `gravitino.entity.store` | Which storage implementation to use, currently we only support key-value pair storage, default value is `kv`. | `kv` | 0.1.0 |-| `gravitino.entity.store.kv` | Detailed implementation of kv storage, currently we only support `RocksDB` storage implementation `RocksDBKvBackend`. | `RocksDBKvBackend` | 0.1.0 |-| `gravitino.entity.store.kv.rocksdbPath` | Directory path of `RocksDBKvBackend`, **we highly recommend you to change this default value** as it's under the deploy directory and version update operations may remove it. | `${GRAVITINO_HOME}/data/rocksdb` | 0.1.0 |+| Configuration item | Description | Default value | Since version |+|---------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------|---------------|+| `gravitino.entity.store` | Which storage implementation to use, currently we only support key-value pair storage, default value is `kv`. | `kv` | 0.1.0 |+| `gravitino.entity.store.kv` | Detailed implementation of kv storage, currently we only support `RocksDB` storage implementation `RocksDBKvBackend`. | `RocksDBKvBackend` | 0.1.0 |+| `gravitino.entity.store.kv.rocksdbPath` | Directory path of `RocksDBKvBackend`, **we highly recommend you to change this default value** as it's under the deploy directory and version update operations may remove it. | `${GRAVITINO_HOME}/data/rocksdb` | 0.1.0 |+| `gravitino.entity.store.maxTransactionSkewTimeMs` | The max skew time of transaction, unit: millisecond. | `2000` | 0.3.0 |### Catalog configurationdiff --git a/rfc/resouces/Transaction.jpg b/rfc/resouces/Transaction.jpgnew file mode 100644index 0000000000..e707ba392eBinary files /dev/null and b/rfc/resouces/Transaction.jpg differdiff --git a/rfc/rfc-3/Transaction-implementation-on-kv.md b/rfc/rfc-3/Transaction-implementation-on-kv.mdnew file mode 100644index 0000000000..4cb4a3b5a6--- /dev/null+++ b/rfc/rfc-3/Transaction-implementation-on-kv.md@@ -0,0 +1,119 @@+<!--+ Copyright 2023 Datastrato.+ This software is licensed under the Apache License version 2.+-->++# RFC-1: Design of transaction mechanism on key-value store++| Revision | Owner | Date |+| :------- |-------|------------|+| v0.1 | Qi Yu | 21/11/2023 |++++## Background+Currently, our storage layer heavily relies on the transaction mechanism provided by key-value storage backend such as RocksDB to ensure reliability. However, some key-value pair databases do not support transaction operations, making it challenging for Gravitino to adapt to other+KV databases such as Redis, Cassandra, Hbase, and so on.++To make gravitino adapt different key-value stores, we need to eliminate transactional dependency and come up with alternative solutions.++## Goal++1. Support transaction operations on key-value store+2. Do not make too much change to the current storage layer+3. Easy to implement and maintain.++## Design++Based on [previous design](../rfc-2/Entity-key-encoding-for-kv-store.md), to support transaction, we use MVCC to implement transaction mechanism. The main idea is to add a version number to each key-value pair. When a transaction is committed, we will update the version number of the key-value pair. When a transaction is aborted, we will delete the key-value pair.+The following figure shows the design of transaction mechanism.++++Note:+1. A, B, C, is the original keys+2. ts1, ts2, ts3 are the timestamp of the transaction+3. tx_ts1, tx_ts2, tx_ts3 are commit marks.++Take the above figure as an example, the transaction is as follows:+Assuming we want to update three key-values pairs:+1. Change the value of Key A from 100 to 150+2. Change the value of Key B from 150 to 200+3. Change the value of Key C from 300 to 200++The transaction process is as follows:++**Prepare stage**+1. First, we will get a TSO(Timestamp oracle) named ts2 as the transaction id.+2. Then we will read old values of A, B, C using the TSO ts2.+3. Update the value of A, B, C to 150, 200, 200 respectively.+4. Then we will add a version number to each key-value pair, the version number is the transaction id.+5. Then we will write the new key-value pairs to the storage layer.++**Commit stage**+We would construct the commit mark tx_ts2 and save it to the storage layer. The value of tx_ts2 contains+all keys in the transaction.++**Rollback stage**+If any steps in prepare stage or commit stage fails, we will roll back the transaction. In fact, we+need to do nothing to roll back the transaction. Because we have added a version number to each key-value pair and+those keys in the failed transaction will not be visible to users.+++## Detail implementation++### Write process++Assuming we want to put key-value pairs 'key1:value1' and 'key2:value2' to the storage layer. The tso we get is 1, The process is as follows:++In prepare stage, we will put the following keys into the storage layer:+```+KEY: 0x6B657931 1F FFFFFFFFFFFFFFFE ---> VALUE: 0x00000000 00000000 76616C756531+KEY: 0x6B657932 1F FFFFFFFFFFFFFFFE ---> VALUE: 0x00000000 00000000 76616C756532+```+- `6B657931`: the hex of 'key1'+- `1F`: we use `1F` space as the separator of key and TSO.+- `FFFFFFFFFFFFFFFE`: Represent tso 1. Note, we use 8 bytes to represent tso. How to convert 1 to `FFFFFFFFFFFFFFFE`? First we convert 1 to 0x0000000000000001, then we use `^` 0xFF to get the complement of 0x0000000000000001, then we get 0xFFFFFFFFFFFFFFFE.+ Why we need to do So? we want to make sure that the key-value pair with the same key and different tso can be sorted in descending order. that is: if tso1 >= tso2, then binary(tso1) <= binary(tso2).+- `00000000 00000000 76616C756531`: the hex format of 'value1'. The first byte `0x00` means is put operation, if the value is '0x01', it marks the key-value pair has been deleted.++In the commit stage, we will put the following keys into the storage layer:+```+KEY: 0x1E 1F FFFFFFFFFFFFFFFE ---> VALUE: keys of the transaction involved.+```+- `1E`: prefix of transaction commit mark+- `1F`: separator+- `FFFFFFFFFFFFFFFE`: Represent tso 1. Note, we use 8 bytes to represent tso. How to convert 1 to `FFFFFFFFFFFFFFFE`? First we convert 1 to 0x0000000000000001, then we use `^` 0xFF to get the complement of 0x0000000000000001, then we get 0xFFFFFFFFFFFFFFFE.++### Read process++Assuming we have the following key-value pairs in storage layer:+```+KEY: 0x6B657931 1F FFFFFFFFFFFFFFFD ---> VALUE: 0x00000000 00000000 76616C756532+KEY: 0x6B657931 1F FFFFFFFFFFFFFFFE ---> VALUE: 0x00000000 00000000 76616C756531+KEY: 0x1E 1F FFFFFFFFFFFFFFFD ---> VALUE: keys of the transaction involved.+KEY: 0x1E 1F FFFFFFFFFFFFFFFE ---> VALUE: keys of the transaction involved.+```+If we want to get the value of key1, the process is as follows:+1. First, we will get a TSO(Timestamp oracle) 3 as the transaction id.+2. Construct the start key to scan the storage layer: `0x6B657931 1F FFFFFFFFFFFFFFFC`+3. Find the first key that with prefix `0x6B657931` and greater than start key `0x6B657931 1F FFFFFFFFFFFFFFFC`, we will get `0x6B657931 1F FFFFFFFFFFFFFFFD`+4. If there exists the key `0x1E 1F FFFFFFFFFFFFFFFE`, means the transaction is committed, then we will get the value of key1 from `0x6B657931 1F FFFFFFFFFFFFFFFD`.+5. or repeat steps 3+6. If the value of key `0x6B657931 1F FFFFFFFFFFFFFFFD` starts will `0x00`, then we will get the value of key1 from `0x6B657931 1F FFFFFFFFFFFFFFFD`. if the value of key `0x6B657931 1F FFFFFFFFFFFFFFFD` starts will `0x01`, it means this key-value pair has been removed, so we return null.++### Delete process+Delete steps are almost the same as that of write process except that the prefix of it is `0x01` instead of `0x00`.++Put key 'test1':+```+KEY: 0x6B657931 1F FFFFFFFFFFFFFFFE ---> VALUE: 0x00000000 00000000 76616C756531+```++Delete key 'test1':+```+KEY: 0x6B657931 1F FFFFFFFFFFFFFFFE ---> VALUE: 0x01000000 00000000 76616C756531+```++### Scan and range query process+Scan and range query are almost the same as that of read process, for more detailed information, please see related implementation `TransactionalKvBackendImpl`.\ No newline at end of file