1 package org.wikimedia.eventutilities.flink.table;
2
3 import static java.util.Collections.emptyMap;
4
5 import java.util.HashMap;
6 import java.util.List;
7 import java.util.Map;
8
9 import javax.annotation.Nonnull;
10 import javax.annotation.ParametersAreNonnullByDefault;
11
12 import org.apache.flink.table.api.Schema;
13 import org.apache.flink.table.api.TableDescriptor;
14 import org.wikimedia.eventutilities.core.event.EventStream;
15 import org.wikimedia.eventutilities.core.event.EventStreamFactory;
16
17 import com.google.common.base.Preconditions;
18
19
20 /**
21 * Builder wrapper to aid in constructing Flink TableDescriptors
22 * using Wikimedia Event Streams. TableDescriptors are passed
23 * to the Flink TableEnvironment when instantiating Table objects
24 * or when creating tables in a catalog.
25 *
26 * This class uses EventStreamFactory to get information
27 * about Event Streams declared in EventStreamConfig, e.g.
28 * schema and topics.
29 *
30 * You must at minimum call eventStream() and connector() before
31 * calling build().
32 *
33 * It is possible to pass in your own Flink Schema.Builder
34 * while using this wrapper. If you need to augment the schema, for example
35 * to add computed / virtual fields, calling getSchemaBuilder()
36 * will get you the Schema.Builder with the stream's schema set as
37 * the physical DataType. After modifying the Schema.Builder as desired,
38 * call schemaBuilder(modifiedSchemaBuilder) again to use it for the
39 * TableDescriptor that will be built.
40 *
41 * Examples:
42 *
43 * Instantiate a EventTableDescriptorBuilder from URIs:
44 * <pre>{@code
45 * EventTableDescriptorBuilder builder = EventTableDescriptorBuilder.from(
46 * Arrays.asList(
47 * "https://schema.wikimedia.org/repositories/primary/jsonschema",
48 * "https://schema.wikimedia.org/repositories/secondary/jsonschema",
49 * ),
50 * "https://meta.wikimedia.org/w/api.php"
51 * );
52 * }</pre>
53 *
54 * Build a DataGen Table:
55 * <pre>{@code
56 * Table t = tableEnv.from(
57 * builder
58 * .connector("datagen")
59 * .eventStream("mediawiki.page-create")
60 * .option("number-of-rows", "10")
61 * .build()
62 * )
63 * );
64 * }</pre>
65 *
66 * Build a Kafka Table:
67 * <pre>{@code
68 * Table t = tableEnv.from(
69 * builder
70 * .eventStream("mediawiki.page-create")
71 * .setupKafka(
72 * "localhost:9092",
73 * "my_consumer_group",
74 * true // If should auto-add a kafka_timestamp watermark virtual field.
75 * )
76 * .build()
77 * )
78 * );
79 * }</pre>
80 *
81 */
82 @ParametersAreNonnullByDefault
83 public class EventTableDescriptorBuilder {
84 private final EventStreamFactory eventStreamFactory;
85
86 private EventStream eventStream;
87
88 private String connectorIdentifier;
89 private String formatIdentifier;
90 private String[] partitionKeys;
91 private Schema.Builder schemaBuilder;
92 private Map<String, String> options;
93
94 // We want to default to using ISO-8601 timestamp format, not SQL,
95 // since WMF Event Platform timestamps are ISO-8601 formatted strings.
96 private static final String JSON_TIMESTAMP_FORMAT_KEY = "json.timestamp-format.standard";
97 private static final String JSON_TIMESTAMP_FORMAT_DEFAULT = "ISO-8601";
98
99 public EventTableDescriptorBuilder(EventStreamFactory eventStreamFactory) {
100 this.eventStreamFactory = eventStreamFactory;
101 this.clear();
102 }
103
104 /**
105 * EventTableDescriptorBuilder factory method.
106 *
107 * @param eventSchemaBaseUris
108 * URIs from which to fetch event JSONSchemas.
109 *
110 * @param eventStreamConfigUri
111 * URI from which to fetch event stream config.
112 */
113 @Nonnull
114 public static EventTableDescriptorBuilder from(
115 List<String> eventSchemaBaseUris,
116 String eventStreamConfigUri
117 ) {
118 return EventTableDescriptorBuilder.from(
119 eventSchemaBaseUris, eventStreamConfigUri, emptyMap()
120 );
121 }
122
123 /**
124 * EventTableDescriptorBuilder factory method.
125 *
126 * @param eventSchemaBaseUris
127 * URIs from which to fetch event JSONSchemas.
128 *
129 * @param eventStreamConfigUri
130 * URI from which to fetch event stream config.
131 *
132 * @param httpClientRoutes
133 * Map of source to dest http client routes.
134 * E.g. "https://meta.wikimedia.org" to "https://api-ro.wikimedia.org"
135 * If null, no special routing will be configured.
136 */
137 @Nonnull
138 public static EventTableDescriptorBuilder from(
139 List<String> eventSchemaBaseUris,
140 String eventStreamConfigUri,
141 Map<String, String> httpClientRoutes
142 ) {
143 return new EventTableDescriptorBuilder(
144 EventStreamFactory.from(
145 eventSchemaBaseUris, eventStreamConfigUri, httpClientRoutes
146 )
147 );
148 }
149
150 /**
151 * Convenience method to get the EventStreamFactory used
152 * by this EventTableDescriptorBuilder.
153 */
154 @Nonnull
155 public EventStreamFactory getEventStreamFactory() {
156 return eventStreamFactory;
157 }
158
159 /**
160 * Sets the connector.
161 *
162 * @param connectorIdentifier
163 * A valid and registered Flink Table Connector Factory Identifier string.
164 * e.g. "kafka" or "filesystem".
165 */
166 @Nonnull
167 public EventTableDescriptorBuilder connector(String connectorIdentifier) {
168 this.connectorIdentifier = connectorIdentifier;
169 return this;
170 }
171
172 /**
173 * Sets the EventStream that will be used to build the TableDescriptor.
174 */
175 @Nonnull
176 public EventTableDescriptorBuilder eventStream(EventStream eventStream) {
177 this.eventStream = eventStream;
178 return this;
179 }
180
181 /**
182 * Sets the EventStream by streamName that will be used to build the TableDescriptor.
183 *
184 * @param streamName
185 * Name of the EventStream, must be declared in EventStreamConfig.
186 */
187 @Nonnull
188 public EventTableDescriptorBuilder eventStream(String streamName) {
189 return eventStream(eventStreamFactory.createEventStream(streamName));
190 }
191
192 /**
193 * Sets the Schema.Builder. If you don't set this the Table Schema will be
194 * converted from the eventStream's JSONSchema.
195 */
196 @Nonnull
197 public EventTableDescriptorBuilder schemaBuilder(Schema.Builder schemaBuilder) {
198 this.schemaBuilder = schemaBuilder;
199 return this;
200 }
201
202 /**
203 * Sets the TableDescriptor.Builder options.
204 * This clears out any previously set options.
205 */
206 @Nonnull
207 public EventTableDescriptorBuilder options(Map<String, String> options) {
208 this.options = new HashMap<>(options);
209 return this;
210 }
211
212 /**
213 * Sets a single TableDescriptor.Builder option.
214 */
215 @Nonnull
216 public EventTableDescriptorBuilder option(String key, String value) {
217 this.options.put(key, value);
218 return this;
219 }
220
221 /**
222 * Sets the format for the TableDescriptor.Builder.
223 * This needed by most, but not all, connectors.
224 */
225 @Nonnull
226 public EventTableDescriptorBuilder format(String format) {
227 this.formatIdentifier = format;
228 return this;
229 }
230
231 /**
232 * Sets the partitionKeys for the TableDescriptor.Builder.
233 */
234 @Nonnull
235 public EventTableDescriptorBuilder partitionedBy(String... partitionKeys) {
236 this.partitionKeys = partitionKeys;
237 return this;
238 }
239
240 /**
241 * Helper to aid in setting up a kafka connector for the EventStream.
242 * You must first call eventStream() before calling this method so that
243 * it can fill in the details for the connector from the EventStream.
244 *
245 * Note: The Kafka Table Connector option scan.start.mode will not be set,
246 * relying on the default value of "group-offsets".
247 * The Kafka consumer property auto.offset.reset will be set to "latest",
248 * which will be used in the case that there are no committed group offsets.
249 * Override this behavior by calling e.g.
250 * {@code option("properties.auto.offset.reset", "earliest")}
251 *
252 * This does not set the key format or hoist any metadata fields
253 * (like kafka_timestamp) into the schema.
254 * See withKafkaTimestampAsWatermark to help use the kafka timestamp
255 * as the watermark.
256 *
257 * @param bootstrapServers
258 * Kafka bootstrap.servers property.
259 *
260 * @param consumerGroup
261 * Kafka consumer.group.id property.
262 *
263 */
264 @Nonnull
265 public EventTableDescriptorBuilder setupKafka(
266 String bootstrapServers,
267 String consumerGroup
268 ) {
269 Preconditions.checkState(
270 this.eventStream != null,
271 "Must call eventStream() before calling setupKafka()."
272 );
273
274 connector("kafka");
275 // EventStreams in Kafka are JSON.
276 format("json");
277
278 option("properties.bootstrap.servers", bootstrapServers);
279 option("topic", String.join(";", eventStream.topics()));
280 option("properties.group.id", consumerGroup);
281 option("properties.auto.offset.reset", "latest");
282
283 return this;
284 }
285
286 /**
287 * Adds a "kafka_timestamp" column to the schema and uses
288 * it as the watermark field with a default watermark delay of 10 seconds.
289 */
290 @Nonnull
291 public EventTableDescriptorBuilder withKafkaTimestampAsWatermark() {
292 return schemaBuilder(
293 SchemaBuilderUtil.withKafkaTimestampAsWatermark(getSchemaBuilder())
294 );
295 }
296
297 /**
298 * Adds kafka timestamp as a virtual column to the schema,
299 * and uses it as the watermark with a delay of watermarkDelaySeconds.
300 *
301 * @param columnName
302 * Name of the timestamp column to add to the schema.
303
304 * @param watermarkDelaySeconds
305 * Seconds to delay the watermark by.
306 *
307 */
308 @Nonnull
309 public EventTableDescriptorBuilder withKafkaTimestampAsWatermark(
310 String columnName,
311 int watermarkDelaySeconds
312 ) {
313 return schemaBuilder(
314 SchemaBuilderUtil.withKafkaTimestampAsWatermark(
315 getSchemaBuilder(),
316 columnName,
317 watermarkDelaySeconds
318 )
319 );
320 }
321
322 /**
323 * Adds kafka timestamp as a virtual column to the schema,
324 * and uses it as the watermark.
325 * See also {@link Schema.Builder#watermark(String, String)}
326 *
327 * @param columnName
328 * Name of the column to add to the schema.
329 *
330 * @param sqlExpression
331 * SQL expression to use for the watermark.
332 * This should probably refer to the columnName, e.g. "$columnName - INTERVAL '30' seconds"
333 *
334 */
335 @Nonnull
336 public EventTableDescriptorBuilder withKafkaTimestampAsWatermark(
337 String columnName,
338 String sqlExpression
339 ) {
340 return schemaBuilder(
341 SchemaBuilderUtil.withKafkaTimestampAsWatermark(
342 getSchemaBuilder(),
343 columnName,
344 sqlExpression
345 )
346 );
347 }
348
349 /**
350 * Use this to get the schemaBuilder for the eventStream
351 * in order to augment and reset it before calling build().
352 * If you change the Schema.Builder, make sure you call
353 * {@code schemaBuilder(modifiedSchemaBuilder)} to apply your changes
354 * before calling {@code build()}.
355 *
356 * @return
357 * The Schema.Builder that will be used to build the Table Schema.
358 */
359 @Nonnull
360 public Schema.Builder getSchemaBuilder() {
361 Preconditions.checkState(
362 !(this.eventStream == null && this.schemaBuilder == null),
363 "Must call eventStream() or schemaBuilder() before calling getSchemaBuilder()."
364 );
365
366 if (this.schemaBuilder == null) {
367 this.schemaBuilder = SchemaBuilderUtil.createEventStreamSchemaBuilder(eventStream);
368 }
369
370 return this.schemaBuilder;
371 }
372
373 /**
374 * Applies all the collected configs and options to
375 * build a TableDescriptor using information from the EventStream.
376 * You can use the returned TableDescriptor to instantiate a Table object
377 * or create a Table in a catalog.
378 *
379 * Any collected state will be cleared before returning, so you
380 * can re-use this EventTableDescriptorBuilder again.
381 */
382 @Nonnull
383 public TableDescriptor build() {
384 Preconditions.checkState(
385 connectorIdentifier != null,
386 "Must call connector() before calling build()."
387 );
388 Preconditions.checkState(
389 eventStream != null,
390 "Must call eventStream() before calling build()."
391 );
392
393 TableDescriptor.Builder tdb = TableDescriptor.forConnector(connectorIdentifier)
394 .schema(getSchemaBuilder().build())
395 .comment(eventStream.toString());
396
397 // Not all connectors use format.
398 if (formatIdentifier != null) {
399 tdb.format(formatIdentifier);
400 }
401
402 if (partitionKeys != null) {
403 tdb.partitionedBy(partitionKeys);
404 }
405
406 // If not specified, set the JSON timestamp format to our default.
407 if (!options.containsKey(JSON_TIMESTAMP_FORMAT_KEY)) {
408 options.put(JSON_TIMESTAMP_FORMAT_KEY, JSON_TIMESTAMP_FORMAT_DEFAULT);
409 }
410
411 options.forEach(tdb::option);
412
413 TableDescriptor td = tdb.build();
414 this.clear();
415 return td;
416 }
417
418 /**
419 * Clears all collected configs and options from this EventTableDescriptorBuilder
420 * so that it can be used to build another TableDescriptor.
421 */
422 @Nonnull
423 public final EventTableDescriptorBuilder clear() {
424 this.options = new HashMap<>();
425 this.eventStream = null;
426 this.connectorIdentifier = null;
427 this.formatIdentifier = null;
428 this.partitionKeys = null;
429 this.schemaBuilder = null;
430
431 return this;
432 }
433
434 }