Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement GenericObject - Allow GenericRecord to wrap any Java Object #10057

Merged
merged 21 commits into from
Apr 8, 2021
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -3888,7 +3888,7 @@ public void testSendCompressedWithDeferredSchemaSetup(boolean enableBatching) th
GenericRecord res = consumer.receive().getValue();
consumer.close();
assertEquals(SchemaType.AVRO, res.getSchemaType());
org.apache.avro.generic.GenericRecord nativeRecord = (org.apache.avro.generic.GenericRecord) res.getNativeRecord();
org.apache.avro.generic.GenericRecord nativeRecord = (org.apache.avro.generic.GenericRecord) res.getNativeObject();
org.apache.avro.Schema schema = nativeRecord.getSchema();
for (org.apache.pulsar.client.api.schema.Field f : res.getFields()) {
log.info("field {} {}", f.getName(), res.getField(f));
Expand Down Expand Up @@ -3930,10 +3930,10 @@ public void testAccessAvroSchemaMetadata(Schema<MyBean> schema) throws Exception
org.apache.avro.generic.GenericRecord nativeAvroRecord = null;
JsonNode nativeJsonRecord = null;
if (schema.getSchemaInfo().getType() == SchemaType.AVRO) {
nativeAvroRecord = (org.apache.avro.generic.GenericRecord) res.getNativeRecord();
nativeAvroRecord = (org.apache.avro.generic.GenericRecord) res.getNativeObject();
assertNotNull(nativeAvroRecord);
} else {
nativeJsonRecord = (JsonNode) res.getNativeRecord();
nativeJsonRecord = (JsonNode) res.getNativeObject();
assertNotNull(nativeJsonRecord);
}
for (org.apache.pulsar.client.api.schema.Field f : res.getFields()) {
Expand Down
103 changes: 102 additions & 1 deletion pulsar-broker/src/test/java/org/apache/pulsar/schema/SchemaTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
import static org.testng.Assert.assertTrue;
import com.google.common.collect.Sets;

import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
Expand All @@ -40,12 +41,12 @@
import org.apache.pulsar.client.api.PulsarClientException;
import org.apache.pulsar.client.api.Schema;
import org.apache.pulsar.client.api.schema.GenericRecord;
import org.apache.pulsar.client.api.schema.PrimitiveRecord;
import org.apache.pulsar.client.api.schema.SchemaDefinition;
import org.apache.pulsar.common.naming.TopicDomain;
import org.apache.pulsar.common.naming.TopicName;
import org.apache.pulsar.common.policies.data.ClusterData;
import org.apache.pulsar.common.policies.data.TenantInfo;
import org.apache.pulsar.common.schema.SchemaInfo;
import org.apache.pulsar.common.schema.SchemaType;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
Expand Down Expand Up @@ -201,6 +202,106 @@ public void testBytesSchemaDeserialize() throws Exception {
consumer1.close();
}

@Test
public void testStringSchema() throws Exception {
final String tenant = PUBLIC_TENANT;
final String namespace = "test-namespace-" + randomName(16);
final String topicName = "test-string-schema";

final String topic = TopicName.get(
TopicDomain.persistent.value(),
tenant,
namespace,
topicName).toString();

admin.namespaces().createNamespace(
tenant + "/" + namespace,
Sets.newHashSet(CLUSTER_NAME));

admin.topics().createPartitionedTopic(topic, 2);

Producer<String> producer = pulsarClient
.newProducer(Schema.STRING)
.topic(topic)
.create();

Consumer<String> consumer = pulsarClient.newConsumer(Schema.STRING)
.subscriptionName("test-sub")
.topic(topic)
.subscribe();

// use GenericRecord even for primitive types
// it will be a PrimitiveRecord
Consumer<GenericRecord> consumer2 = pulsarClient.newConsumer(Schema.AUTO_CONSUME())
.subscriptionName("test-sub3")
.topic(topic)
.subscribe();

producer.send("foo");

Message<String> message = consumer.receive();
Message<GenericRecord> message3 = consumer2.receive();

assertEquals("foo", message.getValue());
assertTrue(message3.getValue() instanceof PrimitiveRecord);
assertEquals(SchemaType.STRING, message3.getValue().getSchemaType());
assertEquals("foo", message3.getValue().getNativeObject());

producer.close();
consumer.close();
consumer2.close();
}

@Test
public void testUseAutoConsumeWithSchemalessTopic() throws Exception {
final String tenant = PUBLIC_TENANT;
final String namespace = "test-namespace-" + randomName(16);
final String topicName = "test-schemaless";

final String topic = TopicName.get(
TopicDomain.persistent.value(),
tenant,
namespace,
topicName).toString();

admin.namespaces().createNamespace(
tenant + "/" + namespace,
Sets.newHashSet(CLUSTER_NAME));

admin.topics().createPartitionedTopic(topic, 2);

Producer<byte[]> producer = pulsarClient
.newProducer()
.topic(topic)
.create();

Consumer<byte[]> consumer = pulsarClient.newConsumer()
.subscriptionName("test-sub")
.topic(topic)
.subscribe();

// use GenericRecord even for primitive types
// it will be a PrimitiveRecord
Consumer<GenericRecord> consumer2 = pulsarClient.newConsumer(Schema.AUTO_CONSUME())
.subscriptionName("test-sub3")
.topic(topic)
.subscribe();

producer.send("foo".getBytes(StandardCharsets.UTF_8));

Message<byte[]> message = consumer.receive();
Message<GenericRecord> message3 = consumer2.receive();

assertEquals("foo".getBytes(StandardCharsets.UTF_8), message.getValue());
assertTrue(message3.getValue() instanceof PrimitiveRecord);
assertEquals(SchemaType.BYTES, message3.getValue().getSchemaType());
assertEquals("foo".getBytes(StandardCharsets.UTF_8), message3.getValue().getNativeObject());

producer.close();
consumer.close();
consumer2.close();
}

@Test
public void testIsUsingAvroSchemaParser() {
for (SchemaType value : SchemaType.values()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
import java.util.Date;
import org.apache.pulsar.client.api.schema.GenericRecord;
import org.apache.pulsar.client.api.schema.GenericSchema;
import org.apache.pulsar.client.api.schema.GenericObject;
import org.apache.pulsar.client.api.schema.SchemaDefinition;
import org.apache.pulsar.client.api.schema.SchemaInfoProvider;
import org.apache.pulsar.client.internal.DefaultImplementation;
Expand Down Expand Up @@ -361,9 +362,8 @@ static Schema<GenericRecord> AUTO() {
* Create a schema instance that automatically deserialize messages
* based on the current topic schema.
*
* <p>The messages values are deserialized into a {@link GenericRecord} object.
*
* <p>Currently this is only supported with Avro and JSON schema types.
* <p>The messages values are deserialized into a {@link GenericRecord} object,
* that extends the {@link GenericObject} interface.
*
* @return the auto schema instance
*/
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.pulsar.client.api.schema;

import org.apache.pulsar.common.schema.SchemaType;

/**
* This is an abstraction over the logical value that is store into a Message.
* Pulsar decodes the payload of the Message using the Schema that is configured for the topic.
*/
public interface GenericObject {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this interface suppose to be used as a schema type for producers or consumers, .e.g. Consumer ? If so, can you write some tests that has consumers / producers that uses this new type of Schema?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there a reason why we need this interface as all. Shouldn't having these additional methods in GenericRecord suffice?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jerrypeng
the idea is to let users user "GenericObject" instead of GenericRecord while dealing with "Any object", on the Consumer/Sink side, because GenericRecord for many users is related to a Struct type (like AVRO GenericRecord), and it carries "getFields()"

If so, can you write some tests that has consumers / producers that uses this new type of Schema?
I added tests about GenericObjectWrapper.

The main goal is to have Sink and having the ability to write Sinks that are not bound to a specific Schema at compile time.


/**
* Return the schema tyoe.
*
* @return the schema type
* @throws UnsupportedOperationException if this feature is not implemented
* @see SchemaType#BYTES when the topic has no schema information
* @see SchemaType#STRING
* @see SchemaType#AVRO
* @see SchemaType#PROTOBUF_NATIVE
* @see SchemaType#JSON
*/
SchemaType getSchemaType();

/**
* Return the internal native representation of the Object,
* like a AVRO GenericRecord, a String or a byte[].
*
* @return the decoded object
* @throws UnsupportedOperationException if the operation is not supported
*/
Object getNativeObject();
eolivelli marked this conversation as resolved.
Show resolved Hide resolved
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
*/
@InterfaceAudience.Public
@InterfaceStability.Stable
public interface GenericRecord {
public interface GenericRecord extends GenericObject {

/**
* Return schema version.
Expand Down Expand Up @@ -71,6 +71,7 @@ default Object getField(Field field) {
* @see SchemaType#PROTOBUF_NATIVE
* @see SchemaType#JSON
*/
@Override
default SchemaType getSchemaType() {
throw new UnsupportedOperationException();
}
Expand All @@ -82,7 +83,8 @@ default SchemaType getSchemaType() {
* @return the internal representation of the record
* @throws UnsupportedOperationException if the operation is not supported
*/
default Object getNativeRecord() {
@Override
default Object getNativeObject() {
jerrypeng marked this conversation as resolved.
Show resolved Hide resolved
throw new UnsupportedOperationException();
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.pulsar.client.api.schema;

import org.apache.pulsar.common.classification.InterfaceAudience;
import org.apache.pulsar.common.classification.InterfaceStability;
import org.apache.pulsar.common.schema.SchemaType;

import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
* An interface represents a message with schema for non Struct types.
*/
@InterfaceAudience.Private
@InterfaceStability.Evolving
public class PrimitiveRecord implements GenericRecord {
jerrypeng marked this conversation as resolved.
Show resolved Hide resolved

private final Object nativeObject;
private final SchemaType schemaType;

public static PrimitiveRecord of(Object nativeRecord, SchemaType schemaType) {
return new PrimitiveRecord(nativeRecord, schemaType);
}

private PrimitiveRecord(Object nativeObject, SchemaType schemaType) {
this.nativeObject = nativeObject;
this.schemaType = schemaType;
}

@Override
public byte[] getSchemaVersion() {
return null;
}

@Override
public List<Field> getFields() {
return Collections.emptyList();
}

@Override
public Object getField(String fieldName) {
return null;
}

@Override
public SchemaType getSchemaType() {
return schemaType;
}

@Override
public Object getNativeObject() {
return nativeObject;
}

@Override
public String toString() {
return Objects.toString(nativeObject);
}

@Override
public int hashCode() {
return Objects.hashCode(nativeObject);
}

@Override
public boolean equals(Object other) {
if (! (other instanceof PrimitiveRecord)) {
return false;
}
return Objects.equals(nativeObject, ((PrimitiveRecord) other).nativeObject);
}
}
Loading