World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#51] feat(core): add SerDe interface for graviton (#52)
Jerry Shao5e40da01fa65
diff --git a/core/src/main/java/com/datastrato/graviton/EntitySerDe.java b/core/src/main/java/com/datastrato/graviton/EntitySerDe.javanew file mode 100644index 0000000000..8a8f0e44bb--- /dev/null+++ b/core/src/main/java/com/datastrato/graviton/EntitySerDe.java@@ -0,0 +1,46 @@+package com.datastrato.graviton;++import java.io.IOException;+import java.util.Optional;++public interface EntitySerDe {++ /**+ * Serializes the entity to a byte array.+ *+ * @param t the entity to serialize+ * @return the serialized byte array of the entity+ * @param <T> The type of entity+ * @throws IOException if the serialization fails+ */+ <T extends Entity> byte[] serialize(T t) throws IOException;++ /**+ * Deserializes the entity from a byte array.+ *+ * @param bytes the byte array to deserialize+ * @param clazz the class of the entity+ * @return the deserialized entity+ * @param <T> The type of entity+ * @throws IOException if the deserialization fails+ */+ default <T extends Entity> T deserialize(byte[] bytes, Class<T> clazz) throws IOException {+ ClassLoader loader =+ Optional.ofNullable(Thread.currentThread().getContextClassLoader())+ .orElse(getClass().getClassLoader());+ return deserialize(bytes, clazz, loader);+ }++ /**+ * Deserializes the entity from a byte array.+ *+ * @param bytes the byte array to deserialize+ * @param clazz the class of the entity+ * @param classLoader the class loader to use+ * @return the deserialized entity+ * @param <T> The type of entity+ * @throws IOException if the deserialization fails+ */+ <T extends Entity> T deserialize(byte[] bytes, Class<T> clazz, ClassLoader classLoader)+ throws IOException;+}diff --git a/core/src/main/java/com/datastrato/graviton/EntitySerDeFactory.java b/core/src/main/java/com/datastrato/graviton/EntitySerDeFactory.javanew file mode 100644index 0000000000..b4ae65c82d--- /dev/null+++ b/core/src/main/java/com/datastrato/graviton/EntitySerDeFactory.java@@ -0,0 +1,35 @@+package com.datastrato.graviton;++import com.datastrato.graviton.proto.ProtoEntitySerDe;+import com.google.common.collect.ImmutableMap;+import java.util.Map;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++public class EntitySerDeFactory {++ private static final Logger LOG = LoggerFactory.getLogger(EntitySerDe.class);++ // Register EntitySerDe's short name to its full qualified class name in the map. So that user+ // don't need to specify the full qualified class name when creating an EntitySerDe.+ private static final Map<String, String> ENTITY_SERDES =+ ImmutableMap.of("proto", ProtoEntitySerDe.class.getCanonicalName());++ private EntitySerDeFactory() {}++ public static EntitySerDe createEntitySerDe(Config config) {+ String name = config.get(configs.ENTITY_SERDE);+ return createEntitySerDe(name);+ }++ public static EntitySerDe createEntitySerDe(String name) {+ String className = ENTITY_SERDES.getOrDefault(name, name);++ try {+ return (EntitySerDe) Class.forName(className).newInstance();+ } catch (Exception e) {+ LOG.error("Failed to create EntitySerDe by name {}.", name, e);+ throw new RuntimeException("Failed to create EntitySerDe: " + name, e);+ }+ }+}diff --git a/core/src/main/java/com/datastrato/graviton/configs.java b/core/src/main/java/com/datastrato/graviton/configs.javaindex aeeb9c11d6..407e0926c1 100644--- a/core/src/main/java/com/datastrato/graviton/configs.java+++ b/core/src/main/java/com/datastrato/graviton/configs.java@@ -12,4 +12,11 @@ public interface configs {.stringConf()// TODO. Change this when we have a EntityStore implementation. @Jerry.createWithDefault("in-memory");++ ConfigEntry<String> ENTITY_SERDE =+ new ConfigBuilder("graviton.entity.serde")+ .doc("The entity serde to use")+ .version("0.1.0")+ .stringConf()+ .createWithDefault("proto");}diff --git a/core/src/main/java/com/datastrato/graviton/proto/ProtoEntitySerDe.java b/core/src/main/java/com/datastrato/graviton/proto/ProtoEntitySerDe.javanew file mode 100644index 0000000000..81a467ae05--- /dev/null+++ b/core/src/main/java/com/datastrato/graviton/proto/ProtoEntitySerDe.java@@ -0,0 +1,125 @@+package com.datastrato.graviton.proto;++import com.datastrato.graviton.Entity;+import com.datastrato.graviton.EntitySerDe;+import com.google.common.collect.ImmutableMap;+import com.google.common.collect.Maps;+import com.google.protobuf.Any;+import com.google.protobuf.Message;+import java.io.IOException;+import java.util.Map;+import java.util.Optional;++public class ProtoEntitySerDe implements EntitySerDe {++ // The implementation of different entities should also register its class to this map,+ // otherwise ProtoEntitySerDe will not be able to deserialize the entity.+ private static final Map<String, String> ENTITY_TO_SERDE =+ ImmutableMap.of(+ "com.datastrato.graviton.meta.AuditInfo", "com.datastrato.graviton.proto.AuditInfoSerDe",+ "com.datastrato.graviton.meta.Lakehouse", "com.datastrato.graviton.proto.LakehouseSerDe");++ private static final Map<String, String> ENTITY_TO_PROTO =+ ImmutableMap.of(+ "com.datastrato.graviton.meta.AuditInfo", "com.datastrato.graviton.proto.AuditInfo",+ "com.datastrato.graviton.meta.Lakehouse", "com.datastrato.graviton.proto.Lakehouse");++ private final Map<Class<? extends Entity>, ProtoSerDe<? extends Entity, ? extends Message>>+ entityToSerDe;++ private final Map<Class<? extends Entity>, Class<? extends Message>> entityToProto;++ private final Map<Class<? extends Message>, Class<? extends Entity>> protoToEntity;++ public ProtoEntitySerDe() throws IOException {+ ClassLoader loader =+ Optional.ofNullable(Thread.currentThread().getContextClassLoader())+ .orElse(getClass().getClassLoader());++ this.entityToSerDe = Maps.newHashMap();+ for (Map.Entry<String, String> entry : ENTITY_TO_SERDE.entrySet()) {+ String key = entry.getKey();+ String s = entry.getValue();+ Class<? extends Entity> entityClass = (Class<? extends Entity>) loadClass(key, loader);+ Class<? extends ProtoSerDe<? extends Entity, ? extends Message>> serdeClass =+ (Class<? extends ProtoSerDe<? extends Entity, ? extends Message>>) loadClass(s, loader);++ try {+ ProtoSerDe<? extends Entity, ? extends Message> serde = serdeClass.newInstance();+ entityToSerDe.put(entityClass, serde);+ } catch (Exception exception) {+ throw new IOException("Failed to instantiate serde class " + s, exception);+ }+ }++ this.entityToProto = Maps.newHashMap();+ this.protoToEntity = Maps.newHashMap();+ for (Map.Entry<String, String> entry : ENTITY_TO_PROTO.entrySet()) {+ String e = entry.getKey();+ String p = entry.getValue();+ Class<? extends Entity> entityClass = (Class<? extends Entity>) loadClass(e, loader);+ Class<? extends Message> protoClass = (Class<? extends Message>) loadClass(p, loader);+ entityToProto.put(entityClass, protoClass);+ protoToEntity.put(protoClass, entityClass);+ }+ }++ @Override+ public <T extends Entity> byte[] serialize(T t) throws IOException {+ Any any = Any.pack(toProto(t));+ return any.toByteArray();+ }++ @Override+ public <T extends Entity> T deserialize(byte[] bytes, Class<T> clazz, ClassLoader classLoader)+ throws IOException {+ Any any = Any.parseFrom(bytes);++ if (!entityToSerDe.containsKey(clazz) || !entityToProto.containsKey(clazz)) {+ throw new IOException("No proto and serde class found for entity " + clazz.getName());+ }++ if (!any.is(entityToProto.get(clazz))) {+ throw new IOException("Invalid proto for entity " + clazz.getName());+ }++ try {+ Class<? extends Message> protoClazz = entityToProto.get(clazz);+ Message anyMessage = any.unpack(protoClazz);+ return fromProto(anyMessage);+ } catch (Exception e) {+ throw new IOException("Failed to deserialize entity " + clazz.getName(), e);+ }+ }++ public <T extends Entity, M extends Message> M toProto(T t) throws IOException {+ if (!entityToSerDe.containsKey(t.getClass())) {+ throw new IOException("No serde found for entity " + t.getClass().getName());+ }++ ProtoSerDe<T, M> protoSerDe = (ProtoSerDe<T, M>) entityToSerDe.get(t.getClass());+ return protoSerDe.serialize(t);+ }++ public <T extends Entity, M extends Message> T fromProto(M m) throws IOException {+ if (!protoToEntity.containsKey(m.getClass())) {+ throw new IOException("No entity class found for proto " + m.getClass().getName());+ }+ Class<? extends Entity> entityClass = protoToEntity.get(m.getClass());++ if (!entityToSerDe.containsKey(entityClass)) {+ throw new IOException("No serde found for entity " + entityClass.getName());+ }++ ProtoSerDe<T, M> protoSerDe = (ProtoSerDe<T, M>) entityToSerDe.get(entityClass);+ return protoSerDe.deserialize(m);+ }++ private Class<?> loadClass(String className, ClassLoader classLoader) throws IOException {+ try {+ return Class.forName(className, true, classLoader);+ } catch (Exception e) {+ throw new IOException("Failed to load class " + className, e);+ }+ }+}diff --git a/core/src/main/java/com/datastrato/graviton/proto/ProtoSerDe.java b/core/src/main/java/com/datastrato/graviton/proto/ProtoSerDe.javaindex 2fb5bfc01b..3a16ca8c32 100644--- a/core/src/main/java/com/datastrato/graviton/proto/ProtoSerDe.java+++ b/core/src/main/java/com/datastrato/graviton/proto/ProtoSerDe.java@@ -1,8 +1,8 @@package com.datastrato.graviton.proto;-import com.google.protobuf.MessageLite;+import com.google.protobuf.Message;-public interface ProtoSerDe<T, M extends MessageLite> {+public interface ProtoSerDe<T, M extends Message> {M serialize(T t);diff --git a/core/src/main/java/com/datastrato/graviton/proto/ProtoUtils.java b/core/src/main/java/com/datastrato/graviton/proto/ProtoUtils.javaindex bec5e591fa..870d4d3793 100644--- a/core/src/main/java/com/datastrato/graviton/proto/ProtoUtils.java+++ b/core/src/main/java/com/datastrato/graviton/proto/ProtoUtils.java@@ -1,50 +1,9 @@package com.datastrato.graviton.proto;-import com.datastrato.graviton.Entity;-import com.google.protobuf.MessageLite;-import com.google.protobuf.Parser;import com.google.protobuf.Timestamp;import java.time.Instant;-import java.util.Collections;-import java.util.HashMap;-import java.util.Map;public class ProtoUtils {- private static final Map<- Class<? extends Entity>, ProtoSerDe<? extends Entity, ? extends MessageLite>>- ENTITY_TO_SERDE;-- static {- Map<Class<? extends Entity>, ProtoSerDe<? extends Entity, ? extends MessageLite>> tmp =- new HashMap<>();- tmp.put(com.datastrato.graviton.meta.AuditInfo.class, new AuditInfoSerDe());- tmp.put(com.datastrato.graviton.meta.Lakehouse.class, new LakehouseSerDe());-- ENTITY_TO_SERDE = Collections.unmodifiableMap(tmp);- }-- private static final Map<- Class<? extends MessageLite>, ProtoSerDe<? extends Entity, ? extends MessageLite>>- PROTO_TO_SERDE;-- static {- Map<Class<? extends MessageLite>, ProtoSerDe<? extends Entity, ? extends MessageLite>> tmp =- new HashMap<>();- tmp.put(AuditInfo.class, new AuditInfoSerDe());- tmp.put(Lakehouse.class, new LakehouseSerDe());-- PROTO_TO_SERDE = Collections.unmodifiableMap(tmp);- }-- private static final Map<Class<? extends Entity>, Parser<?>> ENTITY_TO_PARSER;-- static {- Map<Class<? extends Entity>, Parser<?>> tmp = new HashMap<>();- tmp.put(com.datastrato.graviton.meta.AuditInfo.class, AuditInfo.parser());- tmp.put(com.datastrato.graviton.meta.Lakehouse.class, Lakehouse.parser());-- ENTITY_TO_PARSER = Collections.unmodifiableMap(tmp);- }private ProtoUtils() {}@@ -58,42 +17,4 @@ public class ProtoUtils {public static Instant toInstant(Timestamp timestamp) {return Instant.ofEpochSecond(timestamp.getSeconds(), timestamp.getNanos());}-- public static <T extends Entity, M extends MessageLite> M toProto(T t) {- if (!ENTITY_TO_SERDE.containsKey(t.getClass())) {- throw new ProtoSerDeException("No proto serializer for " + t.getClass().getName());- }-- ProtoSerDe<T, M> protoSerDe = (ProtoSerDe<T, M>) ENTITY_TO_SERDE.get(t.getClass());- return protoSerDe.serialize(t);- }-- public static <T extends Entity> byte[] toBytes(T t) {- return toProto(t).toByteArray();- }-- public static <T extends Entity, M extends MessageLite> T fromProto(M m) {- if (!PROTO_TO_SERDE.containsKey(m.getClass())) {- throw new ProtoSerDeException("No proto deserializer for " + m.getClass().getName());- }-- ProtoSerDe<T, M> protoSerDe = (ProtoSerDe<T, M>) PROTO_TO_SERDE.get(m.getClass());- return protoSerDe.deserialize(m);- }-- public static <T extends Entity, M extends MessageLite> T fromBytes(- byte[] bytes, Class<T> clazz) {- if (!ENTITY_TO_SERDE.containsKey(clazz) || !ENTITY_TO_PARSER.containsKey(clazz)) {- throw new ProtoSerDeException("No proto deserializer or parser for " + clazz.getName());- }-- try {- M message = (M) ENTITY_TO_PARSER.get(clazz).parseFrom(bytes);- ProtoSerDe<T, M> protoSerDe = (ProtoSerDe<T, M>) ENTITY_TO_SERDE.get(clazz);- return protoSerDe.deserialize(message);-- } catch (Exception e) {- throw new ProtoSerDeException("Failed in deserializing bytes to proto", e);- }- }}diff --git a/core/src/test/java/com/datastrato/graviton/proto/TestEntityProtoSerDe.java b/core/src/test/java/com/datastrato/graviton/proto/TestEntityProtoSerDe.javaindex a5473d95f4..035f3cb00d 100644--- a/core/src/test/java/com/datastrato/graviton/proto/TestEntityProtoSerDe.java+++ b/core/src/test/java/com/datastrato/graviton/proto/TestEntityProtoSerDe.java@@ -1,7 +1,10 @@package com.datastrato.graviton.proto;+import com.datastrato.graviton.EntitySerDe;+import com.datastrato.graviton.EntitySerDeFactory;import com.datastrato.graviton.meta.SchemaVersion;import com.google.common.collect.ImmutableMap;+import java.io.IOException;import java.time.Instant;import java.util.Map;import org.junit.jupiter.api.Assertions;@@ -9,12 +12,13 @@ import org.junit.jupiter.api.Test;public class TestEntityProtoSerDe {+ private final EntitySerDe entitySerDe = EntitySerDeFactory.createEntitySerDe("proto");+@Test- public void testAuditInfoSerDe() {+ public void testAuditInfoSerDe() throws IOException {Instant now = Instant.now();String creator = "creator";String modifier = "modifier";- String accessor = "accessor";com.datastrato.graviton.meta.AuditInfo auditInfo =new com.datastrato.graviton.meta.AuditInfo.Builder()@@ -24,14 +28,16 @@ public class TestEntityProtoSerDe {.withLastModifiedTime(now).build();- AuditInfo auditInfoProto = ProtoUtils.toProto(auditInfo);+ ProtoEntitySerDe protoEntitySerDe = (ProtoEntitySerDe) entitySerDe;++ AuditInfo auditInfoProto = protoEntitySerDe.toProto(auditInfo);Assertions.assertEquals(creator, auditInfoProto.getCreator());Assertions.assertEquals(now, ProtoUtils.toInstant(auditInfoProto.getCreateTime()));Assertions.assertEquals(modifier, auditInfoProto.getLastModifier());Assertions.assertEquals(now, ProtoUtils.toInstant(auditInfoProto.getLastModifiedTime()));com.datastrato.graviton.meta.AuditInfo auditInfoFromProto =- ProtoUtils.fromProto(auditInfoProto);+ protoEntitySerDe.fromProto(auditInfoProto);Assertions.assertEquals(auditInfo, auditInfoFromProto);// Test with optional fields@@ -41,24 +47,24 @@ public class TestEntityProtoSerDe {.withCreateTime(now).build();- AuditInfo auditInfoProto1 = ProtoUtils.toProto(auditInfo1);+ AuditInfo auditInfoProto1 = protoEntitySerDe.toProto(auditInfo1);Assertions.assertEquals(creator, auditInfoProto1.getCreator());Assertions.assertEquals(now, ProtoUtils.toInstant(auditInfoProto1.getCreateTime()));com.datastrato.graviton.meta.AuditInfo auditInfoFromProto1 =- ProtoUtils.fromProto(auditInfoProto1);+ protoEntitySerDe.fromProto(auditInfoProto1);Assertions.assertEquals(auditInfo1, auditInfoFromProto1);// Test from/to bytes- byte[] bytes = ProtoUtils.toBytes(auditInfo1);+ byte[] bytes = entitySerDe.serialize(auditInfo1);com.datastrato.graviton.meta.AuditInfo auditInfoFromBytes =- ProtoUtils.fromBytes(bytes, com.datastrato.graviton.meta.AuditInfo.class);+ entitySerDe.deserialize(bytes, com.datastrato.graviton.meta.AuditInfo.class);Assertions.assertEquals(auditInfo1, auditInfoFromBytes);}@Test- public void testEntitiesSerDe() {+ public void testEntitiesSerDe() throws IOException {Instant now = Instant.now();String creator = "creator";Integer tenantId = 1;@@ -83,15 +89,17 @@ public class TestEntityProtoSerDe {.withVersion(version).build();- Lakehouse lakehouseProto = ProtoUtils.toProto(lakehouse);+ ProtoEntitySerDe protoEntitySerDe = (ProtoEntitySerDe) entitySerDe;++ Lakehouse lakehouseProto = protoEntitySerDe.toProto(lakehouse);Assertions.assertEquals(props, lakehouseProto.getPropertiesMap());com.datastrato.graviton.meta.Lakehouse lakehouseFromProto =- ProtoUtils.fromProto(lakehouseProto);+ protoEntitySerDe.fromProto(lakehouseProto);Assertions.assertEquals(lakehouse, lakehouseFromProto);- byte[] lakehouseBytes = ProtoUtils.toBytes(lakehouse);+ byte[] lakehouseBytes = protoEntitySerDe.serialize(lakehouse);com.datastrato.graviton.meta.Lakehouse lakehouseFromBytes =- ProtoUtils.fromBytes(lakehouseBytes, com.datastrato.graviton.meta.Lakehouse.class);+ protoEntitySerDe.deserialize(lakehouseBytes, com.datastrato.graviton.meta.Lakehouse.class);Assertions.assertEquals(lakehouse, lakehouseFromBytes);// Test Lakehouse without props map@@ -103,15 +111,15 @@ public class TestEntityProtoSerDe {.withVersion(version).build();- Lakehouse lakehouseProto1 = ProtoUtils.toProto(lakehouse1);+ Lakehouse lakehouseProto1 = protoEntitySerDe.toProto(lakehouse1);Assertions.assertEquals(0, lakehouseProto1.getPropertiesCount());com.datastrato.graviton.meta.Lakehouse lakehouseFromProto1 =- ProtoUtils.fromProto(lakehouseProto1);+ protoEntitySerDe.fromProto(lakehouseProto1);Assertions.assertEquals(lakehouse1, lakehouseFromProto1);- byte[] lakehouseBytes1 = ProtoUtils.toBytes(lakehouse1);+ byte[] lakehouseBytes1 = entitySerDe.serialize(lakehouse1);com.datastrato.graviton.meta.Lakehouse lakehouseFromBytes1 =- ProtoUtils.fromBytes(lakehouseBytes1, com.datastrato.graviton.meta.Lakehouse.class);+ entitySerDe.deserialize(lakehouseBytes1, com.datastrato.graviton.meta.Lakehouse.class);Assertions.assertEquals(lakehouse1, lakehouseFromBytes1);}}