World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#120] feat(core): Implement key encoding of entity for key-value store (#160)
Qi Yueb5a2c5e89f7
diff --git a/core/src/main/java/com/datastrato/graviton/Entity.java b/core/src/main/java/com/datastrato/graviton/Entity.javaindex edfe8296c5..3ed005ff20 100644--- a/core/src/main/java/com/datastrato/graviton/Entity.java+++ b/core/src/main/java/com/datastrato/graviton/Entity.java@@ -6,16 +6,20 @@ package com.datastrato.graviton;import java.io.Serializable;import java.util.Map;+import lombok.AllArgsConstructor;+import lombok.Getter;+import lombok.ToString;public interface Entity extends Serializable {+ @Getterenum EntityType {METALAKE("ml", 0),CATALOG("ca", 1),SCHEMA("sc", 2),- TABLE("tb", 3),+ TABLE("ta", 3),COLUMN("co", 4),- AUDIT("au", 9999999);+ AUDIT("au", 65534);// Short name can be used to identify the entity type in the logs, peristent storage, etc.private final String shortName;@@ -27,6 +31,18 @@ public interface Entity extends Serializable {}}+ @Getter+ @AllArgsConstructor+ @ToString+ class EntityIdentifer {+ private NameIdentifier nameIdentifier;+ private EntityType entityType;++ public static EntityIdentifer of(NameIdentifier name, EntityType entityType) {+ return new EntityIdentifer(name, entityType);+ }+ }+/*** Validates the entity if the field arguments are valid.*diff --git a/core/src/main/java/com/datastrato/graviton/EntityStore.java b/core/src/main/java/com/datastrato/graviton/EntityStore.javaindex 9bee660b3a..44c7bb9a84 100644--- a/core/src/main/java/com/datastrato/graviton/EntityStore.java+++ b/core/src/main/java/com/datastrato/graviton/EntityStore.java@@ -4,6 +4,7 @@*/package com.datastrato.graviton;+import com.datastrato.graviton.Entity.EntityType;import com.datastrato.graviton.util.Executable;import java.io.Closeable;import java.io.IOException;@@ -43,8 +44,8 @@ public interface EntityStore extends Closeable {* @param type the type of the entity* @throws IOException if the list operation fails*/- <E extends Entity & HasIdentifier> List<E> list(Namespace namespace, Class<E> type)- throws IOException;+ <E extends Entity & HasIdentifier> List<E> list(+ Namespace namespace, Class<E> type, EntityType entityType) throws IOException;/*** Check if the entity with the specified {@link NameIdentifier} exists.@@ -53,20 +54,18 @@ public interface EntityStore extends Closeable {* @return true if the entity exists, false otherwise* @throws IOException if the check operation fails*/- boolean exists(NameIdentifier ident) throws IOException;+ boolean exists(NameIdentifier ident, EntityType entityType) throws IOException;/*** Store the entity into the underlying storage. If the entity already exists, it will overwrite* the existing entity.*- * @param ident the unique identifier of the entity* @param e the entity to store* @param <E> the type of the entity* @throws IOException if the store operation fails*/- default <E extends Entity & HasIdentifier> void put(NameIdentifier ident, E e)- throws IOException {- put(ident, e, false);+ default <E extends Entity & HasIdentifier> void put(E e) throws IOException {+ put(e, false);}/**@@ -76,7 +75,6 @@ public interface EntityStore extends Closeable {* <p>Note. The implementation should be transactional, and should be able to handle concurrent* store of entities.*- * @param ident the unique identifier of the entity* @param e the entity to store* @param overwritten whether to overwrite the existing entity* @param <E> the type of the entity@@ -84,7 +82,7 @@ public interface EntityStore extends Closeable {* @throws EntityAlreadyExistsException if the entity already exists and the overwritten flag is* set to false*/- <E extends Entity & HasIdentifier> void put(NameIdentifier ident, E e, boolean overwritten)+ <E extends Entity & HasIdentifier> void put(E e, boolean overwritten)throws IOException, EntityAlreadyExistsException;/**@@ -108,7 +106,7 @@ public interface EntityStore extends Closeable {* @throws NoSuchEntityException if the entity does not exist*/<E extends Entity & HasIdentifier> E update(- NameIdentifier ident, Class<E> type, Function<E, E> updater)+ NameIdentifier ident, Class<E> type, EntityType entityType, Function<E, E> updater)throws IOException, NoSuchEntityException;/**@@ -119,11 +117,10 @@ public interface EntityStore extends Closeable {** @param ident the unique identifier of the entity* @return the entity retrieved from the underlying storage- * @param type the type of the entity* @throws NoSuchEntityException if the entity does not exist* @throws IOException if the retrieve operation fails*/- <E extends Entity & HasIdentifier> E get(NameIdentifier ident, Class<E> type)+ <E extends Entity & HasIdentifier> E get(NameIdentifier ident, EntityType entityType, Class<E> e)throws NoSuchEntityException, IOException;/**@@ -133,7 +130,7 @@ public interface EntityStore extends Closeable {* @return true if the entity is deleted, false otherwise* @throws IOException if the delete operation fails*/- boolean delete(NameIdentifier ident) throws IOException;+ boolean delete(NameIdentifier ident, EntityType entityType) throws IOException;/*** Execute the specified {@link Executable} in a transaction.diff --git a/core/src/main/java/com/datastrato/graviton/catalog/CatalogManager.java b/core/src/main/java/com/datastrato/graviton/catalog/CatalogManager.javaindex 393c2412ff..5b062480ef 100644--- a/core/src/main/java/com/datastrato/graviton/catalog/CatalogManager.java+++ b/core/src/main/java/com/datastrato/graviton/catalog/CatalogManager.java@@ -9,6 +9,7 @@ import com.datastrato.graviton.CatalogChange;import com.datastrato.graviton.CatalogProvider;import com.datastrato.graviton.Config;import com.datastrato.graviton.Configs;+import com.datastrato.graviton.Entity.EntityType;import com.datastrato.graviton.EntityAlreadyExistsException;import com.datastrato.graviton.EntityStore;import com.datastrato.graviton.NameIdentifier;@@ -150,7 +151,7 @@ public class CatalogManager implements SupportsCatalogs, Closeable {boolean metalakeExists;try {- metalakeExists = store.exists(metalakeIdent);+ metalakeExists = store.exists(metalakeIdent, EntityType.CATALOG);} catch (IOException e) {LOG.error("Failed to do storage operation", e);throw new RuntimeException(e);@@ -161,7 +162,7 @@ public class CatalogManager implements SupportsCatalogs, Closeable {}try {- return store.list(namespace, CatalogEntity.class).stream()+ return store.list(namespace, CatalogEntity.class, EntityType.METALAKE).stream().map(entity -> NameIdentifier.of(namespace, entity.name())).toArray(NameIdentifier[]::new);@@ -185,7 +186,8 @@ public class CatalogManager implements SupportsCatalogs, Closeable {store.executeInTransaction(() -> {NameIdentifier metalakeIdent = NameIdentifier.of(ident.namespace().levels());- BaseMetalake metalake = store.get(metalakeIdent, BaseMetalake.class);+ BaseMetalake metalake =+ store.get(metalakeIdent, EntityType.METALAKE, BaseMetalake.class);CatalogEntity e =new CatalogEntity.Builder()@@ -203,7 +205,7 @@ public class CatalogManager implements SupportsCatalogs, Closeable {.build()).build();- store.put(ident, e, false /* overwrite */);+ store.put(e, false /* overwrite */);return e;});return catalogCache.get(ident, id -> createCatalogWrapper(entity)).catalog;@@ -234,6 +236,7 @@ public class CatalogManager implements SupportsCatalogs, Closeable {store.update(ident,CatalogEntity.class,+ EntityType.CATALOG,catalog -> {CatalogEntity.Builder newCatalogBuilder =new CatalogEntity.Builder()@@ -286,7 +289,7 @@ public class CatalogManager implements SupportsCatalogs, Closeable {catalogCache.invalidate(ident);try {- return store.delete(ident);+ return store.delete(ident, EntityType.CATALOG);} catch (IOException ioe) {LOG.error("Failed to drop catalog {}", ident, ioe);throw new RuntimeException(ioe);@@ -299,7 +302,7 @@ public class CatalogManager implements SupportsCatalogs, Closeable {private CatalogWrapper loadCatalogInternal(NameIdentifier ident) throws NoSuchCatalogException {try {- CatalogEntity entity = store.get(ident, CatalogEntity.class);+ CatalogEntity entity = store.get(ident, EntityType.CATALOG, CatalogEntity.class);return createCatalogWrapper(entity);} catch (NoSuchEntityException ne) {diff --git a/core/src/main/java/com/datastrato/graviton/meta/MetalakeManager.java b/core/src/main/java/com/datastrato/graviton/meta/MetalakeManager.javaindex 7948dc8caa..a61d5b86ae 100644--- a/core/src/main/java/com/datastrato/graviton/meta/MetalakeManager.java+++ b/core/src/main/java/com/datastrato/graviton/meta/MetalakeManager.java@@ -4,6 +4,7 @@*/package com.datastrato.graviton.meta;+import com.datastrato.graviton.Entity.EntityType;import com.datastrato.graviton.EntityAlreadyExistsException;import com.datastrato.graviton.EntityStore;import com.datastrato.graviton.MetalakeChange;@@ -33,7 +34,9 @@ public class MetalakeManager implements SupportsMetalakes {@Overridepublic BaseMetalake[] listMetalakes() {try {- return store.list(Namespace.empty(), BaseMetalake.class).toArray(new BaseMetalake[0]);+ return store+ .list(Namespace.empty(), BaseMetalake.class, EntityType.METALAKE)+ .toArray(new BaseMetalake[0]);} catch (IOException ioe) {LOG.error("Failed to list metalakes due to storage issues", ioe);throw new RuntimeException(ioe);@@ -43,7 +46,7 @@ public class MetalakeManager implements SupportsMetalakes {@Overridepublic BaseMetalake loadMetalake(NameIdentifier ident) throws NoSuchMetalakeException {try {- return store.get(ident, BaseMetalake.class);+ return store.get(ident, EntityType.METALAKE, BaseMetalake.class);} catch (NoSuchEntityException e) {LOG.warn("Metalake {} does not exist", ident, e);throw new NoSuchMetalakeException("Metalake " + ident + " does not exist");@@ -72,9 +75,8 @@ public class MetalakeManager implements SupportsMetalakes {.build();try {- store.put(ident, metalake, false /* overwritten */);+ store.put(metalake, false /* overwritten */);return metalake;-} catch (EntityAlreadyExistsException e) {LOG.warn("Metalake {} already exists", ident, e);throw new MetalakeAlreadyExistsException("Metalake " + ident + " already exists");@@ -91,6 +93,7 @@ public class MetalakeManager implements SupportsMetalakes {return store.update(ident,BaseMetalake.class,+ EntityType.METALAKE,metalake -> {BaseMetalake.Builder builder =new BaseMetalake.Builder()@@ -136,7 +139,7 @@ public class MetalakeManager implements SupportsMetalakes {@Overridepublic boolean dropMetalake(NameIdentifier ident) {try {- return store.delete(ident);+ return store.delete(ident, EntityType.METALAKE);} catch (IOException ioe) {LOG.error("Failed to delete metalake {} due to storage issues", ident, ioe);throw new RuntimeException(ioe);diff --git a/core/src/main/java/com/datastrato/graviton/storage/kv/CustomEntityKeyEncoder.java b/core/src/main/java/com/datastrato/graviton/storage/kv/CustomEntityKeyEncoder.javaindex c64c07398e..a74abecb15 100644--- a/core/src/main/java/com/datastrato/graviton/storage/kv/CustomEntityKeyEncoder.java+++ b/core/src/main/java/com/datastrato/graviton/storage/kv/CustomEntityKeyEncoder.java@@ -4,23 +4,233 @@*/package com.datastrato.graviton.storage.kv;+import static com.datastrato.graviton.Entity.EntityType.CATALOG;+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.EntityIdentifer;+import com.datastrato.graviton.Entity.EntityType;import com.datastrato.graviton.NameIdentifier;-import com.datastrato.graviton.Namespace;+import com.datastrato.graviton.NoSuchEntityException;+import com.datastrato.graviton.util.ByteUtils;+import com.datastrato.graviton.util.Bytes;+import com.google.common.annotations.VisibleForTesting;+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;+/**+ * Encode entity key for KV backend, e.g., RocksDB. The key is used to store the entity in the+ * backend. The final key will be:+ *+ * <pre>+ * Key Value+ * ml_{ml_id} -----> matalake info+ * ml_{ml_id} -----> matalake info+ * ca_{ml_id}_{ca_id} -----> catalog_info+ * ca_{ml_id}_{ca_id} -----> catalog_info+ * sc_{ml_id}_{ca_id}_{sc_id} ---> schema_info+ * sc_{ml_id}_{ca_id}_{sc_id} ---> schema_info+ * br_{ml_id}_{ca_id}_{br_id} ---> broker_info+ * br_{ml_id}_{ca_id}_{br_id} ---> broker_info+ *+ * ta_{ml_id}_{ca_id}_{sc_id}_{table_id} -----> table_info+ * ta_{ml_id}_{ca_id}_{sc_id}_{table_id} -----> table_info+ * to_{ml_id}_{ca_id}_{br_id}_{to_id} -----> topic_info+ * to_{ml_id}_{ca_id}_{br_id}_{to_id} -----> topic_info+ * </pre>+ */public class CustomEntityKeyEncoder implements EntityKeyEncoder {+ public static final Logger LOG = LoggerFactory.getLogger(CustomEntityKeyEncoder.class);- @Override- public byte[] encode(NameIdentifier entity) {- // Simple implementation, just use the entity's identifier as the key- // We will change this in next PR- // TODO (yuqi) Information of NameIdentifier may not enough for key encoding, we need to infer- // object- // class from key and then deserialize it when try to get it from kv store.- return entity.toString().getBytes();+ // 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(+ METALAKE, new String[] {METALAKE.getShortName() + "_"},+ CATALOG, new String[] {CATALOG.getShortName() + "_", "_"},+ SCHEMA, new String[] {SCHEMA.getShortName() + "_", "_", "_"},+ TABLE, new String[] {TABLE.getShortName() + "_", "_", "_", "_"});++ public CustomEntityKeyEncoder(KvBackend backend) {+ this.backend = backend;+ }++ /**+ * 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;+ }++ /**+ * 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+ * @return the encoded key for key-value storage+ */+ private byte[] encodeEntity(EntityIdentifer entityIdentifier, boolean createIdIfNotExists)+ throws IOException {+ EntityType entityType = entityIdentifier.getEntityType();+ String[] nameSpace = entityIdentifier.getNameIdentifier().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);+ }++ NameIdentifier identifier = entityIdentifier.getNameIdentifier();+ // If the name is a wild card, 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) {+ throw new UnsupportedOperationException("Unsupported entity type: " + entityType);+ }+ return formatNamespaceTemplateToByte(namespaceTemplate, namespaceIds);+ }++ // This is for point query and need to use specific name+ 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);++ String[] nameIdentifierTemplate = ENTITY_TYPE_TO_NAME_IDENTIFIER.get(entityType);+ if (nameIdentifierTemplate == null) {+ throw new UnsupportedOperationException("Unsupported entity type: " + entityType);+ }+ return formatNameIdentifierTemplateToByte(nameIdentifierTemplate, namespaceAndNameIds);+ }++ /**+ * Format the name space template to a byte array. For example, if the name space template is+ * "ca_{}_" and the ids are [1], the result is "ca_1_" which means we want to get all catalogs in+ * metalake '1'+ *+ * @param namespaceTemplate the name space template, please see {@link+ * #ENTITY_TYPE_TO_NAME_IDENTIFIER}+ * @param ids the ids that namespace names map to+ */+ private byte[] formatNamespaceTemplateToByte(String[] namespaceTemplate, long[] ids) {+ Preconditions.checkArgument(namespaceTemplate.length == ids.length + 1);++ byte[] bytes = new byte[0];+ for (int i = 0; i < namespaceTemplate.length; i++) {+ if (i != namespaceTemplate.length - 1) {+ bytes = Bytes.concat(bytes, namespaceTemplate[i].getBytes(), ByteUtils.longToByte(ids[i]));+ } else {+ bytes = Bytes.concat(bytes, namespaceTemplate[i].getBytes());+ }+ }++ return bytes;+ }++ /**+ * Format the name identifier to a byte array. For example, if the name space template is+ * "ca_{}_{}" and the ids is [1, 2], the result is "ca_1_2" which means we want to get the+ * specific catalog '2'+ *+ * @param nameIdentifierTemplate the name space template, please see {@link+ * #ENTITY_TYPE_TO_NAME_IDENTIFIER}+ * @param ids the ids that name identifier map to+ */+ private byte[] formatNameIdentifierTemplateToByte(String[] nameIdentifierTemplate, long[] ids) {+ Preconditions.checkArgument(nameIdentifierTemplate.length == ids.length);++ byte[] bytes = new byte[0];+ for (int i = 0; i < ids.length; i++) {+ bytes =+ Bytes.concat(bytes, nameIdentifierTemplate[i].getBytes(), ByteUtils.longToByte(ids[i]));+ }++ return bytes;+ }++ @VisibleForTesting+ public long getNextUsableId() throws IOException {+ byte[] maxByte = backend.get(CURRENT_MAX_ID);+ return maxByte == null ? 0 : ByteUtils.byteToLong(maxByte) + 1;}@Override- public byte[] encode(Namespace namespace) {- return namespace.toString().getBytes();+ public byte[] encode(EntityIdentifer entityIdentifer, boolean createIdIfNotExists)+ throws IOException {+ return encodeEntity(entityIdentifer, createIdIfNotExists);}}diff --git a/core/src/main/java/com/datastrato/graviton/storage/kv/EntityKeyEncoder.java b/core/src/main/java/com/datastrato/graviton/storage/kv/EntityKeyEncoder.javaindex 6f81fd267e..1945adfe19 100644--- a/core/src/main/java/com/datastrato/graviton/storage/kv/EntityKeyEncoder.java+++ b/core/src/main/java/com/datastrato/graviton/storage/kv/EntityKeyEncoder.java@@ -5,15 +5,22 @@package com.datastrato.graviton.storage.kv;-import com.datastrato.graviton.NameIdentifier;-import com.datastrato.graviton.Namespace;+import com.datastrato.graviton.Entity.EntityIdentifer;+import java.io.IOException;/*** Interface for encoding entity key for KV backend, e.g., RocksDB. The key is used to store the* entity in the backend.*/public interface EntityKeyEncoder {- byte[] encode(NameIdentifier identifier);- byte[] encode(Namespace namespace);+ /**+ * Construct the key for key-value store from the entity NameIdentifier and EntityType.+ *+ * @param entityIdentifer entity identifier+ * @param createIdIfNotExists create the id mapping for name if not exists+ * @return encoded key for key-value store+ * @throws IOException+ */+ byte[] encode(EntityIdentifer entityIdentifer, boolean createIdIfNotExists) throws IOException;}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 73b5dde17e..06efd01471 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@@ -57,4 +57,8 @@ 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 75fb8ac387..1e8b0c8822 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,6 +9,8 @@ import static com.datastrato.graviton.Configs.ENTITY_KV_STORE;import com.datastrato.graviton.Config;import com.datastrato.graviton.Entity;+import com.datastrato.graviton.Entity.EntityIdentifer;+import com.datastrato.graviton.Entity.EntityType;import com.datastrato.graviton.EntityAlreadyExistsException;import com.datastrato.graviton.EntitySerDe;import com.datastrato.graviton.EntityStore;@@ -18,12 +20,14 @@ import com.datastrato.graviton.Namespace;import com.datastrato.graviton.NoSuchEntityException;import com.datastrato.graviton.util.Bytes;import com.datastrato.graviton.util.Executable;+import com.google.common.annotations.VisibleForTesting;import com.google.common.collect.ImmutableMap;import com.google.common.collect.Lists;import java.io.IOException;import java.util.List;import java.util.Objects;import java.util.function.Function;+import lombok.Getter;import org.apache.commons.lang3.tuple.Pair;import org.slf4j.Logger;import org.slf4j.LoggerFactory;@@ -38,14 +42,14 @@ public class KvEntityStore implements EntityStore {public static final ImmutableMap<String, String> KV_BACKENDS =ImmutableMap.of("RocksDBKvBackend", RocksDBKvBackend.class.getCanonicalName());- private KvBackend backend;+ @Getter @VisibleForTesting private KvBackend backend;private EntityKeyEncoder entityKeyEncoder;private EntitySerDe serDe;@Overridepublic void initialize(Config config) throws RuntimeException {this.backend = createKvEntityBackend(config);- this.entityKeyEncoder = new CustomEntityKeyEncoder();+ this.entityKeyEncoder = new CustomEntityKeyEncoder(backend);}@Override@@ -54,9 +58,11 @@ public class KvEntityStore implements EntityStore {}@Override- public <E extends Entity & HasIdentifier> List<E> list(Namespace namespace, Class<E> e)- throws IOException {- byte[] startKey = entityKeyEncoder.encode(namespace);+ public <E extends Entity & HasIdentifier> List<E> list(+ Namespace namespace, Class<E> e, EntityType type) throws IOException {+ // Star means it's a wildcard+ NameIdentifier identifier = NameIdentifier.of(namespace, "*");+ byte[] startKey = entityKeyEncoder.encode(EntityIdentifer.of(identifier, type), false);byte[] endKey = Bytes.increment(Bytes.wrap(startKey)).get();List<Pair<byte[], byte[]>> kvs =backend.scan(@@ -77,26 +83,27 @@ public class KvEntityStore implements EntityStore {}@Override- public boolean exists(NameIdentifier ident) throws IOException {- return backend.get(entityKeyEncoder.encode(ident)) != null;+ public boolean exists(NameIdentifier ident, EntityType entityType) throws IOException {+ return backend.get(entityKeyEncoder.encode(EntityIdentifer.of(ident, entityType), false))+ != null;}@Override- public <E extends Entity & HasIdentifier> void put(NameIdentifier ident, E e, boolean overwritten)+ public <E extends Entity & HasIdentifier> void put(E e, boolean overwritten)throws IOException, EntityAlreadyExistsException {// Simple implementation, just use the entity's identifier as the key- byte[] key = entityKeyEncoder.encode(ident);+ byte[] key = entityKeyEncoder.encode(EntityIdentifer.of(e.nameIdentifier(), e.type()), true);byte[] value = serDe.serialize(e);backend.put(key, value, overwritten);}@Overridepublic <E extends Entity & HasIdentifier> E update(- NameIdentifier ident, Class<E> type, Function<E, E> updater)+ NameIdentifier ident, Class<E> type, EntityType entityType, Function<E, E> updater)throws IOException, NoSuchEntityException {return executeInTransaction(() -> {- byte[] key = entityKeyEncoder.encode(ident);+ byte[] key = entityKeyEncoder.encode(EntityIdentifer.of(ident, entityType), false);byte[] value = backend.get(key);if (value == null) {throw new NoSuchEntityException(ident.toString());@@ -105,28 +112,30 @@ public class KvEntityStore implements EntityStore {E e = serDe.deserialize(value, type);E updatedE = updater.apply(e);if (!updatedE.nameIdentifier().equals(ident)) {- delete(ident);+ delete(ident, entityType);}- put(updatedE.nameIdentifier(), updatedE, true /* overwritten */);+ put(updatedE, true /* overwritten */);return updatedE;});}@Override- public <E extends Entity & HasIdentifier> E get(NameIdentifier ident, Class<E> type)+ public <E extends Entity & HasIdentifier> E get(+ NameIdentifier ident, EntityType entityType, Class<E> e)throws NoSuchEntityException, IOException {- byte[] key = entityKeyEncoder.encode(ident);+ byte[] key = entityKeyEncoder.encode(EntityIdentifer.of(ident, entityType), false);+ // refer type from key;byte[] value = backend.get(key);if (value == null) {throw new NoSuchEntityException(ident.toString());}- return serDe.deserialize(value, type);+ return serDe.deserialize(value, e);}@Override- public boolean delete(NameIdentifier ident) throws IOException {- return backend.delete(entityKeyEncoder.encode(ident));+ public boolean delete(NameIdentifier ident, EntityType entityType) throws IOException {+ return backend.delete(entityKeyEncoder.encode(EntityIdentifer.of(ident, entityType), false));}@Overridediff --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 4d2ee1c155..f4f5a9f01d 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@@ -153,6 +153,12 @@ public class RocksDBKvBackend implements KvBackend {int count = 0;while (count < scanRange.getLimit() && rocksIterator.isValid()) {byte[] key = rocksIterator.key();++ // Break if the key is out of the scan range+ if (Bytes.wrap(key).compareTo(scanRange.getEnd()) > 0) {+ break;+ }+if (Bytes.wrap(key).compareTo(scanRange.getStart()) == 0) {if (scanRange.isStartInclusive()) {result.add(Pair.of(key, rocksIterator.value()));@@ -162,7 +168,6 @@ public class RocksDBKvBackend implements KvBackend {if (scanRange.isEndInclusive()) {result.add(Pair.of(key, rocksIterator.value()));}-break;} else {result.add(Pair.of(key, rocksIterator.value()));@@ -236,4 +241,12 @@ 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.javanew file mode 100644index 0000000000..e27c6e6bba--- /dev/null+++ b/core/src/main/java/com/datastrato/graviton/util/ByteUtils.java@@ -0,0 +1,41 @@+/*+ * Copyright 2023 Datastrato.+ * This software is licensed under the Apache License version 2.+ */++package com.datastrato.graviton.util;++import java.nio.ByteBuffer;+import java.nio.ByteOrder;++public class ByteUtils {+ public static byte[] intToByte(int v) {+ ByteBuffer buffer = ByteBuffer.allocate(Integer.BYTES);+ buffer.order(ByteOrder.BIG_ENDIAN);+ buffer.putInt(v);+ return buffer.array();+ }++ public static byte[] longToByte(long v) {+ ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);+ buffer.order(ByteOrder.BIG_ENDIAN);+ buffer.putLong(v);+ return buffer.array();+ }++ public static int byteToInt(byte[] bytes) {+ ByteBuffer buffer = ByteBuffer.allocate(Integer.BYTES);+ buffer.order(ByteOrder.BIG_ENDIAN);+ buffer.put(bytes);+ buffer.flip();+ return buffer.getInt();+ }++ public static long byteToLong(byte[] bytes) {+ ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);+ buffer.order(ByteOrder.BIG_ENDIAN);+ buffer.put(bytes);+ buffer.flip();+ return buffer.getLong();+ }+}diff --git a/core/src/main/java/com/datastrato/graviton/util/Bytes.java b/core/src/main/java/com/datastrato/graviton/util/Bytes.javaindex def69107e8..913766429f 100644--- a/core/src/main/java/com/datastrato/graviton/util/Bytes.java+++ b/core/src/main/java/com/datastrato/graviton/util/Bytes.java@@ -48,12 +48,19 @@ public class Bytes implements Comparable<byte[]> {return this.bytes;}- /** Concat two byte arrays into one. */- public static byte[] concat(byte[] one, byte[] two) {- int totalLen = one.length + two.length;+ /** Concat byte arrays into one. */+ public static byte[] concat(byte[]... values) {+ int totalLen = 0;+ for (byte[] b : values) {+ totalLen += b.length;+ }+byte[] res = new byte[totalLen];- System.arraycopy(one, 0, res, 0, one.length);- System.arraycopy(two, 0, res, one.length, two.length);+ int currentPos = 0;+ for (int i = 0; i < values.length; i++) {+ System.arraycopy(values[i], 0, res, currentPos, values[i].length);+ currentPos += values[i].length;+ }return res;}diff --git a/core/src/test/java/com/datastrato/graviton/TestEntityStore.java b/core/src/test/java/com/datastrato/graviton/TestEntityStore.javaindex 6b1502e1dc..6ad98d985a 100644--- a/core/src/test/java/com/datastrato/graviton/TestEntityStore.java+++ b/core/src/test/java/com/datastrato/graviton/TestEntityStore.java@@ -4,6 +4,7 @@*/package com.datastrato.graviton;+import com.datastrato.graviton.Entity.EntityType;import com.datastrato.graviton.meta.AuditInfo;import com.datastrato.graviton.meta.BaseMetalake;import com.datastrato.graviton.meta.CatalogEntity;@@ -48,8 +49,8 @@ public class TestEntityStore {}@Override- public <E extends Entity & HasIdentifier> List<E> list(Namespace namespace, Class<E> type)- throws IOException {+ public <E extends Entity & HasIdentifier> List<E> list(+ Namespace namespace, Class<E> cl, EntityType entityType) throws IOException {return entityMap.entrySet().stream().filter(e -> e.getKey().namespace().equals(namespace)).map(entry -> (E) entry.getValue())@@ -57,20 +58,20 @@ public class TestEntityStore {}@Override- public boolean exists(NameIdentifier ident) throws IOException {- return entityMap.containsKey(ident);+ public boolean exists(NameIdentifier nameIdentifier, EntityType type) throws IOException {+ return entityMap.containsKey(nameIdentifier);}@Override- public <E extends Entity & HasIdentifier> void put(- NameIdentifier ident, E e, boolean overwritten)+ public <E extends Entity & HasIdentifier> void put(E e, boolean overwritten)throws IOException, EntityAlreadyExistsException {+ NameIdentifier ident = e.nameIdentifier();if (overwritten) {entityMap.put(ident, e);} else {executeInTransaction(() -> {- if (exists(ident)) {+ if (exists(e.nameIdentifier(), e.type())) {throw new EntityAlreadyExistsException("Entity " + ident + " already exists");}entityMap.put(ident, e);@@ -81,7 +82,7 @@ public class TestEntityStore {@Overridepublic <E extends Entity & HasIdentifier> E update(- NameIdentifier ident, Class<E> type, Function<E, E> updater)+ NameIdentifier ident, Class<E> type, EntityType entityType, Function<E, E> updater)throws IOException, NoSuchEntityException {return executeInTransaction(() -> {@@ -93,7 +94,7 @@ public class TestEntityStore {E newE = updater.apply(e);NameIdentifier newIdent = NameIdentifier.of(newE.namespace(), newE.name());if (!newIdent.equals(ident)) {- delete(ident);+ delete(ident, entityType);}entityMap.put(newIdent, newE);return newE;@@ -101,7 +102,8 @@ public class TestEntityStore {}@Override- public <E extends Entity & HasIdentifier> E get(NameIdentifier ident, Class<E> type)+ public <E extends Entity & HasIdentifier> E get(+ NameIdentifier ident, EntityType entityType, Class<E> cl)throws NoSuchEntityException, IOException {E e = (E) entityMap.get(ident);if (e == null) {@@ -112,7 +114,7 @@ public class TestEntityStore {}@Override- public boolean delete(NameIdentifier ident) throws IOException {+ public boolean delete(NameIdentifier ident, EntityType entityType) throws IOException {Entity prev = entityMap.remove(ident);return prev != null;}@@ -172,26 +174,26 @@ public class TestEntityStore {store.initialize(Mockito.mock(Config.class));store.setSerDe(Mockito.mock(EntitySerDe.class));- store.put(metalake.nameIdentifier(), metalake);- store.put(catalog.nameIdentifier(), catalog);- store.put(table.nameIdentifier(), table);+ store.put(metalake);+ store.put(catalog);+ store.put(table);- Metalake retrievedMetalake = store.get(metalake.nameIdentifier(), BaseMetalake.class);+ Metalake retrievedMetalake =+ store.get(metalake.nameIdentifier(), EntityType.METALAKE, BaseMetalake.class);Assertions.assertEquals(metalake, retrievedMetalake);- CatalogEntity retrievedCatalog = store.get(catalog.nameIdentifier(), CatalogEntity.class);+ CatalogEntity retrievedCatalog =+ store.get(catalog.nameIdentifier(), EntityType.CATALOG, CatalogEntity.class);Assertions.assertEquals(catalog, retrievedCatalog);- Table retrievedTable = store.get(table.nameIdentifier(), TestTable.class);+ Table retrievedTable = store.get(table.nameIdentifier(), EntityType.TABLE, TestTable.class);Assertions.assertEquals(table, retrievedTable);- store.delete(metalake.nameIdentifier());+ store.delete(metalake.nameIdentifier(), EntityType.METALAKE);Assertions.assertThrows(NoSuchEntityException.class,- () -> store.get(metalake.nameIdentifier(), BaseMetalake.class));+ () -> store.get(metalake.nameIdentifier(), EntityType.METALAKE, BaseMetalake.class));- Assertions.assertThrows(- EntityAlreadyExistsException.class,- () -> store.put(catalog.nameIdentifier(), catalog, false));+ Assertions.assertThrows(EntityAlreadyExistsException.class, () -> store.put(catalog, false));}}diff --git a/core/src/test/java/com/datastrato/graviton/catalog/TestCatalogManager.java b/core/src/test/java/com/datastrato/graviton/catalog/TestCatalogManager.javaindex 477220d247..cd08b23ca9 100644--- a/core/src/test/java/com/datastrato/graviton/catalog/TestCatalogManager.java+++ b/core/src/test/java/com/datastrato/graviton/catalog/TestCatalogManager.java@@ -55,7 +55,7 @@ public class TestCatalogManager {new AuditInfo.Builder().withCreator("test").withCreateTime(Instant.now()).build()).withVersion(SchemaVersion.V_0_1).build();- entityStore.put(metalakeEntity.nameIdentifier(), metalakeEntity, true);+ entityStore.put(metalakeEntity, true);catalogManager = new CatalogManager(config, entityStore);}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.javanew file mode 100644index 0000000000..c501cc7fa2--- /dev/null+++ b/core/src/test/java/com/datastrato/graviton/storage/kv/TestEntityKeyEncoding.java@@ -0,0 +1,330 @@+/*+ * Copyright 2023 Datastrato.+ * This software is licensed under the Apache License version 2.+ */++package com.datastrato.graviton.storage.kv;++import static com.datastrato.graviton.Configs.DEFUALT_ENTITY_KV_STORE;+import static com.datastrato.graviton.Configs.ENTITY_KV_STORE;+import static com.datastrato.graviton.Configs.ENTITY_STORE;+import static com.datastrato.graviton.Configs.ENTRY_KV_ROCKSDB_BACKEND_PATH;+import static com.datastrato.graviton.storage.kv.CustomEntityKeyEncoder.NAMESPACE_SEPARATOR;+import static com.datastrato.graviton.storage.kv.CustomEntityKeyEncoder.WILD_CARD;++import com.datastrato.graviton.Config;+import com.datastrato.graviton.Configs;+import com.datastrato.graviton.Entity.EntityIdentifer;+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.util.ByteUtils;+import com.datastrato.graviton.util.Bytes;+import java.io.IOException;+import java.lang.reflect.Field;+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;+import org.junit.jupiter.api.TestClassOrder;+import org.junit.jupiter.api.TestInstance;+import org.junit.jupiter.api.TestInstance.Lifecycle;+import org.mockito.Mockito;++@TestInstance(Lifecycle.PER_CLASS)+@TestClassOrder(OrderAnnotation.class)+public class TestEntityKeyEncoding {+ private static final String ROCKS_DB_STORE_PATH = "/tmp/graviton_test_entity_key_encoding";+ private static Config config;++ public static EntityStore ENTITY_STORE_INSTANCE;+ private static CustomEntityKeyEncoder ENCODER;++ @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)));+ ENCODER = new CustomEntityKeyEncoder(((KvEntityStore) ENTITY_STORE_INSTANCE).getBackend());+ }++ @AfterEach+ public void cleanEnv() {+ try {+ if (ENTITY_STORE_INSTANCE != null) {+ ENTITY_STORE_INSTANCE.close();+ }++ FileUtils.deleteDirectory(FileUtils.getFile(ROCKS_DB_STORE_PATH));++ } catch (Exception e) {+ // Ignore+ }+ }++ @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(DEFUALT_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);+ }++ @Test+ @Order(1)+ public void testIdentifierEncoding()+ throws IOException, IllegalAccessException, NoSuchFieldException {+ // Metalake+ // metalake1 --> 1000000+ Namespace namespace = Namespace.of();+ CustomEntityKeyEncoder mockEncoder = Mockito.spy(ENCODER);+ Field f = CustomEntityKeyEncoder.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));++ NameIdentifier mateLakeIdentifier1 = NameIdentifier.of(namespace, "metalake1");+ byte[] realKey =+ mockEncoder.encode(EntityIdentifer.of(mateLakeIdentifier1, EntityType.METALAKE), true);+ byte[] expenctKey =+ Bytes.concat(+ EntityType.METALAKE.getShortName().getBytes(),+ NAMESPACE_SEPARATOR,+ ByteUtils.longToByte(1000000L));+ Assertions.assertArrayEquals(expenctKey, realKey);++ // name ---> id+ // catalog1 --> 1000010+ // catalog2 --> 1000011+ // catalog3 --> 1000012+ 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++) {+ NameIdentifier identifier = catalogIdentifiers[i];+ realKey = mockEncoder.encode(EntityIdentifer.of(identifier, EntityType.CATALOG), true);+ expenctKey =+ Bytes.concat(+ EntityType.CATALOG.getShortName().getBytes(),+ NAMESPACE_SEPARATOR,+ ByteUtils.longToByte(1000000L),+ NAMESPACE_SEPARATOR,+ ByteUtils.longToByte(1000010L + i));+ Assertions.assertArrayEquals(expenctKey, realKey);+ }+ // Assert next useable id+ Assertions.assertEquals(0, ENCODER.getNextUsableId());++ // name ---> id+ // schema1 --> 0+ // schema2 --> 1+ // schema3 --> 2+ 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];+ realKey = mockEncoder.encode(EntityIdentifer.of(identifier, EntityType.SCHEMA), true);+ expenctKey =+ Bytes.concat(+ EntityType.SCHEMA.getShortName().getBytes(),+ NAMESPACE_SEPARATOR,+ ByteUtils.longToByte(1000000L),+ NAMESPACE_SEPARATOR,+ ByteUtils.longToByte(1000011L),+ NAMESPACE_SEPARATOR,+ ByteUtils.longToByte(i));+ Assertions.assertArrayEquals(expenctKey, realKey);+ }+ // Assert next useable id+ Assertions.assertEquals(3, ENCODER.getNextUsableId());++ // name ---> id+ // table1 --> 3+ // table2 --> 4+ // table3 --> 5+ 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];+ realKey = mockEncoder.encode(EntityIdentifer.of(identifier, EntityType.TABLE), true);+ expenctKey =+ Bytes.concat(+ EntityType.TABLE.getShortName().getBytes(),+ NAMESPACE_SEPARATOR,+ ByteUtils.longToByte(1000000L),+ NAMESPACE_SEPARATOR,+ ByteUtils.longToByte(1000011L),+ NAMESPACE_SEPARATOR,+ ByteUtils.longToByte(2L),+ NAMESPACE_SEPARATOR,+ ByteUtils.longToByte(i + 3L));+ Assertions.assertArrayEquals(expenctKey, realKey);+ }+ // Assert next useable id+ Assertions.assertEquals(6, ENCODER.getNextUsableId());++ // Unsupported operation+ Assertions.assertThrows(+ UnsupportedOperationException.class,+ () -> {+ mockEncoder.encode(+ EntityIdentifer.of(+ NameIdentifier.of(+ Namespace.of("metalake1", "catalog2", "schema3", "table1"), "column1"),+ EntityType.COLUMN),+ true);+ });+ }++ @Test+ public void testTransaction() throws IOException {+ Namespace namespace = Namespace.of();+ CustomEntityKeyEncoder 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(EntityIdentifer.of(mateLakeIdentifier1, EntityType.METALAKE), true));+ }++ @Test+ @Order(10)+ public void testNamespaceEncoding()+ throws IOException, IllegalAccessException, NoSuchFieldException {+ // Scan all Metalake+ Namespace namespace = Namespace.of();+ CustomEntityKeyEncoder mockEncoder = Mockito.spy(ENCODER);++ Field f = CustomEntityKeyEncoder.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));++ NameIdentifier metalakeIdentifier = NameIdentifier.of(namespace, WILD_CARD);+ byte[] realKey =+ mockEncoder.encode(EntityIdentifer.of(metalakeIdentifier, EntityType.METALAKE), true);+ byte[] expenctKey =+ Bytes.concat(EntityType.METALAKE.getShortName().getBytes(), NAMESPACE_SEPARATOR);+ Assertions.assertArrayEquals(expenctKey, realKey);++ // Scan all catalog in metalake1+ // metalake1 --> 1000000L+ Namespace catalogNamespace = Namespace.of("metalake1");+ NameIdentifier catalogIdentifier = NameIdentifier.of(catalogNamespace, WILD_CARD);+ realKey = mockEncoder.encode(EntityIdentifer.of(catalogIdentifier, EntityType.CATALOG), true);+ expenctKey =+ Bytes.concat(+ EntityType.CATALOG.getShortName().getBytes(),+ NAMESPACE_SEPARATOR,+ ByteUtils.longToByte(1000000L),+ NAMESPACE_SEPARATOR);+ Assertions.assertArrayEquals(expenctKey, realKey);+ // Assert next useable id+ Assertions.assertEquals(0, ENCODER.getNextUsableId());++ // Scan all sc in metalake1.catalog2+ // catalog2 --> 0+ Namespace schemaNameSpace = Namespace.of("metalake1", "catalog2");+ NameIdentifier schemaIdentifier = NameIdentifier.of(schemaNameSpace, WILD_CARD);+ realKey = mockEncoder.encode(EntityIdentifer.of(schemaIdentifier, EntityType.SCHEMA), true);+ expenctKey =+ Bytes.concat(+ EntityType.SCHEMA.getShortName().getBytes(),+ NAMESPACE_SEPARATOR,+ ByteUtils.longToByte(1000000L),+ NAMESPACE_SEPARATOR,+ ByteUtils.longToByte(1000001L),+ NAMESPACE_SEPARATOR);+ Assertions.assertArrayEquals(expenctKey, realKey);+ // Assert next useable id+ Assertions.assertEquals(0, ENCODER.getNextUsableId());++ // Scan all table in metalake1.catalog2.schema3+ // schema3 --> 1+ Namespace tableNameSpace = Namespace.of("metalake1", "catalog2", "schema3");+ NameIdentifier tableIdentifier = NameIdentifier.of(tableNameSpace, WILD_CARD);+ realKey = mockEncoder.encode(EntityIdentifer.of(tableIdentifier, EntityType.TABLE), true);+ expenctKey =+ Bytes.concat(+ EntityType.TABLE.getShortName().getBytes(),+ NAMESPACE_SEPARATOR,+ ByteUtils.longToByte(1000000L),+ NAMESPACE_SEPARATOR,+ ByteUtils.longToByte(1000001L),+ NAMESPACE_SEPARATOR,+ ByteUtils.longToByte(0L),+ NAMESPACE_SEPARATOR);+ Assertions.assertArrayEquals(expenctKey, realKey);+ // Assert next useable id+ Assertions.assertEquals(1, ENCODER.getNextUsableId());++ // Unsupported operation+ Assertions.assertThrows(+ UnsupportedOperationException.class,+ () -> {+ mockEncoder.encode(+ EntityIdentifer.of(+ NameIdentifier.of(+ Namespace.of("metalake1", "catalog2", "schema3", "table1"), WILD_CARD),+ EntityType.COLUMN),+ true);+ });+ }+}diff --git a/core/src/test/java/com/datastrato/graviton/storage/kv/TestEntityStorageBackend.java b/core/src/test/java/com/datastrato/graviton/storage/kv/TestEntityStorageBackend.javaindex a9efde6fee..975302a4fb 100644--- a/core/src/test/java/com/datastrato/graviton/storage/kv/TestEntityStorageBackend.java+++ b/core/src/test/java/com/datastrato/graviton/storage/kv/TestEntityStorageBackend.java@@ -13,6 +13,7 @@ import static com.datastrato.graviton.Configs.ENTRY_KV_ROCKSDB_BACKEND_PATH;import com.datastrato.graviton.Catalog.Type;import com.datastrato.graviton.Config;import com.datastrato.graviton.Configs;+import com.datastrato.graviton.Entity.EntityType;import com.datastrato.graviton.EntityAlreadyExistsException;import com.datastrato.graviton.EntitySerDeFactory;import com.datastrato.graviton.EntityStore;@@ -25,6 +26,7 @@ import com.datastrato.graviton.meta.BaseMetalake;import com.datastrato.graviton.meta.CatalogEntity;import com.datastrato.graviton.meta.SchemaVersion;import java.time.Instant;+import java.util.List;import org.apache.commons.io.FileUtils;import org.junit.jupiter.api.AfterEach;import org.junit.jupiter.api.Assertions;@@ -96,16 +98,27 @@ public class TestEntityStorageBackend {.withMetalakeId(1L).withAuditInfo(auditInfo).build();+ CatalogEntity catalogCopyAgain =+ new CatalogEntity.Builder()+ .withId(1L)+ .withName("catalogCopyAgain")+ .withNamespace(Namespace.of("metalake"))+ .withType(Type.RELATIONAL)+ .withMetalakeId(1L)+ .withAuditInfo(auditInfo)+ .build();// 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.nameIdentifier(), metalake);+ store.put(metalake);// Try to mock an exceptiondouble a = 1 / 0;- store.put(catalog.nameIdentifier(), catalog);+ store.put(catalog);return null;});} catch (Exception e) {@@ -114,35 +127,49 @@ public class TestEntityStorageBackend {Assertions.assertThrows(NoSuchEntityException.class,- () -> store.get(metalake.nameIdentifier(), BaseMetalake.class));-- store.put(metalake.nameIdentifier(), metalake);- store.put(catalog.nameIdentifier(), catalog);- store.put(metalakeCopy.nameIdentifier(), metalakeCopy);- store.put(catalogCopy.nameIdentifier(), catalogCopy);-- Metalake retrievedMetalake = store.get(metalake.nameIdentifier(), BaseMetalake.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;+ });++ Metalake retrievedMetalake =+ store.get(metalake.nameIdentifier(), EntityType.METALAKE, BaseMetalake.class);Assertions.assertEquals(metalake, retrievedMetalake);- CatalogEntity retrievedCatalog = store.get(catalog.nameIdentifier(), CatalogEntity.class);+ CatalogEntity retrievedCatalog =+ store.get(catalog.nameIdentifier(), EntityType.CATALOG, CatalogEntity.class);Assertions.assertEquals(catalog, retrievedCatalog);- Metalake retrievedMetalakeCopy = store.get(metalakeCopy.nameIdentifier(), BaseMetalake.class);+ Metalake retrievedMetalakeCopy =+ store.get(metalakeCopy.nameIdentifier(), EntityType.METALAKE, BaseMetalake.class);Assertions.assertEquals(metalakeCopy, retrievedMetalakeCopy);CatalogEntity retrievedCatalogCopy =- store.get(catalogCopy.nameIdentifier(), CatalogEntity.class);+ store.get(catalogCopy.nameIdentifier(), EntityType.CATALOG, CatalogEntity.class);Assertions.assertEquals(catalogCopy, retrievedCatalogCopy);- store.delete(metalake.nameIdentifier());+ // Test scan and store list interface+ List<CatalogEntity> catalogEntityList =+ store.list(catalog.namespace(), CatalogEntity.class, EntityType.CATALOG);+ Assertions.assertEquals(3, catalogEntityList.size());+ Assertions.assertTrue(catalogEntityList.contains(catalog));+ Assertions.assertTrue(catalogEntityList.contains(catalogCopy));+ Assertions.assertTrue(catalogEntityList.contains(catalogCopyAgain));++ store.delete(metalake.nameIdentifier(), EntityType.METALAKE);Assertions.assertThrows(NoSuchEntityException.class,- () -> store.get(metalake.nameIdentifier(), BaseMetalake.class));+ () -> store.get(metalake.nameIdentifier(), EntityType.METALAKE, BaseMetalake.class));- Assertions.assertThrows(- EntityAlreadyExistsException.class,- () -> store.put(catalog.nameIdentifier(), catalog, false));- store.delete(catalog.nameIdentifier());+ Assertions.assertThrows(EntityAlreadyExistsException.class, () -> store.put(catalog, false));+ store.delete(catalog.nameIdentifier(), EntityType.CATALOG);Assertions.assertThrows(NoSuchEntityException.class,- () -> store.get(catalog.nameIdentifier(), CatalogEntity.class));+ () -> store.get(catalog.nameIdentifier(), EntityType.CATALOG, CatalogEntity.class));// Test updateBaseMetalake updatedMetalake =@@ -152,13 +179,15 @@ public class TestEntityStorageBackend {.withAuditInfo(auditInfo).withVersion(SchemaVersion.V_0_1).build();- store.put(metalake.nameIdentifier(), metalake);- store.update(metalake.nameIdentifier(), BaseMetalake.class, l -> updatedMetalake);+ store.put(metalake);+ store.update(+ metalake.nameIdentifier(), BaseMetalake.class, EntityType.METALAKE, l -> updatedMetalake);Assertions.assertEquals(- updatedMetalake, store.get(updatedMetalake.nameIdentifier(), BaseMetalake.class));+ updatedMetalake,+ store.get(updatedMetalake.nameIdentifier(), EntityType.METALAKE, BaseMetalake.class));Assertions.assertThrows(NoSuchEntityException.class,- () -> store.get(metalake.nameIdentifier(), BaseMetalake.class));+ () -> store.get(metalake.nameIdentifier(), EntityType.METALAKE, BaseMetalake.class));} catch (Exception e) {Assertions.fail(e.getMessage());diff --git a/core/src/test/java/com/datastrato/util/TestByteUtils.java b/core/src/test/java/com/datastrato/util/TestByteUtils.javanew file mode 100644index 0000000000..f59d502a36--- /dev/null+++ b/core/src/test/java/com/datastrato/util/TestByteUtils.java@@ -0,0 +1,31 @@+/*+ * Copyright 2023 Datastrato.+ * This software is licensed under the Apache License version 2.+ */++package com.datastrato.util;++import com.datastrato.graviton.util.ByteUtils;+import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.Test;++public class TestByteUtils {++ @Test+ public void testIntToByte() {+ int v = 258;+ byte[] b = ByteUtils.intToByte(v);+ Assertions.assertArrayEquals(new byte[] {0x00, 0x00, 0x01, 0x02}, b);+ int v2 = ByteUtils.byteToInt(b);+ assert v == v2;+ }++ @Test+ public void testLongToByte() {+ long v = 259;+ byte[] b = ByteUtils.longToByte(v);+ Assertions.assertArrayEquals(new byte[] {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x03}, b);+ long v2 = ByteUtils.byteToLong(b);+ assert v == v2;+ }+}diff --git a/rfc/rfc-2/Entity-key-encoding-for-kv-store.md b/rfc/rfc-2/Entity-key-encoding-for-kv-store.mdnew file mode 100644index 0000000000..0d61adc109--- /dev/null+++ b/rfc/rfc-2/Entity-key-encoding-for-kv-store.md@@ -0,0 +1,83 @@+<!--+ Copyright 2023 Datastrato.+ This software is licensed under the Apache License version 2.+-->++# RFC-1: Enity Key Encoding design for KV store++| Revision | Owner |+| :------- |-------|+| v0.1 | Qi Yu |++## Background+Currently, there will be many data to storage, for example,+User information. Such as username, passward, user property, this data is structure data+Metadata. Metadata is the key point of our product. Metadata is Heterogeneous and data may be very large+Other information, such as query history, query log and so on++To store this information, there will be 3 kinds of databases to store, that is+Relational database+KV Store+GraphDB+Others like MongoDB, ES++After we refer to snowflake schema and others (Hashdata and so on), KV storage is better than other kinds of storage compared to relational databases.++According to our previous design, Matadata in graviton will be originzed as the following structure+++According to the picture above, Metadata in graviton can be divided into multiple layers which is a little bit like a file directory structure. To implement this hierarchy, we can choose the following options to encode keys.++## Design++### Target++We should design a key encoding method to encode the key of KV store that should satisfy the following requirements:+- Support fast point query+- Support efficient range query+- Not very complicated+- Good expandability and compatibility+++### Design++Firstly, we introduce a global auto-increment ID that reprents the name of namespace. This ID is unique in the whole system.+For example, if there exists a catalog named `catalog1` with namepace name `metalake1`, we will add the following key-value pair to KV store++| Key | Value | Description |+|:----------|-----------|----------------------------------------------------------------|+| metalake1 | 1 | name to id mapping |+| catalog2 | 2 | name to id mapping |+| 1 | metalake1 | id to name mapping |+| 2 | catalog2 | id to name mapping |+ | current_max_id | 2 | Storage current max id, next avaiable id is current max id + 1 |++Attention, For `catalog` and `makelake`, Considering the global uniqueness, we will use a UUID instead of auto-increment ID.+`schema`, `table` and other entities will use auto-increment ID.+++Why we introduce this global auto-increment ID? Because we want to support the following features:+- If we want to rename a namespace, we can just update the name to id mapping+- If the name is too long, we can use a short name to represent it when encoding key of entity (see below)++Then, The whole key of entity can be encoded as the following format+++| Key | Value | Description |+|:-------------------------------------------------|---------------|---------------------------------|+| ml_{ml_id} | matalake info | ml is a short name for metalake |+| ml_{ml_id} | matalake info | ml is a short name for metalake |+| ca_{ml_id}_{ca_id} | catalog_info | ca is a short name for catalog |+| ca_{ml_id}_{ca_id} | catalog_info | ca is a short name for catalog |+| sc_{ml_id}\_{ca_id}_{sc_id} | schema_info | sc is a short name for schema |+| sc_{ml_id}\_{ca_id}_{sc_id} | schema_info | sc is a short name for schema |+| br_{ml_id}\_{ca_id}_{br_id} | broker_info | br is a short name for broker |+| br_{ml_id}\_{ca_id}_{br_id} | broker_info | br is a short name for broker |+| ta_{ml_id}\_{catalog_id}\_{schema_id}_{table_id} | table_info | ta is a short name for table |+| to_{ml_id}\_{catalog_id}\_{br_id}_{topic_id} | topic_info | to is a short name for topic |++## Implementation++Please see code ```CustomKeyEncoder```++