View Javadoc
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   * Simple subclasss of RowTypeInfo that provides support for:
45   * <ul>
46   * <li>WMF Event Platform rules</li>
47   * <li>flink application state schema evolution for the Row type (following WMF guidelines)</li>
48   * </ul>
49   *
50   * NOTE: the serialization format is not compatible with the flink RowSerialization and thus RowTypeInfo and EventRowTypeInfo
51   * should not be mixed up.
52   * <br>
53   *
54   * If for some reasons you have to work with plain RowTypeInfo (pyflink) you can obtain the corresponding RowTypeInfo
55   * using {@link #toRowTypeInfo()}.
56   */
57  @EqualsAndHashCode
58  public class EventRowTypeInfo extends RowTypeInfo {
59      private final LinkedHashMap<String, Integer> positionByName;
60      // map of { alias -> field } used to extract a key from a DataStream Row.
61      private final TreeMap<String, String> aliasedRowKey;
62      // Cache key type information across keyTypeInfo() calls.
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       * Switch between two row TypeInformation implementations.
86       * Inspect the given type info and tries to convert any fromClass to toClass.
87       * Only MapTypeInfo and ObjectArrayTypeInfo are supported, other composite types such as
88       * POJO or Tuples are not inspected. Main purpose of this class is to support RowTypeInfo
89       * generated via {@link org.wikimedia.eventutilities.flink.formats.json.TypeInformationSchemaConversions}.
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      * Obtain the equivalent RowTypeInfo. Useful for APIs that expects to work on a plain {@link RowTypeInfo}.
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         // add canEqual manually because lombok may want to add one with another visibility
141         // failing with: attempting to assign weaker access privileges; was public
142         return obj instanceof EventRowTypeInfo;
143     }
144 
145     /**
146      * List of fields that should not be projected by default
147      * when projecting a source event to a target event.
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      * Creates a new empty Row matching this RowTypeInfo.
158      */
159     public Row createEmptyRow() {
160         return createRowForFieldPath(null);
161     }
162 
163     /**
164      * Creates a new empty instance of a sub Row identified by fieldPath.
165      *
166      * This path supports dotted notation to access nested subfields.
167      * For arrays or maps of Row simply pass the name of the field of the array or map.
168      * @throws IllegalArgumentException if the path leads to a non-existent field or a field that is not a Row.
169      */
170     public Row createEmptySubRow(String fieldPath) {
171         return createRowForFieldPath(fieldPath);
172     }
173 
174     /**
175      * Creates a new empty instance of a sub Row identified by fieldPath.
176      * If fieldPath is null it creates the root Row object.
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      * Recursively inspect MapTypeInfo of ObjectArrayTypeInfo to extract the RowTypeInfo of the leaf value.
187      * @throws IllegalArgumentException if it leads to a non RowTypeInfo field.
188      */
189     private EventRowTypeInfo unwrapRowTypeInfo(TypeInformation<?> fieldTypeInfo) {
190         // Extract the type information from composite types: arrays and maps
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      * Project an input Row to a new Row matching the {@link TypeInformation} of this class.
204      *
205      * The passed Row must:
206      * <ul>
207      *  <li>if intersect is false be compatible with this TypeInformation and must have all the fields
208      *    declared by it
209      *  <li>support named based access
210      * </ul>
211      *
212      * If intersect is true only the fields declared by both row and this TypeInformation will be copied over.
213      * The use-case of this method is to support WMF schema downgrades in case a pipeline
214      * reads events in schema V2 but wants to write them as a previous version
215      * (only new fields are allowed during schema evolution).
216      *
217      * The param ignoredFields can be used to explicitly ignore some field from the projection. The content must
218      * include full-path using a dot as a path separator (e.g. "meta.dt" to exclude the nested "dt" field).
219      *
220      * Edge-cases:
221      * - when intersect is true the resulting Row might be emtpy if no common fields are present
222      * - if the intersection results in an empty composite field (map, row, arrays) this field will not be projected.
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      * Project an input Row to a new Row matching the {@link TypeInformation} of this class.
235      *
236      * The following data will be ignored:
237      * <ul>
238      * <li>all the meta field content except the request_id, domain fields
239      * <li>the $schema field
240      * </ul>
241      *
242      * @see #projectFrom(Row, boolean, Set)
243      * @see #DEFAULT_NON_PROJECTED_FIELDS
244      */
245     public Row projectFrom(Row row, boolean intersect) {
246         return projectFrom(row, intersect, DEFAULT_NON_PROJECTED_FIELDS);
247     }
248 
249     /**
250      * Populate the target row from the source row.
251      *
252      * @return false if nothing was copied (the target row remained empty)
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             // skip ignored fields
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             // do not return an empty Row
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             // no transformation, we assume that everything that is not a Row, a Map or ObjectArray is immutable
312             // (this is probably not true but might cover most WMF use-cases)
313             returnValue = source;
314         }
315         return returnValue;
316     }
317 
318     /**
319      * Set the ingestion time (meta.dt) as per WMF event platform rules.
320      *
321      * @see <a href="https://wikitech.wikimedia.org/wiki/Event_Platform/Schemas/Guidelines#Required_fields">meta.dt rules</a>
322      *
323      * @throws IllegalArgumentException if the type information does not declare the meta field.
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      * Set the event time (dt) as per WMF event platform rules.
339      *
340      * @throws IllegalArgumentException if the type information does not declare the dt field
341      */
342     public void setEventTime(Row element, Instant eventTime) {
343         element.setField(EVENT_TIME_FIELD, eventTime);
344     }
345 
346     /**
347      * Read the event time field.
348      * May return null if the field is not set.
349      */
350     @Nullable
351     public Instant getEventTime(Row element) {
352         return element.getFieldAs(EVENT_TIME_FIELD);
353     }
354 
355     /**
356      * Get the ingestion time of this event if set.
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      * Check if the EventRowTypeInformation instance has a partition key.
385      * @return
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     // Traverse the path type and extract the leaf type from composite types.
409     // Wrapper to RowTypeInfo.getTypeAt() to use in complex WMF Json Schemas.
410     // RowTypeInfo.getTypeAt() will throw an InvalidFieldReferenceException when the leaf
411     // is contained in a CompositeType; for example, it would fail to resolve
412     // Map<String, Row(string_in_subfield: String)>.
413     private TypeInformation<?> unwrapCompositeTypeAt(String fieldPath) {
414         final String fieldPathDelimiter = "\\.";
415         String[] path = fieldPath.split(fieldPathDelimiter);
416 
417         TypeInformation<?> fieldType = null;
418         // Reconstruct fieldPath and unwrap composite types iteratively
419         StringBuilder visitedFieldPath = new StringBuilder();
420         int i = 0;
421         // Start iterating over the
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                 // Iterate over MapTypeInfo of MapTypeInfo (...) and update the visited path accordingly.
430                 while (fieldType instanceof  MapTypeInfo) {
431                     fieldType = ((MapTypeInfo<?, ?>) fieldType).getValueTypeInfo();
432                     i++;
433                 }
434             }
435             // The MapTypeInfo value at visitedFieldPath contained a Row.
436             if (fieldType instanceof RowTypeInfo) {
437                 // Reset the type information to use the nested row as base.
438                 resetVisitedPath = true;
439                 curRowTypeInfo = (EventRowTypeInfo) fieldType;
440                 // Start visiting from the current row. This is to avoid trying to getTypeAt() on
441                 // already traversed CompositeType paths
442                 visitedFieldPath = new StringBuilder();
443             }
444 
445             if (!resetVisitedPath) {
446                 visitedFieldPath.append(fieldPathDelimiter);
447             }
448             i++;
449         }
450         return fieldType;
451     }
452 
453     /**
454      * Extract a key for a given input Row. Returns null is
455      * EventRowTypeInfo has no key.
456      * @param row
457      * @return
458      */
459     public @Nullable Row extractKey(Row row) {
460         if (hasKey()) {
461             // requireNonNull() to control keyTypeInfo() behaviour.
462             // keyTypeInfo() will be null only if hasKey() is false.
463             // In that case, this block will not be evaluated.
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         // no key was defined for this EventRowTypeInfo
472         return null;
473     }
474 
475     // Eager initialization logic for keyTypeInfo
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             // A keyTypeInfo should not have a key. Set aliasedRowKey to null.
482             keyTypeInfo = new EventRowTypeInfo(fieldTypes, aliasedRowKey.keySet().toArray(new String[0]), null);
483         }
484     }
485 
486     /**
487      * Return a TypeInfo representing the schema of Row keys.
488      * Returns null if EventRowTypeInfo has no key.
489      * @return
490      */
491     public @Nullable EventRowTypeInfo keyTypeInfo() {
492         return keyTypeInfo;
493     }
494 }