What is the best way to deal with avro enums when ...
# troubleshooting
g
What is the best way to deal with avro enums when using flink sql ?
b
Not sure about flink sql...but we handle it by using the table api and the
raw
data format. From there, we convert it to a datastream. Then we use a UDF to use the confluent kafka (python) library to deserialize each message. Then convert it back to the Table API if needed
g
Thanks for the reply. But this is to complex for our case. We want to allow analytics to easily explore cdc and events data by just writing sql. Events have enums and as I understand there is no easy way to deserialise that data without using datastreams api 😞
The only way I got it working by forking confluent-avro and adding hacky enum handling
j
@Gintaras Matulas Can you share your fork? Thanks.
g
Initially I did it in scala for our internal commons library. Here I did a quick port here https://github.com/gintarasm/flink Basically I added an optional param for subject. And then if the subject is set I fetch the latest schema and when converting RowTypes
VARCHAR
or
CHAR
instead of defaulting for Avro string type I get it from the schema that I fetched earlier
j
Got it... I thought I could fork Confluent Avro directly.
g
It’s easier just to copy paste the code into it’s own project and then add the jar as dependency to the cluster or the flink job
j
My knowledge there is quite limited! Will try to get it done. Thank you so much @Gintaras Matulas.
g
Probably used incorrect term there. Cause I just copied the code to separate repo and modified it, because the confluent-avro is part of the flink repo it was faster this way
j
Thanks @Gintaras Matulas. How do you use it then? Do you need to build FLINK from the source and then install from there or use Class Shadowing?
g
./mvnw clean package -pl :flink-avro-confluent-registry
This should be the only avro project. Then in
flink-avro-confluent-registry/target
you should have jars. And then depending on your deployments replace the jar in flin
/lib
folder or add this as dependency to your flink job
j
Thanks a lot, @Gintaras Matulas. Your insights are incredibly helpful. I'm beginning to wrap my head around this. I currently use FLINK SQL and create my own JAR with Gradle based on that. It seems your suggestion is to build
flink-avro-confluent-registry
and then include its dependency in
build.gradle
. Is this a right assumption?
Copy code
implementation files('libs/flink-avro-confluent-registry-1.18-SNAPSHOT.jar')
g
Probably. But it really depends on how flink is set up
j
I build my Flink SQL jar on a docker image and deploy to ECR. Then I use that image with Flink EKS Operator. Just the JAR dependencies that is taking a little to get my head around it.
g
So I think in your case adding it to build gradle should be enough
j
Somehow when I use the JAR from your fork I'm getting missing dependencies issues at
io.confluent.kafka.schemaregistry.client.rest.exceptions.RestClientException
. Have you removed this dependencies from your fork? Doesn't look it's coming from your changes.
g
You can just add this https://mvnrepository.com/artifact/io.confluent/kafka-schema-registry-client/7.5.3 It been a long time since I worked with maven. The issue is that this dependency is set as provided and not included in the library. So when you try to run your job it expects at runtime to have this dependency loaded
j
Thanks once again @Gintaras Matulas. That did the trick. I was able to build the JAR. However, I still get errors with the enum:
Copy code
Caused by: java.io.IOException: Failed to deserialize consumer record ConsumerRecord(topic = us1.service.accounting.transactions, partition = 0, leaderEpoch = 2, offset = 0, CreateTime = 1705063363304, serialized key size = 13, serialized value size = 109, headers = RecordHeaders(headers = [RecordHeader(key = x-datadog-trace-id, value = [54, 54, 51, 57, 54, 49, 54, 48, 54, 50, 56, 56, 57, 54, 55, 50, 52, 56, 49]), RecordHeader(key = x-datadog-parent-id, value = [52, 48, 50, 50, 49, 50, 51, 49, 52, 52, 52, 55, 55, 55, 55, 57, 52, 57, 50]), RecordHeader(key = x-datadog-sampling-priority, value = [49]), RecordHeader(key = x-datadog-tags, value = [95, 100, 100, 46, 112, 46, 100, 109, 61, 45, 49, 44, 95, 100, 100, 46, 112, 46, 116, 105, 100, 61, 54, 53, 97, 49, 51, 51, 99, 50, 48, 48, 48, 48, 48, 48, 48, 48]), RecordHeader(key = traceparent, value = [48, 48, 45, 54, 53, 97, 49, 51, 51, 99, 50, 48, 48, 48, 48, 48, 48, 48, 48, 53, 99, 50, 52, 97, 55, 97, 49, 56, 57, 56, 52, 51, 102, 50, 49, 45, 51, 55, 100, 49, 55, 51, 98, 48, 57, 53, 55, 57, 97, 54, 50, 52, 45, 48, 49]), RecordHeader(key = tracestate, value = [100, 100, 61, 115, 58, 49, 59, 116, 46, 100, 109, 58, 45, 49, 59, 116, 46, 116, 105, 100, 58, 54, 53, 97, 49, 51, 51, 99, 50, 48, 48, 48, 48, 48, 48, 48, 48])], isReadOnly = false), key = [B@79b10d8, value = [B@2e776055).
	at org.apache.flink.connector.kafka.source.reader.deserializer.KafkaDeserializationSchemaWrapper.deserialize(KafkaDeserializationSchemaWrapper.java:57)
	at org.apache.flink.connector.kafka.source.reader.KafkaRecordEmitter.emitRecord(KafkaRecordEmitter.java:53)
	... 14 more
Caused by: java.io.IOException: Failed to deserialize Avro record.
	at org.apache.flink.formats.avro.AvroRowDataDeserializationSchema.deserialize(AvroRowDataDeserializationSchema.java:106)
	at org.apache.flink.formats.avro.AvroRowDataDeserializationSchema.deserialize(AvroRowDataDeserializationSchema.java:46)
	at org.apache.flink.api.common.serialization.DeserializationSchema.deserialize(DeserializationSchema.java:82)
	at org.apache.flink.streaming.connectors.kafka.table.DynamicKafkaDeserializationSchema.deserialize(DynamicKafkaDeserializationSchema.java:130)
	at org.apache.flink.connector.kafka.source.reader.deserializer.KafkaDeserializationSchemaWrapper.deserialize(KafkaDeserializationSchemaWrapper.java:54)
	... 15 more
Caused by: org.apache.avro.AvroTypeException: Found com.cloudbeds.AccountingService.SourceKindEnum, expecting string
	at org.apache.avro.io.ResolvingDecoder.doAction(ResolvingDecoder.java:308)
	at org.apache.avro.io.parsing.Parser.advance(Parser.java:86)
	at org.apache.avro.io.ResolvingDecoder.readString(ResolvingDecoder.java:203)
	at org.apache.avro.generic.GenericDatumReader.readString(GenericDatumReader.java:470)
	at org.apache.avro.generic.GenericDatumReader.readString(GenericDatumReader.java:460)
	at org.apache.avro.generic.GenericDatumReader.readWithoutConversion(GenericDatumReader.java:192)
	at org.apache.avro.generic.GenericDatumReader.read(GenericDatumReader.java:161)
	at org.apache.avro.generic.GenericDatumReader.readField(GenericDatumReader.java:260)
	at org.apache.avro.generic.GenericDatumReader.readRecord(GenericDatumReader.java:248)
	at org.apache.avro.generic.GenericDatumReader.readWithoutConversion(GenericDatumReader.java:180)
	at org.apache.avro.generic.GenericDatumReader.read(GenericDatumReader.java:161)
	at org.apache.avro.generic.GenericDatumReader.read(GenericDatumReader.java:154)
	at org.apache.flink.formats.avro.RegistryAvroDeserializationSchema.deserialize(RegistryAvroDeserializationSchema.java:81)
	at org.apache.flink.formats.avro.AvroRowDataDeserializationSchema.deserialize(AvroRowDataDeserializationSchema.java:103)
g
Did you set
value.avro-confluent.fallback-schema = '<schema-subject>'
? When it is set when resolving string types it will use latest version of that schema
j
I have rewritten
SchemaRegistryTableCatalog
to:
Copy code
public class SchemaRegistryTableCatalog extends ReadOnlyTableCatalog {
    ...

    private Map<String, String> generateTableProperties(ObjectPath tablePath, Schema tableSchema) {
        // TODO: Validate config

        var schemaRegistryUrl = catalogConfig.get("schema.registry.url");
        var schemaRegistryBasicAuthCredentialsSource = catalogConfig.get("schema.registry.basic.auth.credentials.source");
        var schemaRegistryBasicAuthUserInfo = catalogConfig.get("schema.registry.basic.auth.user.info");

        var tableProperties = catalogConfig
            .entrySet()
            .stream()
            .filter(entry -> entry.getKey().startsWith("table."))
            .map(entry -> {
                var key = entry.getKey().replace("table.", "");
                var value = entry.getValue();
                return Map.entry(key, value);
            })
            .collect(Collectors.toMap(Entry::getKey, Entry::getValue));

        var schemaRegistryProperties = new HashMap<>(Map.ofEntries(
                Map.entry("topic", getTableTopicName(tablePath)),
                // SR Key
                Map.entry("key.format", "avro-confluent"),
                Map.entry("key.avro-confluent.url", schemaRegistryUrl),
                Map.entry("key.avro-confluent.basic-auth.credentials-source", schemaRegistryBasicAuthCredentialsSource),
                Map.entry("key.avro-confluent.basic-auth.user-info", schemaRegistryBasicAuthUserInfo),
                Map.entry("value.fields-include", "EXCEPT_KEY"),
                // SR Value
                Map.entry("value.format", "avro-confluent"),
                Map.entry("value.avro-confluent.url", schemaRegistryUrl),
                Map.entry("value.avro-confluent.basic-auth.credentials-source", schemaRegistryBasicAuthCredentialsSource),
                Map.entry("value.avro-confluent.basic-auth.user-info", schemaRegistryBasicAuthUserInfo)
        ));

       ...
}
g
Here is an example. From your snippet you are missing the additional config I mentioned earlier|
Copy code
CREATE TABLE some_table (
        the_kafka_key STRING,
        some_enum STRING,
      ) WITH (
        'connector' = 'kafka',
        'topic' = 'kafka-topic',
        'scan.startup.mode' = 'earliest-offset',
        'scan.bounded.mode' = 'latest-offset',
        'properties.bootstrap.servers' = 'bootstrap-server:9092',
        'key.format' = 'raw',
        'key.fields' = 'the_kafka_key',
        'value.format' = 'avro-confluent',
        'value.avro-confluent.url' = 'https://schema-registry.com'
        'value.avro-confluent.fallback-schema' = 'schema-subject'
      );
j
Thanks! Got it. Then I need to fetch
value.avro-confluent.fallback-schema
in my SQL Java migrations app that inherits that config and sets it up. I'm still not understanding what should be the value of
schema-subject
? Is this a generic schema?
g
it is schema subject name. It will use this to call confluent registry api https://docs.confluent.io/platform/current/schema-registry/develop/api.html#get--subjects-(string-%20subject)-versions-(versionId-%20version)-schema to get the schema so it could resolve enum schema
j
@Gintaras Matulas Could you join a quick call? Won't take too much of your time. Would be super helpful if you could but also understand if you can't. Thanks.
I'm not using KAFKA connector too (don't know if that helps). I read from a KAFKA topic, transform the data and write it to a JDBC database (postgres).
Copy code
CREATE CATALOG pg WITH (
    'type' = 'jdbc',
    'default-database' = '${POSTGRES_NAME}',
    'username' = '${POSTGRES_USER}',
    'password' = '${POSTGRES_PASSWORD}',
    'base-url' = 'jdbc:postgresql://postgres:${POSTGRES_PORT}'
);
The issue is before that step. The issue is when it reads from SR directly.
Copy code
CREATE CATALOG sr WITH (
    'type' = 'schema-registry',
    'island' = '${ISLAND}',
    'schema.registry.url' = '${SCHEMA_REGISTRY_URL}',
    'schema.registry.basic.auth.credentials.source' = 'USER_INFO',
    'schema.registry.basic.auth.user.info' = '${SCHEMA_REGISTRY_USER}:${SCHEMA_REGISTRY_PASSWORD}',
    'table.connector' = 'upsert-kafka',
    'table.properties.bootstrap.servers' = '${KAFKA_BROKER}',
    'table.properties.security.protocol' = 'SASL_SSL',
    'table.properties.sasl.mechanism' = 'PLAIN',
    'table.properties.sasl.jaas.config' = 'org.apache.kafka.common.security.plain.PlainLoginModule required username="${KAFKA_SASL_USER}" password="${KAFKA_SASL_PASSWORD}";'
);
@Gintaras Matulas Can you join a quick call?
g
Maybe we can do it tomorrow. Depends on my availability. I am not very familiar with flink sql. For my change to work • You need to use confluent schema registry integration with kafka • schema subject probably will be
<topic name>-value
• Don’t forget to add this config
value.avro-confluent.fallback-schema' = 'schema-subject
j
Hey @Gintaras Matulas. I have been sick for some days. I ended up doing your config but still could never get this to work: There's a 401 when getting the fallback schema:
Copy code
2024-04-24 15:55:26     at org.apache.flink.formats.avro.registry.confluent.RegistryAvroFormatFactory.lambda$getFallbackSchema$0(RegistryAvroFormatFactory.java:184)
2024-04-24 15:55:26     at java.base/java.util.Optional.map(Unknown Source)
2024-04-24 15:55:26     at org.apache.flink.formats.avro.registry.confluent.RegistryAvroFormatFactory.getFallbackSchema(RegistryAvroFormatFactory.java:179)
2024-04-24 15:55:26     at org.apache.flink.formats.avro.registry.confluent.RegistryAvroFormatFactory.access$000(RegistryAvroFormatFactory.java:83)
2024-04-24 15:55:26     at org.apache.flink.formats.avro.registry.confluent.RegistryAvroFormatFactory$1.createRuntimeDecoder(RegistryAvroFormatFactory.java:106)
2024-04-24 15:55:26     at org.apache.flink.formats.avro.registry.confluent.RegistryAvroFormatFactory$1.createRuntimeDecoder(RegistryAvroFormatFactory.java:97)
2024-04-24 15:55:26     at org.apache.flink.table.connector.format.ProjectableDecodingFormat.createRuntimeDecoder(ProjectableDecodingFormat.java:66)
2024-04-24 15:55:26     at org.apache.flink.streaming.connectors.kafka.table.UpsertKafkaDynamicTableFactory$DecodingFormatWrapper.createRuntimeDecoder(UpsertKafkaDynamicTableFactory.java:349)
2024-04-24 15:55:26     at org.apache.flink.streaming.connectors.kafka.table.UpsertKafkaDynamicTableFactory$DecodingFormatWrapper.createRuntimeDecoder(UpsertKafkaDynamicTableFactory.java:331)
2024-04-24 15:55:26     at org.apache.flink.streaming.connectors.kafka.table.KafkaDynamicSource.createDeserialization(KafkaDynamicSource.java:568)
2024-04-24 15:55:26     at org.apache.flink.streaming.connectors.kafka.table.KafkaDynamicSource.getScanRuntimeProvider(KafkaDynamicSource.java:244)
2024-04-24 15:55:26     at org.apache.flink.table.planner.connectors.DynamicSourceUtils.validateScanSource(DynamicSourceUtils.java:478)
2024-04-24 15:55:26     at org.apache.flink.table.planner.connectors.DynamicSourceUtils.prepareDynamicSource(DynamicSourceUtils.java:161)
2024-04-24 15:55:26     at org.apache.flink.table.planner.connectors.DynamicSourceUtils.convertSourceToRel(DynamicSourceUtils.java:125)
2024-04-24 15:55:26     at org.apache.flink.table.planner.plan.schema.CatalogSourceTable.toRel(CatalogSourceTable.java:118)
2024-04-24 15:55:26     at org.apache.calcite.sql2rel.SqlToRelConverter.toRel(SqlToRelConverter.java:4002)
2024-04-24 15:55:26     at org.apache.calcite.sql2rel.SqlToRelConverter.convertIdentifier(SqlToRelConverter.java:2872)
2024-04-24 15:55:26     at org.apache.calcite.sql2rel.SqlToRelConverter.convertFrom(SqlToRelConverter.java:2432)
2024-04-24 15:55:26     at org.apache.calcite.sql2rel.SqlToRelConverter.convertFrom(SqlToRelConverter.java:2346)
2024-04-24 15:55:26     at org.apache.calcite.sql2rel.SqlToRelConverter.convertFrom(SqlToRelConverter.java:2291)
2024-04-24 15:55:26     at org.apache.calcite.sql2rel.SqlToRelConverter.convertJoin(SqlToRelConverter.java:3271)
2024-04-24 15:55:26     at org.apache.calcite.sql2rel.SqlToRelConverter.convertFrom(SqlToRelConverter.java:2451)
2024-04-24 15:55:26     at org.apache.calcite.sql2rel.SqlToRelConverter.convertFrom(SqlToRelConverter.java:2291)
2024-04-24 15:55:26     at org.apache.calcite.sql2rel.SqlToRelConverter.convertSelectImpl(SqlToRelConverter.java:728)
2024-04-24 15:55:26     at org.apache.calcite.sql2rel.SqlToRelConverter.convertSelect(SqlToRelConverter.java:714)
2024-04-24 15:55:26     at org.apache.calcite.sql2rel.SqlToRelConverter.convertQueryRecursive(SqlToRelConverter.java:3848)
2024-04-24 15:55:26     at org.apache.calcite.sql2rel.SqlToRelConverter.convertQuery(SqlToRelConverter.java:618)
@Gintaras Matulas Do you have any idea on what's going on to get 401?
@Gintaras Matulas I'm sorry for insisting but I'm still having the same issue.
g
Does your schema registry requires authorization ? I don’t think that I handle that now
j
Yes. It's CC Schema Registry. Shouldn't you reuse the class which pulls Schemas out of the box?
g
Pushed a fix. Now it should reuse config.
j
Thanks @Gintaras Matulas. I couldn't build your project now:
Copy code
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  3.410 s
[INFO] Finished at: 2024-05-03T12:09:41+01:00
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal com.diffplug.spotless:spotless-maven-plugin:2.27.1:check (spotless-check) on project flink-avro-confluent-registry: The following files had format violations:
[ERROR]     src/main/java/org/apache/flink/formats/avro/registry/confluent/RegistryAvroFormatFactory.java
[ERROR]         @@ -104,7 +104,9 @@
[ERROR]          ················final·RowType·rowType·=·(RowType)·producedDataType.getLogicalType();
[ERROR]          ················String·fallbackSchema·=
[ERROR]          ························getFallbackSchema(
[ERROR]         -································schemaRegistryURL,·optionalPropertiesMap,·formatOptions.getOptional(FALLBACK_SCHEMA));
[ERROR]         +································schemaRegistryURL,
[ERROR]         +································optionalPropertiesMap,
[ERROR]         +································formatOptions.getOptional(FALLBACK_SCHEMA));
[ERROR]          ················final·Schema·schema·=
[ERROR]          ························schemaString
[ERROR]          ································.map(s·->·getAvroSchema(s,·rowType))
[ERROR]         @@ -138,7 +140,10 @@
[ERROR]          ········Map<String,·?>·optionalPropertiesMap·=·buildOptionalPropertiesMap(formatOptions);
[ERROR]
[ERROR]          ········String·fallbackSchema·=
[ERROR]         -················getFallbackSchema(schemaRegistryURL,·optionalPropertiesMap,·formatOptions.getOptional(FALLBACK_SCHEMA));
[ERROR]         +················getFallbackSchema(
[ERROR]         +························schemaRegistryURL,
[ERROR]         +························optionalPropertiesMap,
[ERROR]         +························formatOptions.getOptional(FALLBACK_SCHEMA));
[ERROR]
[ERROR]          ········if·(!subject.isPresent())·{
[ERROR]          ············throw·new·ValidationException(
[ERROR]         @@ -172,7 +177,10 @@
[ERROR]          ········};
[ERROR]          ····}
[ERROR]
[ERROR]         -····private·String·getFallbackSchema(String·schemaRegistryURL,·@Nullable·Map<String,·?>·registryConfigs,·Optional<String>·fallbackSchema)·{
[ERROR]         +····private·String·getFallbackSchema(
[ERROR]         +············String·schemaRegistryURL,
[ERROR]         +············@Nullable·Map<String,·?>·registryConfigs,
[ERROR]         +············Optional<String>·fallbackSchema)·{
[ERROR]          ········CachedSchemaRegistryClient·client·=
[ERROR]          ················new·CachedSchemaRegistryClient(schemaRegistryURL,·10,·registryConfigs);
[ERROR]          ········return·fallbackSchema
[ERROR] Run 'mvn spotless:apply' to fix these violations.
g
forgot to format the code. Now it should work
j
Thanks! It's working but still getting the same:
Caused by: org.apache.avro.AvroTypeException: Found com.cloudbeds.AccountingService.SourceKindEnum, expecting union
.
It seems your fork isn’t working properly or still missing something.
@Gintaras Matulas Thoughts?