World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#234] refactor(core): Replace current id mapping logic with IdMappingService (#254)
Qi Yu227a5931dfa7
diff --git a/core/src/main/java/com/datastrato/graviton/storage/EntityKeyEncoder.java b/core/src/main/java/com/datastrato/graviton/storage/EntityKeyEncoder.javaindex dd63da1dd4..3ff96188f3 100644--- a/core/src/main/java/com/datastrato/graviton/storage/EntityKeyEncoder.java+++ b/core/src/main/java/com/datastrato/graviton/storage/EntityKeyEncoder.java@@ -5,7 +5,6 @@package com.datastrato.graviton.storage;-import com.datastrato.graviton.Entity.EntityIdentifier;import com.datastrato.graviton.Entity.EntityType;import com.datastrato.graviton.NameIdentifier;import java.io.IOException;@@ -15,20 +14,6 @@ public interface EntityKeyEncoder<T> {/*** Construct the key for key-value store from the entity NameIdentifier and EntityType.*- * @param entityIdentifier entity identifier to encode- * @param createIdIfNotExists create the id mapping for name if not exists- * @return encoded key for key-value store- * @throws IOException Exception if error occurs- */- byte[] encode(EntityIdentifier entityIdentifier, boolean createIdIfNotExists) throws IOException;-- /**- * Construct the key for key-value store from the entity NameIdentifier and EntityType.- *- * <p>Note, This method is the replacement of {@link #encode(EntityIdentifier, boolean)}. When we- * implement this method, we should mark {@link #encode(EntityIdentifier, boolean)} as deprecated- * and remove it later.- ** @param ident entity identifier to encode* @param type entity type to encode* @return encoded key for key-value storeddiff --git a/core/src/main/java/com/datastrato/graviton/storage/NameMappingService.java b/core/src/main/java/com/datastrato/graviton/storage/NameMappingService.javaindex 141d9269ec..e524ce5412 100644--- a/core/src/main/java/com/datastrato/graviton/storage/NameMappingService.java+++ b/core/src/main/java/com/datastrato/graviton/storage/NameMappingService.java@@ -17,7 +17,7 @@ import java.io.IOException;public interface NameMappingService extends AutoCloseable {/**- * Get id from name.+ * Get id by name in the mapping service.** @param name the name of the entity* @return the id of the name, or null if the name does not exist@@ -26,16 +26,14 @@ public interface NameMappingService extends AutoCloseable {Long getIdByName(String name) throws IOException;/**- * If we do not find the id of the name in the name mapping service. We will add a new id for the- * name mapping- *- * <p>Note, this method should be called in transaction.+ * Get id from name. If the name does not exist, we will create a new id for the name and bind the+ * mapping between them** @param name the name of the entity- * @param id the id of the name to be binded+ * @return the id of the name* @throws IOException if the underlying storage failed*/- void bindNameAndId(String name, long id) throws IOException;+ long getOrCreateIdFromName(String name) throws IOException;/*** Update the mapping of the name to id. This method is used to update the mapping when we renamediff --git a/core/src/main/java/com/datastrato/graviton/storage/kv/BinaryEntityKeyEncoder.java b/core/src/main/java/com/datastrato/graviton/storage/kv/BinaryEntityKeyEncoder.javaindex 4433046595..7a89999756 100644--- a/core/src/main/java/com/datastrato/graviton/storage/kv/BinaryEntityKeyEncoder.java+++ b/core/src/main/java/com/datastrato/graviton/storage/kv/BinaryEntityKeyEncoder.java@@ -9,12 +9,10 @@ import static com.datastrato.graviton.Entity.EntityType.METALAKE;import static com.datastrato.graviton.Entity.EntityType.SCHEMA;import static com.datastrato.graviton.Entity.EntityType.TABLE;-import com.datastrato.graviton.Entity.EntityIdentifier;import com.datastrato.graviton.Entity.EntityType;import com.datastrato.graviton.NameIdentifier;-import com.datastrato.graviton.exceptions.NoSuchEntityException;import com.datastrato.graviton.storage.EntityKeyEncoder;-import com.datastrato.graviton.storage.IdGenerator;+import com.datastrato.graviton.storage.NameMappingService;import com.datastrato.graviton.util.ByteUtils;import com.datastrato.graviton.util.Bytes;import com.google.common.annotations.VisibleForTesting;@@ -22,7 +20,6 @@ import com.google.common.base.Preconditions;import com.google.common.collect.ImmutableMap;import java.io.IOException;import java.util.Map;-import java.util.UUID;import org.slf4j.Logger;import org.slf4j.LoggerFactory;@@ -50,26 +47,10 @@ import org.slf4j.LoggerFactory;public class BinaryEntityKeyEncoder implements EntityKeyEncoder<byte[]> {public static final Logger LOG = LoggerFactory.getLogger(BinaryEntityKeyEncoder.class);- // name prefix of name in name to id mapping,- // e.g., name_metalake1 -> 1- // name_metalake2 -> 2- private static final byte[] NAME_PREFIX = "name_".getBytes();-- // id prefix of id in name to id mapping,- // e.g., id_1 -> metalake1- // id_2 -> metalake2- private static final byte[] ID_PREFIX = "id_".getBytes();-- // Store current max id, -1 if not exists, e.g., if current_max_id is 0, that means only one- // ID has been created, and the next id should be 1.- private static final byte[] CURRENT_MAX_ID = "current_max_id".getBytes();-@VisibleForTesting static final byte[] NAMESPACE_SEPARATOR = "_".getBytes();@VisibleForTesting static final String WILD_CARD = "*";- private final KvBackend backend;-// Key format template. Please the comment of the class for more details.public static final Map<EntityType, String[]> ENTITY_TYPE_TO_NAME_IDENTIFIER =ImmutableMap.of(@@ -78,89 +59,28 @@ public class BinaryEntityKeyEncoder implements EntityKeyEncoder<byte[]> {SCHEMA, new String[] {SCHEMA.getShortName() + "_", "_", "_"},TABLE, new String[] {TABLE.getShortName() + "_", "_", "_", "_"});- private IdGenerator idGenerator;+ @VisibleForTesting final NameMappingService nameMappingService;- public BinaryEntityKeyEncoder(KvBackend backend, IdGenerator idGenerator) {- this.backend = backend;- this.idGenerator = idGenerator;- }-- /**- * Get or create id for name. If the name is not in the storage, create a new id for it. The id is- * the current max id + 1. Matalake and catalog will directly use UUID as id, other entities use- * incremental id- *- * <p>Attention, this method should be called in transaction. What's more, we should also consider- * the concurrency issue. For example, if two threads want to create a new id for the same name,- * the result is not deterministic if we do not use synchronization.- */- @VisibleForTesting- synchronized long getOrCreateId(- String name, boolean isMetalakeOrCatalog, boolean createIdIfNotExists) throws IOException {- byte[] nameByte = Bytes.concat(NAME_PREFIX, name.getBytes());- byte[] idByte = backend.get(nameByte);- if (idByte != null) {- return ByteUtils.byteToLong(idByte);- }-- // Create if not exists- if (!createIdIfNotExists) {- throw new NoSuchEntityException("No such entity with name " + name);- }-- // Now we need to create a new id for the name, So if this is not in transaction, throw an- // Exception- if (!backend.isInTransaction()) {- throw new IOException("getOrCreateId should be called in transaction");- }-- // Matalake and catalog use UUID as id, other entities use incremental id- // According to- // https://stackoverflow.com/questions/325443/likelihood-of-collision-using-most-significant-bits-of-a-uuid-in-java- // UUID.randomUUID().getLeastSignificantBits() is a good choice for id- long id = isMetalakeOrCatalog ? UUID.randomUUID().getLeastSignificantBits() : getNextUsableId();- byte[] maxByte = ByteUtils.longToByte(id);- LOG.info(- "Create new id '{}' for name '{}', isMetalakeOrCatalog '{}'",- id,- name,- isMetalakeOrCatalog);-- // Write current max id to storage, For metalake as it's generated from UUID, No need to store- // it- if (!isMetalakeOrCatalog) {- backend.put(CURRENT_MAX_ID, maxByte, true);- }-- // Write name_metalake1 -> 1- backend.put(nameByte, maxByte, false);-- // Write id_1 ---> metalake1- byte[] idToNameKey = Bytes.concat(ID_PREFIX, maxByte);- byte[] idToNameValue = name.getBytes();- backend.put(idToNameKey, idToNameValue, false);- return id;+ public BinaryEntityKeyEncoder(NameMappingService nameMappingService) {+ this.nameMappingService = nameMappingService;}/*** Encode entity key for KV backend, e.g., RocksDB. The key is used to store the entity in the* backend.*- * @param entityIdentifier the entity identifier to encode+ * @param identifier NameIdentifier of the entity+ * @param entityType the entity identifier to encode* @return the encoded key for key-value storage*/- private byte[] encodeEntity(EntityIdentifier entityIdentifier, boolean createIdIfNotExists)- throws IOException {- EntityType entityType = entityIdentifier.getEntityType();- String[] nameSpace = entityIdentifier.getNameIdentifier().namespace().levels();+ private byte[] encodeEntity(NameIdentifier identifier, EntityType entityType) throws IOException {+ String[] nameSpace = identifier.namespace().levels();long[] namespaceIds = new long[nameSpace.length];for (int i = 0; i < nameSpace.length; i++) {- namespaceIds[i] =- getOrCreateId(nameSpace[i], i <= 1 /* is metalake or catalog */, createIdIfNotExists);+ namespaceIds[i] = nameMappingService.getOrCreateIdFromName(nameSpace[i]);}- NameIdentifier identifier = entityIdentifier.getNameIdentifier();- // If the name is a wild card, we only need to encode the namespace.+ // If the name is a wildcard, We only need to encode the namespace.if (WILD_CARD.equals(identifier.name())) {String[] namespaceTemplate = ENTITY_TYPE_TO_NAME_IDENTIFIER.get(entityType);if (namespaceTemplate == null) {@@ -173,7 +93,7 @@ public class BinaryEntityKeyEncoder implements EntityKeyEncoder<byte[]> {long[] namespaceAndNameIds = new long[namespaceIds.length + 1];System.arraycopy(namespaceIds, 0, namespaceAndNameIds, 0, namespaceIds.length);namespaceAndNameIds[namespaceIds.length] =- getOrCreateId(identifier.name(), namespaceIds.length <= 1, createIdIfNotExists);+ nameMappingService.getOrCreateIdFromName(identifier.name());String[] nameIdentifierTemplate = ENTITY_TYPE_TO_NAME_IDENTIFIER.get(entityType);if (nameIdentifierTemplate == null) {@@ -226,22 +146,15 @@ public class BinaryEntityKeyEncoder implements EntityKeyEncoder<byte[]> {return bytes;}-- @VisibleForTesting- public long getNextUsableId() throws IOException {- byte[] maxByte = backend.get(CURRENT_MAX_ID);- return maxByte == null ? 0 : ByteUtils.byteToLong(maxByte) + 1;- }-/*** Encodes an entity object into a byte array for use as a key in a key-value store.*- * @param entityIdentifier The entity object to be encoded.+ * @param ident NameIdentifier of the entity+ * @param type the entity identifier to encode* @return The byte array representing the encoded key.*/@Override- public byte[] encode(EntityIdentifier entityIdentifier, boolean createIdIfNotExists)- throws IOException {- return encodeEntity(entityIdentifier, createIdIfNotExists);+ public byte[] encode(NameIdentifier ident, EntityType type) throws IOException {+ return encodeEntity(ident, type);}}diff --git a/core/src/main/java/com/datastrato/graviton/storage/kv/KvBackend.java b/core/src/main/java/com/datastrato/graviton/storage/kv/KvBackend.javaindex fc428877c6..a9b7fa1cc3 100644--- a/core/src/main/java/com/datastrato/graviton/storage/kv/KvBackend.java+++ b/core/src/main/java/com/datastrato/graviton/storage/kv/KvBackend.java@@ -76,8 +76,4 @@ public interface KvBackend extends Closeable {*/<R, E extends Exception> R executeInTransaction(Executable<R, E> executable)throws E, IOException;-- default boolean isInTransaction() {- return false;- }}diff --git a/core/src/main/java/com/datastrato/graviton/storage/kv/KvEntityStore.java b/core/src/main/java/com/datastrato/graviton/storage/kv/KvEntityStore.javaindex 76858b72a0..d0b770d656 100644--- a/core/src/main/java/com/datastrato/graviton/storage/kv/KvEntityStore.java+++ b/core/src/main/java/com/datastrato/graviton/storage/kv/KvEntityStore.java@@ -9,7 +9,6 @@ import static com.datastrato.graviton.Configs.ENTITY_KV_STORE;import com.datastrato.graviton.Config;import com.datastrato.graviton.Entity;-import com.datastrato.graviton.Entity.EntityIdentifier;import com.datastrato.graviton.Entity.EntityType;import com.datastrato.graviton.EntityAlreadyExistsException;import com.datastrato.graviton.EntitySerDe;@@ -19,8 +18,7 @@ import com.datastrato.graviton.NameIdentifier;import com.datastrato.graviton.Namespace;import com.datastrato.graviton.exceptions.NoSuchEntityException;import com.datastrato.graviton.storage.EntityKeyEncoder;-import com.datastrato.graviton.storage.IdGenerator;-import com.datastrato.graviton.storage.RandomIdGenerator;+import com.datastrato.graviton.storage.NameMappingService;import com.datastrato.graviton.util.Bytes;import com.datastrato.graviton.util.Executable;import com.google.common.annotations.VisibleForTesting;@@ -46,15 +44,16 @@ public class KvEntityStore implements EntityStore {ImmutableMap.of("RocksDBKvBackend", RocksDBKvBackend.class.getCanonicalName());@Getter @VisibleForTesting private KvBackend backend;- private EntityKeyEncoder entityKeyEncoder;+ private EntityKeyEncoder<byte[]> entityKeyEncoder;private EntitySerDe serDe;@Overridepublic void initialize(Config config) throws RuntimeException {this.backend = createKvEntityBackend(config);- // TODO (yuqi) Make idGenerator configurable- IdGenerator idGenerator = new RandomIdGenerator();- this.entityKeyEncoder = new BinaryEntityKeyEncoder(backend, idGenerator);+ // TODO(yuqi) Currently, KvNameMappingSerivice and KvEntityStore shares the same backend+ // instance, We should make it configurable in the future.+ NameMappingService nameMappingService = new KvNameMappingService(backend);+ this.entityKeyEncoder = new BinaryEntityKeyEncoder(nameMappingService);}@Override@@ -67,7 +66,7 @@ public class KvEntityStore implements EntityStore {Namespace namespace, Class<E> e, EntityType type) throws IOException {// Star means it's a wildcardNameIdentifier identifier = NameIdentifier.of(namespace, "*");- byte[] startKey = entityKeyEncoder.encode(EntityIdentifier.of(identifier, type), false);+ byte[] startKey = entityKeyEncoder.encode(identifier, type);byte[] endKey = Bytes.increment(Bytes.wrap(startKey)).get();List<Pair<byte[], byte[]>> kvs =backend.scan(@@ -89,18 +88,15 @@ public class KvEntityStore implements EntityStore {@Overridepublic boolean exists(NameIdentifier ident, EntityType entityType) throws IOException {- return backend.get(entityKeyEncoder.encode(EntityIdentifier.of(ident, entityType), false))- != null;+ return backend.get(entityKeyEncoder.encode(ident, entityType)) != null;}@Overridepublic <E extends Entity & HasIdentifier> void put(E e, boolean overwritten)throws IOException, EntityAlreadyExistsException {- // Simple implementation, just use the entity's identifier as the keyexecuteInTransaction(() -> {- byte[] key =- entityKeyEncoder.encode(EntityIdentifier.of(e.nameIdentifier(), e.type()), true);+ byte[] key = entityKeyEncoder.encode(e.nameIdentifier(), e.type());byte[] value = serDe.serialize(e);backend.put(key, value, overwritten);return null;@@ -113,7 +109,7 @@ public class KvEntityStore implements EntityStore {throws IOException, NoSuchEntityException {return executeInTransaction(() -> {- byte[] key = entityKeyEncoder.encode(EntityIdentifier.of(ident, entityType), false);+ byte[] key = entityKeyEncoder.encode(ident, entityType);byte[] value = backend.get(key);if (value == null) {throw new NoSuchEntityException(ident.toString());@@ -134,8 +130,7 @@ 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(EntityIdentifier.of(ident, entityType), false);- // refer type from key;+ byte[] key = entityKeyEncoder.encode(ident, entityType);byte[] value = backend.get(key);if (value == null) {throw new NoSuchEntityException(ident.toString());@@ -145,7 +140,7 @@ public class KvEntityStore implements EntityStore {@Overridepublic boolean delete(NameIdentifier ident, EntityType entityType) throws IOException {- return backend.delete(entityKeyEncoder.encode(EntityIdentifier.of(ident, entityType), false));+ return backend.delete(entityKeyEncoder.encode(ident, entityType));}@Overridediff --git a/core/src/main/java/com/datastrato/graviton/storage/kv/KvNameMappingService.java b/core/src/main/java/com/datastrato/graviton/storage/kv/KvNameMappingService.javaindex fb82d55c02..c877f2c63b 100644--- a/core/src/main/java/com/datastrato/graviton/storage/kv/KvNameMappingService.java+++ b/core/src/main/java/com/datastrato/graviton/storage/kv/KvNameMappingService.java@@ -5,7 +5,9 @@package com.datastrato.graviton.storage.kv;+import com.datastrato.graviton.storage.IdGenerator;import com.datastrato.graviton.storage.NameMappingService;+import com.datastrato.graviton.storage.RandomIdGenerator;import com.datastrato.graviton.util.ByteUtils;import com.datastrato.graviton.util.Bytes;import com.google.common.annotations.VisibleForTesting;@@ -23,6 +25,7 @@ public class KvNameMappingService implements NameMappingService {// TODO(yuqi) Make this configurable@VisibleForTesting final KvBackend backend;private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();+ @VisibleForTesting final IdGenerator idGenerator = new RandomIdGenerator();// name prefix of name in name to id mapping,// e.g., name_metalake1 -> 1@@ -50,18 +53,17 @@ public class KvNameMappingService implements NameMappingService {}}- @Override- public void bindNameAndId(String name, long id) throws IOException {+ private long bindNameAndId(String name) throws IOException {byte[] nameByte = Bytes.concat(NAME_PREFIX, name.getBytes());-+ long id = idGenerator.nextId();lock.writeLock().lock();try {- backend.executeInTransaction(+ return backend.executeInTransaction(() -> {backend.put(nameByte, ByteUtils.longToByte(id), false);byte[] idByte = Bytes.concat(ID_PREFIX, ByteUtils.longToByte(id));backend.put(idByte, name.getBytes(), false);- return null;+ return id;});} finally {lock.writeLock().unlock();@@ -109,4 +111,18 @@ public class KvNameMappingService implements NameMappingService {public void close() throws Exception {backend.close();}++ @Override+ public long getOrCreateIdFromName(String name) throws IOException {+ Long id = getIdByName(name);+ if (id == null) {+ synchronized (this) {+ if ((id = getIdByName(name)) == null) {+ id = bindNameAndId(name);+ }+ }+ }++ return id;+ }}diff --git a/core/src/main/java/com/datastrato/graviton/storage/kv/RocksDBKvBackend.java b/core/src/main/java/com/datastrato/graviton/storage/kv/RocksDBKvBackend.javaindex 76a98047ff..393a4373e2 100644--- a/core/src/main/java/com/datastrato/graviton/storage/kv/RocksDBKvBackend.java+++ b/core/src/main/java/com/datastrato/graviton/storage/kv/RocksDBKvBackend.java@@ -247,12 +247,4 @@ public class RocksDBKvBackend implements KvBackend {Throwables.getStackTraceAsString(e));}}-- @Override- public boolean isInTransaction() {- // TODO (yuqi), check if the transaction is still valid and We do not allow transaction nesting- // That is, A transaction can not be started inside another transaction when outer transaction- // is still active- return TX_LOCAL.get() != null;- }}diff --git a/core/src/main/java/com/datastrato/graviton/util/ByteUtils.java b/core/src/main/java/com/datastrato/graviton/util/ByteUtils.javaindex a0afcc8bda..a4fb41fa6e 100644--- a/core/src/main/java/com/datastrato/graviton/util/ByteUtils.java+++ b/core/src/main/java/com/datastrato/graviton/util/ByteUtils.java@@ -65,6 +65,13 @@ public class ByteUtils {return buffer.getLong();}+ /**+ * Format a byte array to a human-readable string. For example, if the byte array is [0x00, 0x01,+ * 0x02, 0x03], the result is '0x00010203'+ *+ * @param bytes Bytes to be formatted+ * @return A human-readable string+ */public static String formatByteArray(byte[] bytes) {StringBuilder sb = new StringBuilder("0x");for (byte b : bytes) {diff --git a/core/src/test/java/com/datastrato/graviton/storage/kv/TestEntityKeyEncoding.java b/core/src/test/java/com/datastrato/graviton/storage/kv/TestEntityKeyEncoding.javaindex a9631c3d24..2d70434c8e 100644--- a/core/src/test/java/com/datastrato/graviton/storage/kv/TestEntityKeyEncoding.java+++ b/core/src/test/java/com/datastrato/graviton/storage/kv/TestEntityKeyEncoding.java@@ -14,14 +14,14 @@ import static com.datastrato.graviton.storage.kv.BinaryEntityKeyEncoder.WILD_CARimport com.datastrato.graviton.Config;import com.datastrato.graviton.Configs;-import com.datastrato.graviton.Entity.EntityIdentifier;import com.datastrato.graviton.Entity.EntityType;import com.datastrato.graviton.EntitySerDeFactory;import com.datastrato.graviton.EntityStore;import com.datastrato.graviton.EntityStoreFactory;import com.datastrato.graviton.NameIdentifier;import com.datastrato.graviton.Namespace;-import com.datastrato.graviton.storage.RandomIdGenerator;+import com.datastrato.graviton.storage.IdGenerator;+import com.datastrato.graviton.storage.NameMappingService;import com.datastrato.graviton.util.ByteUtils;import com.datastrato.graviton.util.Bytes;import java.io.IOException;@@ -55,9 +55,22 @@ public class TestEntityKeyEncoding {ENTITY_STORE_INSTANCE.initialize(config);ENTITY_STORE_INSTANCE.setSerDe(EntitySerDeFactory.createEntitySerDe(config.get(Configs.ENTITY_SERDE)));- ENCODER =- new BinaryEntityKeyEncoder(- ((KvEntityStore) ENTITY_STORE_INSTANCE).getBackend(), new RandomIdGenerator());+ NameMappingService nameMappingService =+ new KvNameMappingService(((KvEntityStore) ENTITY_STORE_INSTANCE).getBackend());+ ENCODER = new BinaryEntityKeyEncoder(nameMappingService);+ }++ private IdGenerator getIdGeneratorAndSpy(BinaryEntityKeyEncoder entityKeyEncoder)+ throws IllegalAccessException, NoSuchFieldException {+ KvNameMappingService nameMappingService =+ (KvNameMappingService) entityKeyEncoder.nameMappingService;++ Field field = nameMappingService.getClass().getDeclaredField("idGenerator");+ field.setAccessible(true);+ IdGenerator idGenerator = (IdGenerator) field.get(nameMappingService);+ IdGenerator spyIdGenerator = Mockito.spy(idGenerator);+ field.set(nameMappingService, spyIdGenerator);+ return spyIdGenerator;}@AfterEach@@ -88,45 +101,24 @@ public class TestEntityKeyEncoding {public void testIdentifierEncoding()throws IOException, IllegalAccessException, NoSuchFieldException {// Metalake- // metalake1 --> 1000000+ // metalake1 --> 0Namespace namespace = Namespace.of();- BinaryEntityKeyEncoder mockEncoder = Mockito.spy(ENCODER);- Field f = BinaryEntityKeyEncoder.class.getDeclaredField("backend");- f.setAccessible(true);- KvBackend backend = (KvBackend) f.get(mockEncoder);-- KvBackend mockBackend = Mockito.spy(backend);- Mockito.doReturn(true).when(mockBackend).isInTransaction();- f.set(mockEncoder, mockBackend);-- Mockito.doReturn(1000000L)- .when(mockEncoder)- .getOrCreateId(Mockito.eq("metalake1"), Mockito.eq(true), Mockito.eq(true));-- Mockito.doReturn(1000010L)- .when(mockEncoder)- .getOrCreateId(Mockito.eq("catalog1"), Mockito.eq(true), Mockito.eq(true));- Mockito.doReturn(1000011L)- .when(mockEncoder)- .getOrCreateId(Mockito.eq("catalog2"), Mockito.eq(true), Mockito.eq(true));- Mockito.doReturn(1000012L)- .when(mockEncoder)- .getOrCreateId(Mockito.eq("catalog3"), Mockito.eq(true), Mockito.eq(true));+ IdGenerator mockIdGenerator = getIdGeneratorAndSpy(ENCODER);+ Mockito.doReturn(0L).when(mockIdGenerator).nextId();NameIdentifier mateLakeIdentifier1 = NameIdentifier.of(namespace, "metalake1");- byte[] realKey =- mockEncoder.encode(EntityIdentifier.of(mateLakeIdentifier1, EntityType.METALAKE), true);+ byte[] realKey = ENCODER.encode(mateLakeIdentifier1, EntityType.METALAKE);byte[] expenctKey =Bytes.concat(EntityType.METALAKE.getShortName().getBytes(),NAMESPACE_SEPARATOR,- ByteUtils.longToByte(1000000L));+ ByteUtils.longToByte(0L));Assertions.assertArrayEquals(expenctKey, realKey);// name ---> id- // catalog1 --> 1000010- // catalog2 --> 1000011- // catalog3 --> 1000012+ // catalog1 --> 1+ // catalog2 --> 2+ // catalog3 --> 3Namespace catalogNamespace = Namespace.of("metalake1");NameIdentifier catalogIdentifier1 = NameIdentifier.of(catalogNamespace, "catalog1");NameIdentifier catalogIdentifier2 = NameIdentifier.of(catalogNamespace, "catalog2");@@ -135,24 +127,23 @@ public class TestEntityKeyEncoding {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 = mockEncoder.encode(EntityIdentifier.of(identifier, EntityType.CATALOG), true);+ realKey = ENCODER.encode(identifier, EntityType.CATALOG);expenctKey =Bytes.concat(EntityType.CATALOG.getShortName().getBytes(),NAMESPACE_SEPARATOR,- ByteUtils.longToByte(1000000L),+ ByteUtils.longToByte(0L),NAMESPACE_SEPARATOR,- ByteUtils.longToByte(1000010L + i));+ ByteUtils.longToByte(1L + i));Assertions.assertArrayEquals(expenctKey, realKey);}- // Assert next useable id- Assertions.assertEquals(0, ENCODER.getNextUsableId());// name ---> id- // schema1 --> 0- // schema2 --> 1- // schema3 --> 2+ // schema1 --> 4+ // schema2 --> 5+ // schema3 --> 6Namespace schemaNameSpace = Namespace.of("metalake1", "catalog2");NameIdentifier schemaIdentifier1 = NameIdentifier.of(schemaNameSpace, "schema1");NameIdentifier schemaIdentifier2 = NameIdentifier.of(schemaNameSpace, "schema2");@@ -162,25 +153,24 @@ public class TestEntityKeyEncoding {for (int i = 0; i < schemaIdentifiers.length; i++) {NameIdentifier identifier = schemaIdentifiers[i];- realKey = mockEncoder.encode(EntityIdentifier.of(identifier, EntityType.SCHEMA), true);+ Mockito.doReturn(4L + i).when(mockIdGenerator).nextId();+ realKey = ENCODER.encode(identifier, EntityType.SCHEMA);expenctKey =Bytes.concat(EntityType.SCHEMA.getShortName().getBytes(),NAMESPACE_SEPARATOR,- ByteUtils.longToByte(1000000L),+ ByteUtils.longToByte(0L),NAMESPACE_SEPARATOR,- ByteUtils.longToByte(1000011L),+ ByteUtils.longToByte(2L),NAMESPACE_SEPARATOR,- ByteUtils.longToByte(i));+ ByteUtils.longToByte(4L + i));Assertions.assertArrayEquals(expenctKey, realKey);}- // Assert next useable id- Assertions.assertEquals(3, ENCODER.getNextUsableId());// name ---> id- // table1 --> 3- // table2 --> 4- // table3 --> 5+ // table1 --> 7+ // table2 --> 8+ // table3 --> 9Namespace tableNameSpace = Namespace.of("metalake1", "catalog2", "schema3");NameIdentifier tableIdentifier1 = NameIdentifier.of(tableNameSpace, "table1");NameIdentifier tableIdentifier2 = NameIdentifier.of(tableNameSpace, "table2");@@ -190,145 +180,103 @@ public class TestEntityKeyEncoding {for (int i = 0; i < tableIdentifiers.length; i++) {NameIdentifier identifier = tableIdentifiers[i];- realKey = mockEncoder.encode(EntityIdentifier.of(identifier, EntityType.TABLE), true);+ Mockito.doReturn(7L + i).when(mockIdGenerator).nextId();+ realKey = ENCODER.encode(identifier, EntityType.TABLE);expenctKey =Bytes.concat(EntityType.TABLE.getShortName().getBytes(),NAMESPACE_SEPARATOR,- ByteUtils.longToByte(1000000L),- NAMESPACE_SEPARATOR,- ByteUtils.longToByte(1000011L),+ ByteUtils.longToByte(0L),NAMESPACE_SEPARATOR,ByteUtils.longToByte(2L),NAMESPACE_SEPARATOR,- ByteUtils.longToByte(i + 3L));+ ByteUtils.longToByte(6L),+ NAMESPACE_SEPARATOR,+ ByteUtils.longToByte(i + 7L));Assertions.assertArrayEquals(expenctKey, realKey);}- // Assert next useable id- Assertions.assertEquals(6, ENCODER.getNextUsableId());// Unsupported operation+ Mockito.doReturn(10L).when(mockIdGenerator).nextId();Assertions.assertThrows(UnsupportedOperationException.class,() -> {- mockEncoder.encode(- EntityIdentifier.of(- NameIdentifier.of(- Namespace.of("metalake1", "catalog2", "schema3", "table1"), "column1"),- EntityType.COLUMN),- true);+ ENCODER.encode(+ NameIdentifier.of(+ Namespace.of("metalake1", "catalog2", "schema3", "table1"), "column1"),+ EntityType.COLUMN);});}- @Test- public void testTransaction() throws IOException {- Namespace namespace = Namespace.of();- BinaryEntityKeyEncoder mockEncoder = Mockito.spy(ENCODER);-- Mockito.doReturn(1000000L)- .when(mockEncoder)- .getOrCreateId(Mockito.eq("metalake1"), Mockito.eq(true), Mockito.eq(false));-- NameIdentifier mateLakeIdentifier1 = NameIdentifier.of(namespace, "metalake1");- Assertions.assertThrows(- IOException.class,- () ->- mockEncoder.encode(- EntityIdentifier.of(mateLakeIdentifier1, EntityType.METALAKE), true));- }-@Test@Order(10)public void testNamespaceEncoding()throws IOException, IllegalAccessException, NoSuchFieldException {// Scan all MetalakeNamespace namespace = Namespace.of();- BinaryEntityKeyEncoder mockEncoder = Mockito.spy(ENCODER);-- Field f = BinaryEntityKeyEncoder.class.getDeclaredField("backend");- f.setAccessible(true);- KvBackend backend = (KvBackend) f.get(mockEncoder);-- KvBackend mockBackend = Mockito.spy(backend);- Mockito.doReturn(true).when(mockBackend).isInTransaction();- f.set(mockEncoder, mockBackend);-- Mockito.doReturn(1000000L)- .when(mockEncoder)- .getOrCreateId(Mockito.eq("metalake1"), Mockito.eq(true), Mockito.eq(true));-- Mockito.doReturn(1000001L)- .when(mockEncoder)- .getOrCreateId(Mockito.eq("catalog2"), Mockito.eq(true), Mockito.eq(true));+ IdGenerator mockIdGenerator = getIdGeneratorAndSpy(ENCODER);NameIdentifier metalakeIdentifier = NameIdentifier.of(namespace, WILD_CARD);- byte[] realKey =- mockEncoder.encode(EntityIdentifier.of(metalakeIdentifier, EntityType.METALAKE), true);+ byte[] realKey = ENCODER.encode(metalakeIdentifier, EntityType.METALAKE);byte[] expenctKey =Bytes.concat(EntityType.METALAKE.getShortName().getBytes(), NAMESPACE_SEPARATOR);Assertions.assertArrayEquals(expenctKey, realKey);// Scan all catalog in metalake1- // metalake1 --> 1000000L+ // metalake1 --> 0L+ Mockito.doReturn(0L).when(mockIdGenerator).nextId();Namespace catalogNamespace = Namespace.of("metalake1");NameIdentifier catalogIdentifier = NameIdentifier.of(catalogNamespace, WILD_CARD);- realKey = mockEncoder.encode(EntityIdentifier.of(catalogIdentifier, EntityType.CATALOG), true);+ realKey = ENCODER.encode(catalogIdentifier, EntityType.CATALOG);expenctKey =Bytes.concat(EntityType.CATALOG.getShortName().getBytes(),NAMESPACE_SEPARATOR,- ByteUtils.longToByte(1000000L),+ ByteUtils.longToByte(0L),NAMESPACE_SEPARATOR);Assertions.assertArrayEquals(expenctKey, realKey);- // Assert next useable id- Assertions.assertEquals(0, ENCODER.getNextUsableId());// Scan all sc in metalake1.catalog2- // catalog2 --> 0+ // catalog2 --> 1+ Mockito.doReturn(1L).when(mockIdGenerator).nextId();Namespace schemaNameSpace = Namespace.of("metalake1", "catalog2");NameIdentifier schemaIdentifier = NameIdentifier.of(schemaNameSpace, WILD_CARD);- realKey = mockEncoder.encode(EntityIdentifier.of(schemaIdentifier, EntityType.SCHEMA), true);+ realKey = ENCODER.encode(schemaIdentifier, EntityType.SCHEMA);expenctKey =Bytes.concat(EntityType.SCHEMA.getShortName().getBytes(),NAMESPACE_SEPARATOR,- ByteUtils.longToByte(1000000L),+ ByteUtils.longToByte(0L),NAMESPACE_SEPARATOR,- ByteUtils.longToByte(1000001L),+ ByteUtils.longToByte(1L),NAMESPACE_SEPARATOR);Assertions.assertArrayEquals(expenctKey, realKey);- // Assert next useable id- Assertions.assertEquals(0, ENCODER.getNextUsableId());// Scan all table in metalake1.catalog2.schema3- // schema3 --> 1+ // schema3 --> 2+ Mockito.doReturn(2L).when(mockIdGenerator).nextId();Namespace tableNameSpace = Namespace.of("metalake1", "catalog2", "schema3");NameIdentifier tableIdentifier = NameIdentifier.of(tableNameSpace, WILD_CARD);- realKey = mockEncoder.encode(EntityIdentifier.of(tableIdentifier, EntityType.TABLE), true);+ realKey = ENCODER.encode(tableIdentifier, EntityType.TABLE);expenctKey =Bytes.concat(EntityType.TABLE.getShortName().getBytes(),NAMESPACE_SEPARATOR,- ByteUtils.longToByte(1000000L),+ ByteUtils.longToByte(0L),NAMESPACE_SEPARATOR,- ByteUtils.longToByte(1000001L),+ ByteUtils.longToByte(1L),NAMESPACE_SEPARATOR,- ByteUtils.longToByte(0L),+ ByteUtils.longToByte(2L),NAMESPACE_SEPARATOR);Assertions.assertArrayEquals(expenctKey, realKey);- // Assert next useable id- Assertions.assertEquals(1, ENCODER.getNextUsableId());- // Unsupported operation+ Mockito.doReturn(3L).when(mockIdGenerator).nextId();Assertions.assertThrows(UnsupportedOperationException.class,- () -> {- mockEncoder.encode(- EntityIdentifier.of(- NameIdentifier.of(- Namespace.of("metalake1", "catalog2", "schema3", "table1"), WILD_CARD),- EntityType.COLUMN),- true);- });+ () ->+ ENCODER.encode(+ NameIdentifier.of(+ Namespace.of("metalake1", "catalog2", "schema3", "table1"), WILD_CARD),+ EntityType.COLUMN));}}diff --git a/core/src/test/java/com/datastrato/graviton/storage/kv/TestKvNameMappingService.java b/core/src/test/java/com/datastrato/graviton/storage/kv/TestKvNameMappingService.javaindex e46acb86d3..e910cdc28e 100644--- a/core/src/test/java/com/datastrato/graviton/storage/kv/TestKvNameMappingService.java+++ b/core/src/test/java/com/datastrato/graviton/storage/kv/TestKvNameMappingService.java@@ -16,6 +16,7 @@ import com.datastrato.graviton.storage.IdGenerator;import com.datastrato.graviton.storage.NameMappingService;import com.datastrato.graviton.storage.RandomIdGenerator;import java.io.IOException;+import java.lang.reflect.Field;import org.apache.commons.io.FileUtils;import org.junit.jupiter.api.Assertions;import org.junit.jupiter.api.BeforeEach;@@ -29,7 +30,7 @@ import org.mockito.Mockito;public class TestKvNameMappingService {public static final String ROCKS_DB_STORE_PATH = "/tmp/graviton_name_mapping";- private IdGenerator idGenerator = new RandomIdGenerator();+ private final IdGenerator idGenerator = new RandomIdGenerator();@BeforeEachpublic void cleanEnv() {@@ -52,21 +53,33 @@ public class TestKvNameMappingService {return new KvNameMappingService(backend);}+ private IdGenerator getIdGeneratorByRefection(NameMappingService nameMappingService)+ throws Exception {+ Field field = nameMappingService.getClass().getDeclaredField("idGenerator");+ field.setAccessible(true);+ IdGenerator idGenerator = (IdGenerator) field.get(nameMappingService);+ IdGenerator spyIdGenerator = Mockito.spy(idGenerator);+ field.set(nameMappingService, spyIdGenerator);+ return spyIdGenerator;+ }+@Test@Order(1)public void testGetIdByName() throws Exception {- IdGenerator idGenerator = new RandomIdGenerator();try (NameMappingService nameMappingService =createNameMappingService(ROCKS_DB_STORE_PATH + "/1")) {Assertions.assertNull(nameMappingService.getIdByName("name1"));- long name1Id = idGenerator.nextId();- nameMappingService.bindNameAndId("name1", name1Id);++ IdGenerator spyIdGenerator = getIdGeneratorByRefection(nameMappingService);+ Mockito.doReturn(1L).when(spyIdGenerator).nextId();++ long name1Id = nameMappingService.getOrCreateIdFromName("name1");Long name1IdRead = nameMappingService.getIdByName("name1");Assertions.assertEquals(name1Id, name1IdRead);Assertions.assertNull(nameMappingService.getIdByName("name2"));- long name2Id = idGenerator.nextId();- nameMappingService.bindNameAndId("name2", name2Id);+ Mockito.doReturn(2L).when(spyIdGenerator).nextId();+ long name2Id = nameMappingService.getOrCreateIdFromName("name2");Long name2IdRead = nameMappingService.getIdByName("name2");Assertions.assertEquals(name2Id, name2IdRead);}@@ -75,22 +88,23 @@ public class TestKvNameMappingService {@Test@Order(2)public void testUpdateName() throws Exception {- long name1Id = idGenerator.nextId();try (NameMappingService nameMappingService =createNameMappingService(ROCKS_DB_STORE_PATH + "/2")) {- nameMappingService.bindNameAndId("name1", name1Id);+ IdGenerator idGenerator = getIdGeneratorByRefection(nameMappingService);+ Mockito.doReturn(1L).when(idGenerator).nextId();+ long name1IdRead = nameMappingService.getOrCreateIdFromName("name1");Assertions.assertNotNull(nameMappingService.getIdByName("name1"));- long name2Id = idGenerator.nextId();- nameMappingService.bindNameAndId("name2", name2Id);+ Mockito.doReturn(2L).when(idGenerator).nextId();+ long name2IdRead = nameMappingService.getOrCreateIdFromName("name2");Assertions.assertNotNull(nameMappingService.getIdByName("name1"));- Assertions.assertNotEquals(name1Id, name2Id);+ Assertions.assertNotEquals(name1IdRead, name2IdRead);boolean result = nameMappingService.updateName("name1", "name3");Assertions.assertTrue(result);Long name3Id = nameMappingService.getIdByName("name3");- Assertions.assertEquals(name1Id, name3Id);+ Assertions.assertEquals(name1IdRead, name3Id);Assertions.assertNull(nameMappingService.getIdByName("name1"));Assertions.assertFalse(nameMappingService.updateName("name1", "name4"));@@ -99,18 +113,21 @@ public class TestKvNameMappingService {@Test@Order(3)- public void testBindAndUnBind() throws IOException {- long name1Id = idGenerator.nextId();+ public void testBindAndUnBind() throws Exception {+ idGenerator.nextId();NameMappingService nameMappingService = createNameMappingService(ROCKS_DB_STORE_PATH + "/3");- nameMappingService.bindNameAndId("name1", name1Id);+ 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"));- long name2Id = idGenerator.nextId();- nameMappingService.bindNameAndId("name2", name2Id);+ 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());