1 package org.wikimedia.eventutilities.flink.formats.json;
2
3 import java.util.Map;
4
5 import javax.annotation.Nonnull;
6 import javax.annotation.ParametersAreNonnullByDefault;
7
8 import org.apache.flink.api.common.typeinfo.TypeInformation;
9 import org.apache.flink.api.java.typeutils.RowTypeInfo;
10 import org.apache.flink.table.api.Schema;
11 import org.apache.flink.table.types.DataType;
12 import org.apache.flink.table.types.logical.LogicalType;
13 import org.apache.flink.table.types.logical.LogicalTypeRoot;
14 import org.wikimedia.eventutilities.core.event.types.JsonSchemaConverter;
15 import org.wikimedia.eventutilities.flink.EventRowTypeInfo;
16
17 import com.fasterxml.jackson.databind.ObjectMapper;
18 import com.fasterxml.jackson.databind.node.ObjectNode;
19
20 /**
21 * Converts from JSONSchemas to Flink types.
22 *
23 * Adheres to a few Event Platform specific schema conventions,
24 * specifically support for specifying Map types in JSONSchema
25 * via additionalProperties schema.
26 *
27 * Example:
28 * Create a streaming Table from JSON data in a Kafka topic using a JSONSchema.
29 * <pre>{@code
30 * ObjectNode jsonSchema = # ... Get this somehow, perhaps from EventStream schema() method.
31 *
32 * # This schemaBuilder will already have the DataType set via the JSONSchema.
33 * Schema.Builder schemaBuilder = JsonSchemaFlinkConverter.toSchemaBuilder(jsonSchema);
34 *
35 * # Add the kafka_timestamp as the metadata column and use it as the watermark.
36 * schemaBuilder.columnByMetadata(
37 * "kafka_timestamp",
38 * "TIMESTAMP_LTZ(3) NOT NULL",
39 * "timestamp",
40 * true
41 * );
42 * schemaBuilder.watermark("kafka_timestamp", "kafka_timestamp");
43 *
44 * # Create a Dynamic Table from this topic in Kafka.
45 * stEnv.createTemporaryTable(
46 * "my_table",
47 * TableDescriptor.forConnector("kafka")
48 * .schema(schemaBuilderlder.build())
49 * .option("properties.bootstrap.servers", "localhost:9092")
50 * .option("topic", "my_stream_topic")
51 * .option("properties.group.id", "my_consumer_group0")
52 * .option("scan.startup.mode", "latest-offset")
53 * .format("json")
54 * .build()
55 * )
56 * }</pre>
57 *
58 * Or, get the RowTypeInfo (AKA TypeInformation of Row) corresponding to an event JSONSchema.
59 * <pre>{@code
60 * ObjectNode jsonSchema = # ... Get this somehow, perhaps from EventStream schema() method.
61 * RowTypeInfo eventSchemaTypeInfo = JsonSchemaFlinkConverter.toRowTypeInfo(jsonSchema);
62 * }</pre>
63 */
64 @ParametersAreNonnullByDefault
65 public final class JsonSchemaFlinkConverter {
66
67 /**
68 * JsonSchemaConverter instance to convert to Flink Table API DataType.
69 */
70 private static final JsonSchemaConverter<DataType> DATA_TYPE_CONVERTER =
71 new JsonSchemaConverter<>(new DataTypeSchemaConversions());
72
73 /**
74 * JsonSchemaConverter to convert to Flink DataStream API TypeInformation.
75 */
76 private static final JsonSchemaConverter<TypeInformation<?>> TYPE_INFORMATION_CONVERTER =
77 new JsonSchemaConverter<>(new TypeInformationSchemaConversions());
78
79 /**
80 * Returns a Table API Schema Builder starting with a Row DataType
81 * converted from the provided JSONSchema.
82 *
83 * @param jsonSchema
84 * The JSONSchema ObjectNode. This should have "type": "object"
85 * to properly convert to a logical
86 * {@link org.apache.flink.table.types.logical.RowType}
87 *
88 * @throws IllegalArgumentException
89 * if the JSONSchema is not on "object" type.
90 *
91 * @return
92 * {@link org.apache.flink.table.api.Schema.Builder}
93 * with DataType with logical RowType as schema.
94 */
95 @Nonnull
96 public static Schema.Builder toSchemaBuilder(ObjectNode jsonSchema) {
97 JsonSchemaConverter.checkJsonSchemaIsObject(jsonSchema);
98
99 DataType dataType = toDataType(jsonSchema);
100
101 // Assert that the converted DataType's LogicalType is of type Row.
102 LogicalType logicalType = dataType.getLogicalType();
103 if (!logicalType.is(LogicalTypeRoot.ROW)) {
104 throw new IllegalStateException(
105 "Converted JSONSchema to Flink LogicalType " + logicalType +
106 " but expected " + LogicalTypeRoot.ROW + ". This should not happen."
107 );
108 }
109
110 Schema.Builder builder = Schema.newBuilder();
111 builder.fromRowDataType(dataType);
112 return builder;
113 }
114
115 /**
116 * Converts this JSONSchema to a Flink Table API DataType.
117 *
118 * @param jsonSchema
119 * The JSONSchema ObjectNode. This should have at minimum type.
120 *
121 * @return
122 * jsonSchema converted to
123 * {@link DataType}
124 */
125 @Nonnull
126 public static DataType toDataType(ObjectNode jsonSchema) {
127 return DATA_TYPE_CONVERTER.convert(jsonSchema);
128 }
129
130 /**
131 * Converts this JSONSchema to a Flink DataStream API TypeInformation.
132 *
133 * @param jsonSchema
134 * The JSONSchema ObjectNode. This should have at minimum "type".
135 *
136 * @return
137 * jsonSchema converted to {@link TypeInformation}
138 */
139 @Nonnull
140 public static TypeInformation<?> toTypeInformation(ObjectNode jsonSchema) {
141 JsonSchemaConverter.checkJsonSchemaIsObject(jsonSchema);
142 RowTypeInfo typeInfo = (RowTypeInfo) TYPE_INFORMATION_CONVERTER.convert(jsonSchema);
143 return EventRowTypeInfo.create(typeInfo);
144 }
145
146 /**
147 * Converts this JSONSchema to a Flink DataStream API TypeInformation with key TypeInformation
148 * extracted from messageKeyFields mappings.
149 * Returns jsonSchema converted to TypeInformation
150 * @param jsonSchema the JSONSchema ObjectNode. This should have at minimum "type".
151 * @param messageKeyFields message key fields declared in the stream config.
152 * @return
153 */
154 @Nonnull
155 public static TypeInformation<?> toTypeInformation(ObjectNode jsonSchema, ObjectNode messageKeyFields) {
156 JsonSchemaConverter.checkJsonSchemaIsObject(jsonSchema);
157 RowTypeInfo typeInfo = (RowTypeInfo) TYPE_INFORMATION_CONVERTER.convert(jsonSchema);
158 Map<String, String> aliasedRowKey = new ObjectMapper().convertValue(messageKeyFields, Map.class);
159
160 if (aliasedRowKey != null) {
161 return EventRowTypeInfo.create(typeInfo, aliasedRowKey);
162 }
163
164 return EventRowTypeInfo.create(typeInfo);
165 }
166 /**
167 * Converts this JSONSchema to a Flink DataStream API {@link EventRowTypeInfo},
168 * which is an instance of
169 * {@link TypeInformation}<{@link org.apache.flink.types.Row}>.
170 * EventRowTypeInfo has some extra logic for working with TypeInformation
171 * when it represents a {@link org.apache.flink.types.Row}.
172 * You can use RowTypeInfo as if it were a TypeInformation of Row.
173 *
174 * @param jsonSchema
175 * The JSONSchema ObjectNode. his should have "type": "object"
176 * to property convert to
177 * {@link TypeInformation}<{@link org.apache.flink.types.Row}>.
178 *
179 * @throws IllegalArgumentException
180 * if the JSONSchema is not on "object" type.
181
182 * @return
183 * jsonSchema converted to {@link TypeInformation}<{@link org.apache.flink.types.Row}>.
184 */
185 @Nonnull
186 public static EventRowTypeInfo toRowTypeInfo(ObjectNode jsonSchema
187 ) {
188 return (EventRowTypeInfo) toTypeInformation(jsonSchema);
189 }
190
191 /** Converts this JSONSchema to a Flink DataStream API {@link EventRowTypeInfo},
192 * with stream partitions keys extracted from messageKeyFields mappings.
193 *
194 * @param jsonSchema
195 * @param messageKeyFields
196 * @return
197 */
198 @Nonnull
199 public static EventRowTypeInfo toRowTypeInfo(ObjectNode jsonSchema, ObjectNode messageKeyFields
200 ) {
201 return (EventRowTypeInfo) toTypeInformation(jsonSchema, messageKeyFields);
202 }
203
204 /**
205 * Gets a JSON deserializer to Row in hybrid named position mode for the jsonSchema.
206 * Missing fields are allowed (and set to null), and parse errors
207 * are always thrown.
208 *
209 * @param jsonSchema
210 * The JSONSchema ObjectNode. his should have "type": "object"
211 * to property convert to
212 * {@link TypeInformation}<{@link org.apache.flink.types.Row}>.
213 *
214 * @return
215 * DeserializationSchema of Row that can deserialize JSON data for the jsonSchema to a FLink Row.
216 */
217 public static JsonRowDeserializationSchema toDeserializationSchemaRow(
218 @Nonnull ObjectNode jsonSchema
219 ) {
220 return new JsonRowDeserializationSchema.Builder(toRowTypeInfo(jsonSchema)).build();
221 }
222
223 /**
224 * Constructor to make maven checkstyle plugin happy.
225 * See: https://checkstyle.sourceforge.io/config_design.html#HideUtilityClassConstructor
226 */
227 private JsonSchemaFlinkConverter() {}
228
229 }