1 package org.wikimedia.eventutilities.flink;
2
3 import static java.util.function.Function.identity;
4 import static org.wikimedia.eventutilities.core.event.JsonEventGenerator.EVENT_TIME_FIELD;
5 import static org.wikimedia.eventutilities.core.event.JsonEventGenerator.META_FIELD;
6 import static org.wikimedia.eventutilities.core.event.JsonEventGenerator.META_ID_FIELD;
7 import static org.wikimedia.eventutilities.core.event.JsonEventGenerator.META_INGESTION_TIME_FIELD;
8 import static org.wikimedia.eventutilities.core.event.JsonEventGenerator.META_STREAM_FIELD;
9 import static org.wikimedia.eventutilities.core.event.JsonEventGenerator.SCHEMA_FIELD;
10
11 import java.lang.reflect.Array;
12 import java.time.Instant;
13 import java.util.Arrays;
14 import java.util.List;
15 import java.util.LinkedHashMap;
16 import java.util.HashMap;
17 import java.util.Map;
18 import java.util.Objects;
19 import java.util.Set;
20 import java.util.TreeMap;
21 import java.util.function.Function;
22 import java.util.stream.Collectors;
23 import java.util.stream.IntStream;
24
25 import javax.annotation.Nullable;
26
27 import org.apache.flink.api.common.ExecutionConfig;
28 import org.apache.flink.api.common.serialization.SerializerConfig;
29 import org.apache.flink.api.common.typeinfo.TypeInformation;
30 import org.apache.flink.api.common.typeutils.TypeSerializer;
31 import org.apache.flink.api.java.typeutils.MapTypeInfo;
32 import org.apache.flink.api.java.typeutils.ObjectArrayTypeInfo;
33 import org.apache.flink.api.java.typeutils.RowTypeInfo;
34 import org.apache.flink.types.Row;
35 import org.apache.flink.types.RowKind;
36 import org.apache.flink.types.RowUtils;
37
38 import com.google.common.collect.ImmutableSet;
39
40 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
41 import lombok.EqualsAndHashCode;
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57 @EqualsAndHashCode
58 public class EventRowTypeInfo extends RowTypeInfo {
59 private final LinkedHashMap<String, Integer> positionByName;
60
61 private final TreeMap<String, String> aliasedRowKey;
62
63 private EventRowTypeInfo keyTypeInfo;
64
65 public static EventRowTypeInfo create(String[] fieldNames, TypeInformation<?>... types) {
66 return EventRowTypeInfo.create(null, fieldNames, types);
67 }
68
69 public static EventRowTypeInfo create(Map<String, String> aliasedRowKey, String[] fieldNames, TypeInformation<?>... types) {
70 TypeInformation<?>[] fieldTypes = Arrays.stream(types)
71 .map(t -> EventRowTypeInfo.switchRowTypeInfoImpl(t, RowTypeInfo.class, EventRowTypeInfo.class, EventRowTypeInfo::create))
72 .toArray(TypeInformation[]::new);
73 return new EventRowTypeInfo(fieldTypes, fieldNames, aliasedRowKey);
74 }
75
76 public static EventRowTypeInfo create(RowTypeInfo info) {
77 return EventRowTypeInfo.create(info.getFieldNames(), info.getFieldTypes());
78 }
79
80 public static EventRowTypeInfo create(RowTypeInfo info, Map<String, String> aliasedRowKey) {
81 return EventRowTypeInfo.create(aliasedRowKey, info.getFieldNames(), info.getFieldTypes());
82 }
83
84
85
86
87
88
89
90
91 private static <F extends TypeInformation<?>, T extends TypeInformation<?>> TypeInformation<?> switchRowTypeInfoImpl(
92 TypeInformation<?> typeInformation,
93 Class<F> fromClass, Class<T> toClass,
94 Function<F, T> conversion
95 ) {
96 if (toClass.equals(typeInformation.getClass())) {
97 return typeInformation;
98 }
99 if (fromClass.equals(typeInformation.getClass())) {
100 return conversion.apply(fromClass.cast(typeInformation));
101 }
102 if (typeInformation.getClass().equals(MapTypeInfo.class)) {
103 MapTypeInfo<?, ?> mapTypeInfo = (MapTypeInfo<?, ?>) typeInformation;
104 return new MapTypeInfo<>(mapTypeInfo.getKeyTypeInfo(), switchRowTypeInfoImpl(mapTypeInfo.getValueTypeInfo(), fromClass, toClass, conversion));
105 }
106 if (typeInformation.getClass().equals(ObjectArrayTypeInfo.class)) {
107 ObjectArrayTypeInfo<?, ?> arrayTypeInfo = (ObjectArrayTypeInfo<?, ?>) typeInformation;
108 return ObjectArrayTypeInfo.getInfoFor(arrayTypeInfo.getTypeClass(),
109 switchRowTypeInfoImpl(arrayTypeInfo.getComponentInfo(), fromClass, toClass, conversion));
110 }
111 return typeInformation;
112 }
113
114 public EventRowTypeInfo(TypeInformation<?>[] types, String[] fieldNames) {
115 this(types, fieldNames, null);
116 }
117
118 public EventRowTypeInfo(TypeInformation<?>[] types, String[] fieldNames, @Nullable Map<String, String> aliasedRowKey) {
119 super(types, fieldNames);
120 this.positionByName = IntStream.range(0, fieldNames.length)
121 .boxed()
122 .collect(Collectors.toMap(i -> fieldNames[i], identity(), (i, j) -> i, LinkedHashMap::new));
123
124 this.aliasedRowKey = (aliasedRowKey != null) ? new TreeMap<>(aliasedRowKey) : new TreeMap<>();
125 initializeKeyTypeInfo();
126 }
127
128
129
130
131 public RowTypeInfo toRowTypeInfo() {
132 TypeInformation<?>[] fieldTypes = Arrays.stream(types)
133 .map(t -> EventRowTypeInfo.switchRowTypeInfoImpl(t, EventRowTypeInfo.class, RowTypeInfo.class, EventRowTypeInfo::toRowTypeInfo))
134 .toArray(TypeInformation[]::new);
135 return new RowTypeInfo(fieldTypes, fieldNames);
136 }
137
138 @Override
139 public boolean canEqual(Object obj) {
140
141
142 return obj instanceof EventRowTypeInfo;
143 }
144
145
146
147
148
149 public static final Set<String> DEFAULT_NON_PROJECTED_FIELDS = ImmutableSet.of(
150 META_FIELD + "." + META_ID_FIELD,
151 META_FIELD + "." + META_INGESTION_TIME_FIELD,
152 META_FIELD + "." + META_STREAM_FIELD,
153 SCHEMA_FIELD
154 );
155
156
157
158
159 public Row createEmptyRow() {
160 return createRowForFieldPath(null);
161 }
162
163
164
165
166
167
168
169
170 public Row createEmptySubRow(String fieldPath) {
171 return createRowForFieldPath(fieldPath);
172 }
173
174
175
176
177
178 private Row createRowForFieldPath(@Nullable String fieldPath) {
179 if (fieldPath == null) {
180 return RowUtils.createRowWithNamedPositions(RowKind.INSERT, new Object[getArity()], positionByName);
181 }
182 return unwrapRowTypeInfo(this.getTypeAt(fieldPath)).createEmptyRow();
183 }
184
185
186
187
188
189 private EventRowTypeInfo unwrapRowTypeInfo(TypeInformation<?> fieldTypeInfo) {
190
191 if (fieldTypeInfo instanceof MapTypeInfo) {
192 return unwrapRowTypeInfo(((MapTypeInfo<?, ?>) fieldTypeInfo).getValueTypeInfo());
193 } else if (fieldTypeInfo instanceof ObjectArrayTypeInfo<?, ?>) {
194 return unwrapRowTypeInfo(((ObjectArrayTypeInfo<?, ?>) fieldTypeInfo).getComponentInfo());
195 }
196 if (!(fieldTypeInfo instanceof EventRowTypeInfo)) {
197 throw new IllegalArgumentException("Expected a RowTypeInfo");
198 }
199 return (EventRowTypeInfo) fieldTypeInfo;
200 }
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224 @SuppressFBWarnings(
225 value = "SPP_PASSING_THIS_AS_PARM",
226 justification = "We are calling copyRowContent() with different parameter in other places, it makes sense to reuse it with 'this' here.")
227 public Row projectFrom(Row row, boolean intersect, Set<String> ignoredFields) {
228 Row newRow = createEmptyRow();
229 copyRowContent(row, newRow, this, null, intersect, ignoredFields);
230 return newRow;
231 }
232
233
234
235
236
237
238
239
240
241
242
243
244
245 public Row projectFrom(Row row, boolean intersect) {
246 return projectFrom(row, intersect, DEFAULT_NON_PROJECTED_FIELDS);
247 }
248
249
250
251
252
253
254 @SuppressWarnings("checkstyle:CyclomaticComplexity")
255 private boolean copyRowContent(Row source, Row target, RowTypeInfo targetTypeinfo, @Nullable String path, boolean intersect, Set<String> ignoredFields) {
256 Set<String> fieldNames = source.getFieldNames(true);
257 boolean empty = true;
258 if (fieldNames == null) {
259 throw new IllegalArgumentException("Source Row must support named based access");
260 }
261 for (String field: targetTypeinfo.getFieldNames()) {
262 String npath = path != null ? path + "." + field : field;
263 boolean sourceHasField = fieldNames.contains(field);
264
265 if (ignoredFields.contains(npath) || (intersect && !sourceHasField)) {
266 continue;
267 }
268 TypeInformation<?> targetField = targetTypeinfo.getTypeAt(field);
269 if (!intersect && !sourceHasField) {
270 throw new IllegalArgumentException("The source row does not support the field [" + npath + "].");
271 }
272 Object sourceField = source.getField(field);
273 if (sourceField != null) {
274 Object copiedSource = copy(sourceField, targetField, npath, intersect, ignoredFields);
275 if (copiedSource != null) {
276 empty = false;
277 target.setField(field, copy(sourceField, targetField, npath, intersect, ignoredFields));
278 }
279 }
280 }
281 return !empty;
282 }
283
284 private Object copy(Object source, TypeInformation<?> typeInformation, String fieldPath, boolean intersect, Set<String> ignoredFields) {
285 final Object returnValue;
286 if (typeInformation instanceof RowTypeInfo) {
287 Row targetSubfield = createEmptySubRow(fieldPath);
288 boolean copied = copyRowContent((Row) source, targetSubfield, (RowTypeInfo) typeInformation, fieldPath, intersect, ignoredFields);
289
290 returnValue = copied ? targetSubfield : null;
291 } else if (typeInformation instanceof MapTypeInfo) {
292 Map<?, ?> sourceSubfield = (Map<?, ?>) source;
293 TypeInformation<?> valueTypeInfo = ((MapTypeInfo<?, ?>) typeInformation).getValueTypeInfo();
294 Map<Object, Object> targetSubfield = new HashMap<>();
295 for (Map.Entry<?, ?> entry: sourceSubfield.entrySet()) {
296 targetSubfield.put(entry.getKey(), copy(entry.getValue(), valueTypeInfo, fieldPath, intersect, ignoredFields));
297 }
298 returnValue = targetSubfield;
299 } else if (typeInformation instanceof ObjectArrayTypeInfo) {
300 ObjectArrayTypeInfo<?, ?> objectArrayTypeInfo = (ObjectArrayTypeInfo<?, ?>) typeInformation;
301 Object[] sourceArray = (Object[]) source;
302 Object[] targetSubfield = (Object[]) Array.newInstance(objectArrayTypeInfo.getComponentInfo().getTypeClass(), ((Object[]) source).length);
303 for (int i = 0; i < sourceArray.length; i++) {
304 Object sourceMember = sourceArray[i];
305 if (sourceMember != null) {
306 targetSubfield[i] = copy(sourceMember, objectArrayTypeInfo.getComponentInfo(), fieldPath, intersect, ignoredFields);
307 }
308 }
309 returnValue = targetSubfield;
310 } else {
311
312
313 returnValue = source;
314 }
315 return returnValue;
316 }
317
318
319
320
321
322
323
324
325 public void setIngestionTime(Row element, Instant ingestionTime) {
326 if (!this.hasField(META_FIELD)) {
327 throw new IllegalArgumentException("This TypeInformation does not declare the " + META_FIELD + " field");
328 }
329 Row meta = element.getFieldAs(META_FIELD);
330 if (meta == null) {
331 meta = createEmptySubRow(META_FIELD);
332 element.setField(META_FIELD, meta);
333 }
334 meta.setField(META_INGESTION_TIME_FIELD, ingestionTime);
335 }
336
337
338
339
340
341
342 public void setEventTime(Row element, Instant eventTime) {
343 element.setField(EVENT_TIME_FIELD, eventTime);
344 }
345
346
347
348
349
350 @Nullable
351 public Instant getEventTime(Row element) {
352 return element.getFieldAs(EVENT_TIME_FIELD);
353 }
354
355
356
357
358 public Instant getIngestionTime(Row element) {
359 Row meta = element.getFieldAs(META_FIELD);
360 if (meta != null) {
361 return meta.getFieldAs(EVENT_TIME_FIELD);
362 }
363 return null;
364 }
365
366 @Deprecated
367 @Override
368 public TypeSerializer<Row> createSerializer(ExecutionConfig config) {
369 return new EventRowSerializer(
370 Arrays.stream(types).map(t -> t.createSerializer(config))
371 .toArray(TypeSerializer[]::new), positionByName
372 );
373 }
374
375 @Override
376 public TypeSerializer<Row> createSerializer(SerializerConfig config) {
377 return new EventRowSerializer(
378 Arrays.stream(types).map(t -> t.createSerializer(config)).toArray(TypeSerializer[]::new),
379 positionByName
380 );
381 }
382
383
384
385
386
387 public boolean hasKey() {
388 return !aliasedRowKey.isEmpty();
389 }
390
391 private Object getFieldAt(Row row, String fieldPath) {
392 final String fieldPathDelimiter = "\\.";
393 List<String> path = Arrays.stream(fieldPath.split(fieldPathDelimiter)).collect(Collectors.toList());
394 Object target = row;
395
396 for (String field: path) {
397 if (target instanceof Row) {
398 target = ((Row) target).getField(field);
399 } else if (target instanceof Map) {
400 target = ((Map) target).get(field);
401 } else if (target == null) {
402 throw new IllegalArgumentException("Optional (nullable) fields are not allowed in key: " + fieldPath);
403 }
404 }
405 return target;
406 }
407
408
409
410
411
412
413 private TypeInformation<?> unwrapCompositeTypeAt(String fieldPath) {
414 final String fieldPathDelimiter = "\\.";
415 String[] path = fieldPath.split(fieldPathDelimiter);
416
417 TypeInformation<?> fieldType = null;
418
419 StringBuilder visitedFieldPath = new StringBuilder();
420 int i = 0;
421
422 EventRowTypeInfo curRowTypeInfo = this;
423 boolean resetVisitedPath;
424 while (i < path.length) {
425 resetVisitedPath = false;
426 visitedFieldPath.append(path[i]);
427 fieldType = curRowTypeInfo.getTypeAt(String.valueOf(visitedFieldPath));
428 if (fieldType instanceof MapTypeInfo) {
429
430 while (fieldType instanceof MapTypeInfo) {
431 fieldType = ((MapTypeInfo<?, ?>) fieldType).getValueTypeInfo();
432 i++;
433 }
434 }
435
436 if (fieldType instanceof RowTypeInfo) {
437
438 resetVisitedPath = true;
439 curRowTypeInfo = (EventRowTypeInfo) fieldType;
440
441
442 visitedFieldPath = new StringBuilder();
443 }
444
445 if (!resetVisitedPath) {
446 visitedFieldPath.append(fieldPathDelimiter);
447 }
448 i++;
449 }
450 return fieldType;
451 }
452
453
454
455
456
457
458
459 public @Nullable Row extractKey(Row row) {
460 if (hasKey()) {
461
462
463
464 Row rowKey = Objects.requireNonNull(keyTypeInfo()).createEmptyRow();
465 aliasedRowKey.forEach((key, fieldPath) ->
466 rowKey.setField(key, getFieldAt(row, fieldPath))
467 );
468
469 return rowKey;
470 }
471
472 return null;
473 }
474
475
476 private void initializeKeyTypeInfo() {
477 if (hasKey()) {
478 TypeInformation<?>[] fieldTypes = aliasedRowKey.keySet().stream()
479 .map(k -> unwrapCompositeTypeAt(aliasedRowKey.get(k)))
480 .toArray(TypeInformation[]::new);
481
482 keyTypeInfo = new EventRowTypeInfo(fieldTypes, aliasedRowKey.keySet().toArray(new String[0]), null);
483 }
484 }
485
486
487
488
489
490
491 public @Nullable EventRowTypeInfo keyTypeInfo() {
492 return keyTypeInfo;
493 }
494 }