diff --git a/flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/config/ExecutionConfigOptions.java b/flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/config/ExecutionConfigOptions.java --- a/flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/config/ExecutionConfigOptions.java +++ b/flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/config/ExecutionConfigOptions.java @@ -344,6 +344,49 @@ public class ExecutionConfigOptions { + "If set to ALLOW_UNORDERED, will attempt to use {@see AsyncDataStream.OutputMode.UNORDERED} when it does not " + "affect the correctness of the result, otherwise ORDERED will be still used."); + // ------------------------------------------------------------------------ + // Async Scalar Function + // ------------------------------------------------------------------------ + @Documentation.TableOption(execMode = Documentation.ExecMode.STREAMING) + public static final ConfigOption TABLE_EXEC_ASYNC_SCALAR_BUFFER_CAPACITY = + key("table.exec.async-scalar.buffer-capacity") + .intType() + .defaultValue(10) + .withDescription( + "The max number of async i/o operation that the async lookup join can trigger."); + + @Documentation.TableOption(execMode = Documentation.ExecMode.STREAMING) + public static final ConfigOption TABLE_EXEC_ASYNC_SCALAR_TIMEOUT = + key("table.exec.async-scalar.timeout") + .durationType() + .defaultValue(Duration.ofMinutes(3)) + .withDescription( + "The async timeout for the asynchronous operation to complete."); + + @Documentation.TableOption(execMode = Documentation.ExecMode.STREAMING) + public static final ConfigOption TABLE_EXEC_ASYNC_SCALAR_RETRY_STRATEGY = + key("table.exec.async-scalar.retry-strategy") + .enumType(RetryStrategy.class) + .defaultValue(RetryStrategy.FIXED_DELAY) + .withDescription( + "Restart strategy which will be used, FIXED_DELAY by default."); + + @Documentation.TableOption(execMode = Documentation.ExecMode.STREAMING) + public static final ConfigOption TABLE_EXEC_ASYNC_SCALAR_RETRY_DELAY = + key("table.exec.async-scalar.retry-delay") + .durationType() + .defaultValue(Duration.ofMillis(100)) + .withDescription("The delay to wait before trying again."); + + @Documentation.TableOption(execMode = Documentation.ExecMode.STREAMING) + public static final ConfigOption TABLE_EXEC_ASYNC_SCALAR_MAX_ATTEMPTS = + key("table.exec.async-scalar.max-attempts") + .intType() + .defaultValue(3) + .withDescription( + "The max number of async retry attempts to make before task " + + "execution is failed."); + // ------------------------------------------------------------------------ // MiniBatch Options // ------------------------------------------------------------------------ @@ -692,6 +735,16 @@ public enum AsyncOutputMode { ALLOW_UNORDERED } + /** Retry strategy in the case of failure. */ + @PublicEvolving + public enum RetryStrategy { + /** When a failure occurs, don't retry. */ + NO_RETRY, + + /** A fixed delay before retrying again. */ + FIXED_DELAY + } + /** Determine if CAST operates using the legacy behaviour or the new one. */ @Deprecated public enum LegacyCastBehaviour implements DescribedEnum { diff --git a/flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/AsyncScalarFunction.java b/flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/AsyncScalarFunction.java new file mode 100644 --- /dev/null +++ b/flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/AsyncScalarFunction.java @@ -0,0 +1,103 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.flink.table.functions; + +import org.apache.flink.annotation.PublicEvolving; +import org.apache.flink.table.catalog.DataTypeFactory; +import org.apache.flink.table.types.extraction.TypeInferenceExtractor; +import org.apache.flink.table.types.inference.TypeInference; + +/** + * Base class for a user-defined scalar function which returns results asynchronously. A + * user-defined scalar function maps zero, one, or multiple scalar values to a new scalar value. + * + *

The behavior of a {@link AsyncScalarFunction} can be defined by implementing a custom + * evaluation method. An evaluation method must be declared publicly and named eval. + * Evaluation methods can also be overloaded by implementing multiple methods named eval + * . The first argument of the method must be a {@link + * java.util.concurrent.CompletableFuture} of the return type. The method body must complete the + * future either if there is a result or if it completes exceptionally. + * + *

By default, input and output data types are automatically extracted using reflection. If the + * reflective information is not sufficient, it can be supported and enriched with {@link + * org.apache.flink.table.annotation.DataTypeHint} and {@link + * org.apache.flink.table.annotation.FunctionHint} annotations. + * + *

The following examples show how to specify an async scalar function: + * + *

{@code
+ * // a function that accepts two INT arguments and computes a sum
+ * class SumFunction extends AsyncScalarFunction {
+ *   public void eval(CompletableFuture future, Integer a, Integer b) {
+ *     return future.complete(a + b);
+ *   }
+ * }
+ *
+ * // a function that accepts either INT NOT NULL or BOOLEAN NOT NULL and computes a STRING
+ * class StringifyFunction extends AsyncScalarFunction {
+ *   public void eval(CompletableFuture future, int i) {
+ *     return future.complete(String.valueOf(i));
+ *   }
+ *   public void eval(CompletableFuture future, boolean b) {
+ *     return future.complete(String.valueOf(b));
+ *   }
+ * }
+ *
+ * // a function that accepts either INT or BOOLEAN and computes a STRING using function hints
+ * @FunctionHint(input = [@DataTypeHint("INT")])
+ * @FunctionHint(input = [@DataTypeHint("BOOLEAN")])
+ * class StringifyFunction extends AsyncScalarFunction {
+ *   public void eval(CompletableFuture future, Object o) {
+ *     return future.complete(o.toString());
+ *   }
+ * }
+ *
+ * // a function that accepts any data type as argument and computes a STRING
+ * class StringifyFunction extends AsyncScalarFunction {
+ *   public void eval(CompletableFuture future,
+ *                    @DataTypeHint(inputGroup = InputGroup.ANY) Object o) {
+ *     return future.complete(o.toString());
+ *   }
+ * }
+ *
+ * // a function that accepts an arbitrary number of BIGINT values and computes a DECIMAL(10, 4)
+ * class SumFunction extends AsyncScalarFunction {
+ *   public void eval(@DataTypeHint("DECIMAL(10, 4)") CompletableFuture future,
+ *                    Long... values) {
+ *     // ...
+ *   }
+ * }
+ * }
+ * + *

For storing a user-defined function in a catalog, the class must have a default constructor + * and must be instantiable during runtime. Anonymous functions in Table API can only be persisted + * if the function is not stateful (i.e. containing only transient and static fields). + */ +@PublicEvolving +public class AsyncScalarFunction extends UserDefinedFunction { + @Override + public final FunctionKind getKind() { + return FunctionKind.ASYNC_SCALAR; + } + + @Override + public TypeInference getTypeInference(DataTypeFactory typeFactory) { + return TypeInferenceExtractor.forAsyncScalarFunction(typeFactory, getClass()); + } +} diff --git a/flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/FunctionKind.java b/flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/FunctionKind.java --- a/flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/FunctionKind.java +++ b/flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/FunctionKind.java @@ -25,6 +25,8 @@ public enum FunctionKind { SCALAR, + ASYNC_SCALAR, + TABLE, ASYNC_TABLE, diff --git a/flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/UserDefinedFunction.java b/flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/UserDefinedFunction.java --- a/flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/UserDefinedFunction.java +++ b/flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/UserDefinedFunction.java @@ -50,6 +50,7 @@ * * * @see ScalarFunction + * @see AsyncScalarFunction * @see TableFunction * @see AsyncTableFunction * @see AggregateFunction diff --git a/flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/UserDefinedFunctionHelper.java b/flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/UserDefinedFunctionHelper.java --- a/flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/UserDefinedFunctionHelper.java +++ b/flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/UserDefinedFunctionHelper.java @@ -44,10 +44,13 @@ import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; +import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; import static org.apache.flink.api.java.typeutils.TypeExtractionUtils.getAllDeclaredMethods; @@ -67,6 +70,8 @@ public final class UserDefinedFunctionHelper { public static final String SCALAR_EVAL = "eval"; + public static final String ASYNC_SCALAR_EVAL = "eval"; + public static final String TABLE_EVAL = "eval"; public static final String AGGREGATE_ACCUMULATE = "accumulate"; @@ -459,6 +464,9 @@ private static void validateImplementationMethods( Class functionClass) { if (ScalarFunction.class.isAssignableFrom(functionClass)) { validateImplementationMethod(functionClass, false, false, SCALAR_EVAL); + } else if (AsyncScalarFunction.class.isAssignableFrom(functionClass)) { + validateImplementationMethod(functionClass, false, false, ASYNC_SCALAR_EVAL); + validateAsyncImplementationMethod(functionClass, ASYNC_SCALAR_EVAL); } else if (TableFunction.class.isAssignableFrom(functionClass)) { validateImplementationMethod(functionClass, true, false, TABLE_EVAL); } else if (AsyncTableFunction.class.isAssignableFrom(functionClass)) { @@ -521,6 +529,40 @@ private static void validateImplementationMethod( } } + private static void validateAsyncImplementationMethod( + Class clazz, String... methodNameOptions) { + final Set nameSet = new HashSet<>(Arrays.asList(methodNameOptions)); + final List methods = getAllDeclaredMethods(clazz); + for (Method method : methods) { + if (!nameSet.contains(method.getName())) { + continue; + } + if (!method.getReturnType().equals(Void.TYPE)) { + throw new ValidationException( + String.format( + "Method '%s' of function class '%s' must be void.", + method.getName(), clazz.getName())); + } + boolean foundParam = false; + if (method.getParameterCount() >= 1) { + Type firstParam = method.getGenericParameterTypes()[0]; + firstParam = ExtractionUtils.resolveVariableWithClassContext(clazz, firstParam); + if (CompletableFuture.class.equals(firstParam) + || firstParam instanceof ParameterizedType + && CompletableFuture.class.equals( + ((ParameterizedType) firstParam).getRawType())) { + foundParam = true; + } + } + if (!foundParam) { + throw new ValidationException( + String.format( + "Method '%s' of function class '%s' must have a first argument of type java.util.concurrent.CompletableFuture.", + method.getName(), clazz.getName())); + } + } + } + /** Checks if a user-defined function can be easily instantiated. */ private static void validateInstantiation(Class clazz, boolean requiresDefaultConstructor) { if (!InstantiationUtil.isPublic(clazz)) { diff --git a/flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/extraction/DataTypeExtractor.java b/flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/extraction/DataTypeExtractor.java --- a/flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/extraction/DataTypeExtractor.java +++ b/flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/extraction/DataTypeExtractor.java @@ -68,6 +68,7 @@ import static org.apache.flink.table.types.extraction.ExtractionUtils.hasInvokableConstructor; import static org.apache.flink.table.types.extraction.ExtractionUtils.isStructuredFieldMutable; import static org.apache.flink.table.types.extraction.ExtractionUtils.resolveVariable; +import static org.apache.flink.table.types.extraction.ExtractionUtils.resolveVariableWithClassContext; import static org.apache.flink.table.types.extraction.ExtractionUtils.toClass; import static org.apache.flink.table.types.extraction.ExtractionUtils.validateStructuredClass; import static org.apache.flink.table.types.extraction.ExtractionUtils.validateStructuredFieldReadability; @@ -155,6 +156,46 @@ public static DataType extractFromMethodParameter( paramPos, method.getName(), baseClass.getName())); } + /** + * Extracts a data type from a method parameter by considering surrounding classes and parameter + * annotation. This version assumes that the parameter is a generic type, and uses the generic + * position type as the extracted data type. For example, if the parameter is a + * CompletableFuture<Long> and genericPos is 0, it will extract Long. + */ + public static DataType extractFromGenericMethodParameter( + DataTypeFactory typeFactory, + Class baseClass, + Method method, + int paramPos, + int genericPos) { + + Type parameterType = method.getGenericParameterTypes()[paramPos]; + parameterType = resolveVariableWithClassContext(baseClass, parameterType); + if (!(parameterType instanceof ParameterizedType)) { + throw extractionError( + "The method '%s' needs generic parameters for the %d arg.", + method.getName(), paramPos); + } + final Type genericParameterType = + ((ParameterizedType) parameterType).getActualTypeArguments()[genericPos]; + final Parameter parameter = method.getParameters()[paramPos]; + final DataTypeHint hint = parameter.getAnnotation(DataTypeHint.class); + final DataTypeTemplate template; + if (hint != null) { + template = DataTypeTemplate.fromAnnotation(typeFactory, hint); + } else { + template = DataTypeTemplate.fromDefaults(); + } + return extractDataTypeWithClassContext( + typeFactory, + template, + baseClass, + genericParameterType, + String.format( + " in generic parameter %d of method '%s' in class '%s'", + paramPos, method.getName(), baseClass.getName())); + } + /** * Extracts a data type from a method return type by considering surrounding classes and method * annotation. diff --git a/flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/extraction/ExtractionUtils.java b/flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/extraction/ExtractionUtils.java --- a/flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/extraction/ExtractionUtils.java +++ b/flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/extraction/ExtractionUtils.java @@ -37,9 +37,11 @@ import java.io.IOException; import java.io.InputStream; import java.lang.annotation.Annotation; +import java.lang.reflect.Array; import java.lang.reflect.Constructor; import java.lang.reflect.Executable; import java.lang.reflect.Field; +import java.lang.reflect.GenericArrayType; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.Parameter; @@ -348,6 +350,53 @@ public static Optional> extractSimpleGeneric( } } + /** Resolves a variable type while accepting a context for resolution. */ + public static Type resolveVariableWithClassContext(@Nullable Type contextType, Type type) { + final List typeHierarchy; + if (contextType != null) { + typeHierarchy = collectTypeHierarchy(contextType); + } else { + typeHierarchy = Collections.emptyList(); + } + if (!containsTypeVariable(type)) { + return type; + } + if (type instanceof TypeVariable) { + return resolveVariable(typeHierarchy, (TypeVariable) type); + } else if (type instanceof ParameterizedType) { + ParameterizedType parameterizedType = (ParameterizedType) type; + List paramTypes = new ArrayList<>(); + for (Type paramType : parameterizedType.getActualTypeArguments()) { + paramType = resolveVariableWithClassContext(contextType, paramType); + paramTypes.add(paramType); + } + return new ParameterizedTypeImpl( + paramTypes.toArray(paramTypes.toArray(new Type[0])), + parameterizedType.getRawType(), + parameterizedType.getOwnerType()); + } else if (type instanceof GenericArrayType) { + Type componentType = + resolveVariableWithClassContext( + contextType, ((GenericArrayType) type).getGenericComponentType()); + return new GenericArrayTypeImpl(componentType); + } else { + return type; + } + } + + /** Gets the associated class type from a Type parameter. */ + public static Class getClassFromType(Type type) { + if (type instanceof ParameterizedType) { + return (Class) ((ParameterizedType) type).getRawType(); + } else if (type instanceof GenericArrayType) { + return Array.newInstance( + (Class) ((GenericArrayType) type).getGenericComponentType(), 0) + .getClass(); + } + // Otherwise assume it's a basic type that can be cast. + return (Class) type; + } + // -------------------------------------------------------------------------------------------- // Methods intended for this package // -------------------------------------------------------------------------------------------- @@ -1002,6 +1051,85 @@ public static Class classForName(String name, boolean initialize, ClassLoader return Class.forName(name, initialize, classLoader); } + /** Utility to know if the type contains a type variable that needs to be resolved. */ + private static boolean containsTypeVariable(Type type) { + if (type instanceof TypeVariable) { + return true; + } else if (type instanceof ParameterizedType) { + return Arrays.stream(((ParameterizedType) type).getActualTypeArguments()) + .anyMatch(ExtractionUtils::containsTypeVariable); + } else if (type instanceof GenericArrayType) { + return containsTypeVariable(((GenericArrayType) type).getGenericComponentType()); + } + // WildcardType does not contain a type variable, and we don't consider it resolvable. + return false; + } + + /** + * {@link ParameterizedType} we use for resolving types, so that if you resolve the type + * CompletableFuture<T>, we can create resolve the parameter and return + * CompletableFuture<Long>. + */ + private static class ParameterizedTypeImpl implements ParameterizedType { + + private final Type[] actualTypeArguments; + private final Type rawType; + private final Type ownerType; + + public ParameterizedTypeImpl(Type[] actualTypeArguments, Type rawType, Type ownerType) { + this.actualTypeArguments = actualTypeArguments; + this.rawType = rawType; + this.ownerType = ownerType; + } + + @Override + public Type[] getActualTypeArguments() { + return actualTypeArguments; + } + + @Override + public Type getRawType() { + return rawType; + } + + @Override + public Type getOwnerType() { + return ownerType; + } + + @Override + public String toString() { + List actualTypes = + Arrays.stream(getActualTypeArguments()) + .map(Type::getTypeName) + .collect(Collectors.toList()); + return getRawType().getTypeName() + "<" + String.join(", ", actualTypes) + ">"; + } + } + + /** + * {@link GenericArrayType} we use for resolving types, so that if you resolve the type + * List<T[]>, we can create resolve the parameter and return List<Long[]>. + */ + private static class GenericArrayTypeImpl implements GenericArrayType { + + private final Type genericComponentType; + + public GenericArrayTypeImpl(Type genericComponentType) { + this.genericComponentType = genericComponentType; + } + + @Override + public Type getGenericComponentType() { + return genericComponentType; + } + + @Override + public String getTypeName() { + return getGenericComponentType().getTypeName() + "[]"; + } + } + // -------------------------------------------------------------------------------------------- private ExtractionUtils() { diff --git a/flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/extraction/FunctionMappingExtractor.java b/flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/extraction/FunctionMappingExtractor.java --- a/flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/extraction/FunctionMappingExtractor.java +++ b/flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/extraction/FunctionMappingExtractor.java @@ -29,18 +29,23 @@ import javax.annotation.Nullable; import java.lang.reflect.Method; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.apache.flink.table.types.extraction.ExtractionUtils.collectAnnotationsOfClass; import static org.apache.flink.table.types.extraction.ExtractionUtils.collectAnnotationsOfMethod; import static org.apache.flink.table.types.extraction.ExtractionUtils.extractionError; +import static org.apache.flink.table.types.extraction.ExtractionUtils.getClassFromType; import static org.apache.flink.table.types.extraction.ExtractionUtils.isAssignable; import static org.apache.flink.table.types.extraction.ExtractionUtils.isInvokable; +import static org.apache.flink.table.types.extraction.ExtractionUtils.resolveVariableWithClassContext; /** * Utility for extracting function mappings from signature to result, e.g. from (INT, STRING) to @@ -143,21 +148,10 @@ static ResultExtraction createGenericResultExtraction( boolean allowDataTypeHint) { return (extractor, method) -> { if (allowDataTypeHint) { - final Set dataTypeHints = new HashSet<>(); - dataTypeHints.addAll(collectAnnotationsOfMethod(DataTypeHint.class, method)); - dataTypeHints.addAll( - collectAnnotationsOfClass( - DataTypeHint.class, extractor.getFunctionClass())); - if (dataTypeHints.size() > 1) { - throw extractionError( - "More than one data type hint found for output of function. " - + "Please use a function hint instead."); + Optional hints = extractHints(extractor, method); + if (hints.isPresent()) { + return hints.get(); } - if (dataTypeHints.size() == 1) { - return FunctionTemplate.createResultTemplate( - extractor.typeFactory, dataTypeHints.iterator().next()); - } - // otherwise continue with regular extraction } final DataType dataType = DataTypeExtractor.extractFromGeneric( @@ -169,6 +163,53 @@ static ResultExtraction createGenericResultExtraction( }; } + /** + * Extraction that uses a generic type variable of a method parameter for producing a {@link + * FunctionResultTemplate}. + * + *

If enabled, a {@link DataTypeHint} from method or class has higher priority. + */ + static ResultExtraction createGenericResultExtractionFromMethod( + int paramPos, int genericPos, boolean allowDataTypeHint) { + return (extractor, method) -> { + if (allowDataTypeHint) { + Optional hints = extractHints(extractor, method); + if (hints.isPresent()) { + return hints.get(); + } + } + final DataType dataType = + DataTypeExtractor.extractFromGenericMethodParameter( + extractor.typeFactory, + extractor.getFunctionClass(), + method, + paramPos, + genericPos); + return FunctionResultTemplate.of(dataType); + }; + } + + /** Uses hints to extract functional template. */ + private static Optional extractHints( + BaseMappingExtractor extractor, Method method) { + final Set dataTypeHints = new HashSet<>(); + dataTypeHints.addAll(collectAnnotationsOfMethod(DataTypeHint.class, method)); + dataTypeHints.addAll( + collectAnnotationsOfClass(DataTypeHint.class, extractor.getFunctionClass())); + if (dataTypeHints.size() > 1) { + throw extractionError( + "More than one data type hint found for output of function. " + + "Please use a function hint instead."); + } + if (dataTypeHints.size() == 1) { + return Optional.ofNullable( + FunctionTemplate.createResultTemplate( + extractor.typeFactory, dataTypeHints.iterator().next())); + } + // otherwise continue with regular extraction + return Optional.empty(); + } + /** Verification that checks a method by parameters and return type. */ static MethodVerification createParameterAndReturnTypeVerification() { return (method, signature, result) -> { @@ -208,6 +249,30 @@ static MethodVerification createParameterWithArgumentVerification( }; } + /** Verification that checks a method by parameters including an additional first parameter. */ + static MethodVerification createGenericParameterWithArgumentAndReturnTypeVerification( + Class baseClass, Class argumentClass, int paramPos, int genericPos) { + return (method, signature, result) -> { + final Class[] parameters = + Stream.concat(Stream.of(argumentClass), signature.stream()) + .toArray(Class[]::new); + + Type genericType = method.getGenericParameterTypes()[paramPos]; + genericType = resolveVariableWithClassContext(baseClass, genericType); + if (!(genericType instanceof ParameterizedType)) { + throw extractionError( + "The method '%s' needs generic parameters for the %d arg.", + method.getName(), paramPos); + } + Type returnType = + ((ParameterizedType) genericType).getActualTypeArguments()[genericPos]; + Class returnClazz = getClassFromType(returnType); + if (!(isInvokable(method, parameters) && isAssignable(result, returnClazz, true))) { + throw createMethodNotFoundError(method.getName(), parameters, null); + } + }; + } + /** Verification that checks a method by parameters. */ static MethodVerification createParameterVerification() { return (method, signature, result) -> { diff --git a/flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/extraction/TypeInferenceExtractor.java b/flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/extraction/TypeInferenceExtractor.java --- a/flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/extraction/TypeInferenceExtractor.java +++ b/flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/extraction/TypeInferenceExtractor.java @@ -23,6 +23,7 @@ import org.apache.flink.table.annotation.FunctionHint; import org.apache.flink.table.catalog.DataTypeFactory; import org.apache.flink.table.functions.AggregateFunction; +import org.apache.flink.table.functions.AsyncScalarFunction; import org.apache.flink.table.functions.AsyncTableFunction; import org.apache.flink.table.functions.ScalarFunction; import org.apache.flink.table.functions.TableAggregateFunction; @@ -49,7 +50,9 @@ import java.util.stream.Collectors; import static org.apache.flink.table.types.extraction.ExtractionUtils.extractionError; +import static org.apache.flink.table.types.extraction.FunctionMappingExtractor.createGenericParameterWithArgumentAndReturnTypeVerification; import static org.apache.flink.table.types.extraction.FunctionMappingExtractor.createGenericResultExtraction; +import static org.apache.flink.table.types.extraction.FunctionMappingExtractor.createGenericResultExtractionFromMethod; import static org.apache.flink.table.types.extraction.FunctionMappingExtractor.createParameterAndReturnTypeVerification; import static org.apache.flink.table.types.extraction.FunctionMappingExtractor.createParameterSignatureExtraction; import static org.apache.flink.table.types.extraction.FunctionMappingExtractor.createParameterVerification; @@ -85,6 +88,22 @@ public static TypeInference forScalarFunction( return extractTypeInference(mappingExtractor); } + /** Extracts a type inference from a {@link AsyncScalarFunction}. */ + public static TypeInference forAsyncScalarFunction( + DataTypeFactory typeFactory, Class function) { + final FunctionMappingExtractor mappingExtractor = + new FunctionMappingExtractor( + typeFactory, + function, + UserDefinedFunctionHelper.ASYNC_SCALAR_EVAL, + createParameterSignatureExtraction(1), + null, + createGenericResultExtractionFromMethod(0, 0, true), + createGenericParameterWithArgumentAndReturnTypeVerification( + function, CompletableFuture.class, 0, 0)); + return extractTypeInference(mappingExtractor); + } + /** Extracts a type inference from a {@link AggregateFunction}. */ public static TypeInference forAggregateFunction( DataTypeFactory typeFactory, Class> function) { diff --git a/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/catalog/FunctionCatalogOperatorTable.java b/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/catalog/FunctionCatalogOperatorTable.java --- a/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/catalog/FunctionCatalogOperatorTable.java +++ b/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/catalog/FunctionCatalogOperatorTable.java @@ -193,6 +193,7 @@ private boolean verifyFunctionKind( if (kind == FunctionKind.TABLE) { return true; } else if (kind == FunctionKind.SCALAR + || kind == FunctionKind.ASYNC_SCALAR || kind == FunctionKind.AGGREGATE || kind == FunctionKind.TABLE_AGGREGATE) { if (category != null && category.isTableFunction()) { diff --git a/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/codegen/AsyncCodeGenerator.java b/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/codegen/AsyncCodeGenerator.java new file mode 100644 --- /dev/null +++ b/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/codegen/AsyncCodeGenerator.java @@ -0,0 +1,225 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.flink.table.planner.codegen; + +import org.apache.flink.configuration.ReadableConfig; +import org.apache.flink.streaming.api.functions.async.AsyncFunction; +import org.apache.flink.table.data.GenericRowData; +import org.apache.flink.table.data.RowData; +import org.apache.flink.table.functions.FunctionKind; +import org.apache.flink.table.planner.functions.bridging.BridgingSqlFunction; +import org.apache.flink.table.planner.utils.JavaScalaConversionUtil; +import org.apache.flink.table.runtime.generated.GeneratedFunction; +import org.apache.flink.table.runtime.operators.calc.async.DelegatingAsyncResultFuture; +import org.apache.flink.table.types.logical.RowType; +import org.apache.flink.table.types.logical.utils.LogicalTypeChecks; + +import org.apache.calcite.rex.RexCall; +import org.apache.calcite.rex.RexNode; +import org.apache.calcite.rex.RexVisitorImpl; +import org.apache.commons.text.StringSubstitutor; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.stream.Collectors; + +/** + * Generates an {@link AsyncFunction} which can be used to evaluate calc projections from an async + * scalar function. + */ +public class AsyncCodeGenerator { + + public static final String DEFAULT_EXCEPTION_TERM = "e"; + public static final String DEFAULT_DELEGATING_FUTURE_TERM = "f"; + + /** + * Creates a generated function which produces an {@link AsyncFunction} which executes the calc + * projections. + * + * @param name The name used to generate the underlying function name + * @param inputType The RowType of the input RowData + * @param returnType The RowType of the resulting RowData + * @param retainHeader If the header of the row should be retained + * @param calcProjection The list of projections to be executed by this function + * @param tableConfig The table configuration + * @param classLoader The classloader to use while resolving classes + * @return A {@link GeneratedFunction} returning an {@link AsyncFunction} executing the given + * list of projections + */ + public static GeneratedFunction> generateFunction( + String name, + RowType inputType, + RowType returnType, + List calcProjection, + boolean retainHeader, + ReadableConfig tableConfig, + ClassLoader classLoader) { + CodeGeneratorContext ctx = new CodeGeneratorContext(tableConfig, classLoader); + String processCode = + generateProcessCode( + ctx, + inputType, + returnType, + calcProjection, + retainHeader, + CodeGenUtils.DEFAULT_INPUT1_TERM(), + CodeGenUtils.DEFAULT_COLLECTOR_TERM(), + DEFAULT_EXCEPTION_TERM, + CodeGenUtils.DEFAULT_OUT_RECORD_TERM(), + DEFAULT_DELEGATING_FUTURE_TERM); + return FunctionCodeGenerator.generateFunction( + ctx, + name, + getFunctionClass(), + processCode, + returnType, + inputType, + CodeGenUtils.DEFAULT_INPUT1_TERM(), + JavaScalaConversionUtil.toScala(Optional.empty()), + JavaScalaConversionUtil.toScala(Optional.empty()), + CodeGenUtils.DEFAULT_COLLECTOR_TERM(), + CodeGenUtils.DEFAULT_CONTEXT_TERM()); + } + + @SuppressWarnings("unchecked") + private static Class> getFunctionClass() { + return (Class>) (Object) AsyncFunction.class; + } + + private static String generateProcessCode( + CodeGeneratorContext ctx, + RowType inputType, + RowType outRowType, + List projection, + boolean retainHeader, + String inputTerm, + String collectorTerm, + String errorTerm, + String recordTerm, + String delegatingFutureTerm) { + + projection.forEach(n -> n.accept(new AsyncScalarFunctionsValidator())); + + ExprCodeGenerator exprGenerator = + new ExprCodeGenerator(ctx, false) + .bindInput( + inputType, + inputTerm, + JavaScalaConversionUtil.toScala(Optional.empty())); + + List projectionExprs = + projection.stream() + .map(exprGenerator::generateExpression) + .collect(Collectors.toList()); + int syncIndex = 0; + int index = 0; + StringBuilder outputs = new StringBuilder(); + StringBuilder syncInvocations = new StringBuilder(); + StringBuilder asyncInvocation = new StringBuilder(); + if (retainHeader) { + outputs.append(String.format("%s.setRowKind(rowKind);\n", recordTerm, inputTerm)); + } + for (GeneratedExpression fieldExpr : projectionExprs) { + if (fieldExpr.resultTerm().isEmpty()) { + outputs.append( + String.format("%s.setField(%d, resultObject);\n", recordTerm, index)); + asyncInvocation.append(fieldExpr.code()); + } else { + outputs.append( + String.format( + "%s.setField(%d, %s.getSynchronousResult(%d));\n", + recordTerm, index, delegatingFutureTerm, syncIndex)); + syncInvocations.append(fieldExpr.code()); + syncInvocations.append( + String.format( + "%s.addSynchronousResult(%s);\n", + delegatingFutureTerm, fieldExpr.resultTerm())); + syncIndex++; + } + index++; + } + + Map values = new HashMap<>(); + values.put("delegatingFutureTerm", delegatingFutureTerm); + values.put("delegatingFutureType", DelegatingAsyncResultFuture.class.getCanonicalName()); + values.put("collectorTerm", collectorTerm); + values.put("typeTerm", GenericRowData.class.getCanonicalName()); + values.put("recordTerm", recordTerm); + values.put("inputTerm", inputTerm); + values.put("fieldCount", Integer.toString(LogicalTypeChecks.getFieldCount(outRowType))); + values.put("outputs", outputs.toString()); + values.put("syncInvocations", syncInvocations.toString()); + values.put("asyncInvocation", asyncInvocation.toString()); + values.put("errorTerm", errorTerm); + + return StringSubstitutor.replace( + String.join( + "\n", + new String[] { + "final ${delegatingFutureType} ${delegatingFutureTerm} ", + " = new ${delegatingFutureType}(${collectorTerm});", + "final org.apache.flink.types.RowKind rowKind = ${inputTerm}.getRowKind();\n", + "try {", + " java.util.function.Function outputFactory = ", + " new java.util.function.Function() {", + " @Override", + " public ${typeTerm} apply(Object resultObject) {", + " final ${typeTerm} ${recordTerm} = new ${typeTerm}(${fieldCount});", + " ${outputs}", + " return ${recordTerm};", + " }", + " };", + "", + " ${delegatingFutureTerm}.setOutputFactory(outputFactory);", + // Ensure that sync invocations come first so that we know that they're + // available when the async callback occurs. + " ${syncInvocations}", + " ${asyncInvocation}", + "", + "} catch (Throwable ${errorTerm}) {", + " ${collectorTerm}.completeExceptionally(${errorTerm});", + "}" + }), + values); + } + + private static class AsyncScalarFunctionsValidator extends RexVisitorImpl { + public AsyncScalarFunctionsValidator() { + super(true); + } + + @Override + public Void visitCall(RexCall call) { + super.visitCall(call); + + if (call.getOperator() instanceof BridgingSqlFunction + && ((BridgingSqlFunction) call.getOperator()).getDefinition().getKind() + != FunctionKind.ASYNC_SCALAR) { + throw new CodeGenException( + "Invalid use of function " + + call.getOperator() + + "." + + "Code generation should only be done with async calls"); + } + return null; + } + } +} diff --git a/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/bridging/BridgingSqlFunction.java b/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/bridging/BridgingSqlFunction.java --- a/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/bridging/BridgingSqlFunction.java +++ b/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/bridging/BridgingSqlFunction.java @@ -116,7 +116,9 @@ public static BridgingSqlFunction of( TypeInference typeInference) { final FunctionKind functionKind = resolvedFunction.getDefinition().getKind(); checkState( - functionKind == FunctionKind.SCALAR || functionKind == FunctionKind.TABLE, + functionKind == FunctionKind.SCALAR + || functionKind == FunctionKind.ASYNC_SCALAR + || functionKind == FunctionKind.TABLE, "Scalar or table function kind expected."); if (functionKind == FunctionKind.TABLE) { diff --git a/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/common/CommonExecAsyncCalc.java b/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/common/CommonExecAsyncCalc.java new file mode 100644 --- /dev/null +++ b/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/common/CommonExecAsyncCalc.java @@ -0,0 +1,163 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.flink.table.planner.plan.nodes.exec.common; + +import org.apache.flink.api.dag.Transformation; +import org.apache.flink.configuration.ReadableConfig; +import org.apache.flink.streaming.api.functions.async.AsyncFunction; +import org.apache.flink.streaming.api.operators.OneInputStreamOperatorFactory; +import org.apache.flink.streaming.api.operators.async.AsyncWaitOperatorFactory; +import org.apache.flink.streaming.api.transformations.OneInputTransformation; +import org.apache.flink.table.data.RowData; +import org.apache.flink.table.planner.calcite.FlinkTypeFactory; +import org.apache.flink.table.planner.codegen.AsyncCodeGenerator; +import org.apache.flink.table.planner.delegation.PlannerBase; +import org.apache.flink.table.planner.plan.nodes.exec.ExecEdge; +import org.apache.flink.table.planner.plan.nodes.exec.ExecNodeBase; +import org.apache.flink.table.planner.plan.nodes.exec.ExecNodeConfig; +import org.apache.flink.table.planner.plan.nodes.exec.ExecNodeContext; +import org.apache.flink.table.planner.plan.nodes.exec.InputProperty; +import org.apache.flink.table.planner.plan.nodes.exec.SingleTransformationTranslator; +import org.apache.flink.table.planner.plan.nodes.exec.utils.ExecNodeUtil; +import org.apache.flink.table.planner.plan.utils.AsyncUtil; +import org.apache.flink.table.runtime.generated.GeneratedFunction; +import org.apache.flink.table.runtime.operators.calc.async.AsyncFunctionRunner; +import org.apache.flink.table.runtime.typeutils.InternalTypeInfo; +import org.apache.flink.table.types.logical.LogicalType; +import org.apache.flink.table.types.logical.RowType; + +import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonProperty; + +import org.apache.calcite.rex.RexCall; +import org.apache.calcite.rex.RexInputRef; +import org.apache.calcite.rex.RexNode; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +import static org.apache.flink.util.Preconditions.checkArgument; +import static org.apache.flink.util.Preconditions.checkNotNull; + +/** Base class for exec Async Calc. */ +public abstract class CommonExecAsyncCalc extends ExecNodeBase + implements SingleTransformationTranslator { + + public static final String ASYNC_CALC_TRANSFORMATION = "async-calc"; + + public static final String FIELD_NAME_PROJECTION = "projection"; + + @JsonProperty(FIELD_NAME_PROJECTION) + private final List projection; + + public CommonExecAsyncCalc( + int id, + ExecNodeContext context, + ReadableConfig persistedConfig, + List projection, + List inputProperties, + RowType outputType, + String description) { + super(id, context, persistedConfig, inputProperties, outputType, description); + checkArgument(inputProperties.size() == 1); + this.projection = checkNotNull(projection); + } + + @SuppressWarnings("unchecked") + @Override + protected Transformation translateToPlanInternal( + PlannerBase planner, ExecNodeConfig config) { + final ExecEdge inputEdge = getInputEdges().get(0); + final Transformation inputTransform = + (Transformation) inputEdge.translateToPlan(planner); + return createAsyncOneInputTransformation( + inputTransform, config, planner.getFlinkContext().getClassLoader()); + } + + private OneInputTransformation createAsyncOneInputTransformation( + Transformation inputTransform, + ExecNodeConfig config, + ClassLoader classLoader) { + List asyncRexCalls = + projection.stream() + .filter(x -> x instanceof RexCall) + .map(x -> (RexCall) x) + .collect(Collectors.toList()); + + List forwardedFields = + projection.stream() + .filter(x -> x instanceof RexInputRef) + .map(x -> ((RexInputRef) x).getIndex()) + .collect(Collectors.toList()); + final ExecEdge inputEdge = getInputEdges().get(0); + RowType inputRowType = + RowType.of(inputEdge.getOutputType().getChildren().toArray(new LogicalType[0])); + + List forwardedFieldsLogicalTypes = + forwardedFields.stream() + .map(inputRowType.getChildren()::get) + .collect(Collectors.toList()); + List asyncCallLogicalTypes = + asyncRexCalls.stream() + .map(node -> FlinkTypeFactory.toLogicalType(node.getType())) + .collect(Collectors.toList()); + List fieldsLogicalTypes = new ArrayList<>(); + fieldsLogicalTypes.addAll(forwardedFieldsLogicalTypes); + fieldsLogicalTypes.addAll(asyncCallLogicalTypes); + InternalTypeInfo asyncOperatorResultTypeInfo = + InternalTypeInfo.ofFields(fieldsLogicalTypes.toArray(new LogicalType[0])); + OneInputStreamOperatorFactory factory = + getAsyncFunctionOperator(config, classLoader, inputRowType); + return ExecNodeUtil.createOneInputTransformation( + inputTransform, + createTransformationMeta(ASYNC_CALC_TRANSFORMATION, config), + factory, + asyncOperatorResultTypeInfo, + inputTransform.getParallelism(), + false); + } + + private OneInputStreamOperatorFactory getAsyncFunctionOperator( + ExecNodeConfig config, ClassLoader classLoader, RowType inputRowType) { + + RowType resultTypeInfo = + RowType.of( + projection.stream() + .map(node -> FlinkTypeFactory.toLogicalType(node.getType())) + .toArray(LogicalType[]::new)); + + GeneratedFunction> generatedFunction = + AsyncCodeGenerator.generateFunction( + "AsyncScalarFunction", + inputRowType, + resultTypeInfo, + projection, + true, + config, + classLoader); + AsyncFunctionRunner func = new AsyncFunctionRunner(generatedFunction); + AsyncUtil.Options options = AsyncUtil.getAsyncOptions(config); + return new AsyncWaitOperatorFactory<>( + func, + options.asyncTimeout, + options.asyncBufferCapacity, + options.asyncOutputMode, + options.asyncRetryStrategy); + } +} diff --git a/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/stream/StreamExecAsyncCalc.java b/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/stream/StreamExecAsyncCalc.java new file mode 100644 --- /dev/null +++ b/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/stream/StreamExecAsyncCalc.java @@ -0,0 +1,82 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.flink.table.planner.plan.nodes.exec.stream; + +import org.apache.flink.FlinkVersion; +import org.apache.flink.configuration.ReadableConfig; +import org.apache.flink.table.data.RowData; +import org.apache.flink.table.planner.plan.nodes.exec.ExecNode; +import org.apache.flink.table.planner.plan.nodes.exec.ExecNodeContext; +import org.apache.flink.table.planner.plan.nodes.exec.ExecNodeMetadata; +import org.apache.flink.table.planner.plan.nodes.exec.InputProperty; +import org.apache.flink.table.planner.plan.nodes.exec.common.CommonExecAsyncCalc; +import org.apache.flink.table.types.logical.RowType; + +import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonCreator; +import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonProperty; + +import org.apache.calcite.rex.RexNode; + +import java.util.Collections; +import java.util.List; + +/** Stream {@link ExecNode} for {@link org.apache.flink.table.functions.AsyncScalarFunction}. */ +@ExecNodeMetadata( + name = "stream-exec-async-calc", + version = 1, + producedTransformations = CommonExecAsyncCalc.ASYNC_CALC_TRANSFORMATION, + minPlanVersion = FlinkVersion.v1_19, + minStateVersion = FlinkVersion.v1_19, + consumedOptions = { + "table.exec.async-scalar.buffer-capacity", + "table.exec.async-scalar.timeout", + "table.exec.async-scalar.retry-strategy", + "table.exec.async-scalar.retry-delay", + "table.exec.async-scalar.max-attempts", + }) +public class StreamExecAsyncCalc extends CommonExecAsyncCalc implements StreamExecNode { + + public StreamExecAsyncCalc( + ReadableConfig tableConfig, + List projection, + InputProperty inputProperty, + RowType outputType, + String description) { + this( + ExecNodeContext.newNodeId(), + ExecNodeContext.newContext(StreamExecAsyncCalc.class), + ExecNodeContext.newPersistedConfig(StreamExecAsyncCalc.class, tableConfig), + projection, + Collections.singletonList(inputProperty), + outputType, + description); + } + + @JsonCreator + public StreamExecAsyncCalc( + @JsonProperty(FIELD_NAME_ID) int id, + @JsonProperty(FIELD_NAME_TYPE) ExecNodeContext context, + @JsonProperty(FIELD_NAME_CONFIGURATION) ReadableConfig persistedConfig, + @JsonProperty(FIELD_NAME_PROJECTION) List projection, + @JsonProperty(FIELD_NAME_INPUT_PROPERTIES) List inputProperties, + @JsonProperty(FIELD_NAME_OUTPUT_TYPE) RowType outputType, + @JsonProperty(FIELD_NAME_DESCRIPTION) String description) { + super(id, context, persistedConfig, projection, inputProperties, outputType, description); + } +} diff --git a/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/physical/stream/StreamPhysicalAsyncCalc.java b/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/physical/stream/StreamPhysicalAsyncCalc.java new file mode 100644 --- /dev/null +++ b/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/physical/stream/StreamPhysicalAsyncCalc.java @@ -0,0 +1,85 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.flink.table.planner.plan.nodes.physical.stream; + +import org.apache.flink.table.planner.calcite.FlinkTypeFactory; +import org.apache.flink.table.planner.plan.nodes.exec.ExecNode; +import org.apache.flink.table.planner.plan.nodes.exec.InputProperty; +import org.apache.flink.table.planner.plan.nodes.exec.stream.StreamExecAsyncCalc; +import org.apache.flink.table.planner.plan.utils.AsyncUtil; + +import org.apache.calcite.plan.RelOptCluster; +import org.apache.calcite.plan.RelTraitSet; +import org.apache.calcite.rel.RelNode; +import org.apache.calcite.rel.core.Calc; +import org.apache.calcite.rel.type.RelDataType; +import org.apache.calcite.rex.RexNode; +import org.apache.calcite.rex.RexProgram; + +import java.util.List; +import java.util.stream.Collectors; + +import static org.apache.flink.table.planner.utils.ShortcutUtils.unwrapTableConfig; + +/** Stream physical RelNode for {@link org.apache.flink.table.functions.AsyncScalarFunction}. */ +public class StreamPhysicalAsyncCalc extends StreamPhysicalCalcBase { + private final RelOptCluster cluster; + private final RexProgram calcProgram; + private final RelDataType outputRowType; + + public StreamPhysicalAsyncCalc( + RelOptCluster cluster, + RelTraitSet traitSet, + RelNode inputRel, + RexProgram calcProgram, + RelDataType outputRowType) { + super(cluster, traitSet, inputRel, calcProgram, outputRowType); + this.cluster = cluster; + this.calcProgram = calcProgram; + this.outputRowType = outputRowType; + } + + @Override + public Calc copy(RelTraitSet traitSet, RelNode child, RexProgram program) { + return new StreamPhysicalAsyncCalc(cluster, traitSet, child, program, outputRowType); + } + + @Override + public ExecNode translateToExecNode() { + List projection = + calcProgram.getProjectList().stream() + .map(calcProgram::expandLocalRef) + .collect(Collectors.toList()); + if (calcProgram.getCondition() != null) { + throw new IllegalStateException( + "The condition of StreamPhysicalAsyncCalc should be null."); + } + if (projection.stream().filter(AsyncUtil::containsAsyncCall).count() > 1) { + throw new IllegalStateException( + "Only a single async projection is allowed in StreamPhysicalAsyncCalc."); + } + + return new StreamExecAsyncCalc( + unwrapTableConfig(this), + projection, + InputProperty.DEFAULT, + FlinkTypeFactory.toLogicalRowType(getRowType()), + getRelDetailedDescription()); + } +} diff --git a/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/rules/logical/AsyncCalcSplitRule.java b/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/rules/logical/AsyncCalcSplitRule.java new file mode 100644 --- /dev/null +++ b/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/rules/logical/AsyncCalcSplitRule.java @@ -0,0 +1,203 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.flink.table.planner.plan.rules.logical; + +import org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalCalc; +import org.apache.flink.table.planner.plan.utils.AsyncUtil; +import org.apache.flink.table.planner.utils.JavaScalaConversionUtil; + +import org.apache.calcite.plan.RelOptRule; +import org.apache.calcite.plan.RelOptRuleCall; +import org.apache.calcite.rex.RexCall; +import org.apache.calcite.rex.RexNode; +import org.apache.calcite.rex.RexProgram; + +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; + +import scala.Option; + +/** + * Defines split rules for async calc nodes. These largely exist to isolate and simplify the calls + * to the async function from other calc operations, so that the operator can handle just that + * functionality. + */ +public class AsyncCalcSplitRule { + + private static final RemoteCalcCallFinder ASYNC_CALL_FINDER = new AsyncRemoteCalcCallFinder(); + public static final RelOptRule SPLIT_CONDITION = + new RemoteCalcSplitConditionRule(ASYNC_CALL_FINDER); + public static final RelOptRule SPLIT_PROJECT = + new RemoteCalcSplitProjectionRule(ASYNC_CALL_FINDER); + public static final RelOptRule SPLIT_PROJECTION_REX_FIELD = + new RemoteCalcSplitProjectionRexFieldRule(ASYNC_CALL_FINDER); + public static final RelOptRule SPLIT_CONDITION_REX_FIELD = + new RemoteCalcSplitConditionRexFieldRule(ASYNC_CALL_FINDER); + public static final RelOptRule EXPAND_PROJECT = + new RemoteCalcExpandProjectRule(ASYNC_CALL_FINDER); + public static final RelOptRule PUSH_CONDITION = + new RemoteCalcPushConditionRule(ASYNC_CALL_FINDER); + public static final RelOptRule REWRITE_PROJECT = + new RemoteCalcRewriteProjectionRule(ASYNC_CALL_FINDER); + public static final RelOptRule NESTED_SPLIT = new AsyncCalcSplitNestedRule(ASYNC_CALL_FINDER); + public static final RelOptRule ONE_PER_CALC_SPLIT = + new AsyncCalcSplitOnePerCalcRule(ASYNC_CALL_FINDER); + + /** + * An Async implementation of {@link RemoteCalcCallFinder} which finds uses of {@link + * org.apache.flink.table.functions.AsyncScalarFunction}. + */ + public static class AsyncRemoteCalcCallFinder implements RemoteCalcCallFinder { + @Override + public boolean containsRemoteCall(RexNode node) { + return AsyncUtil.containsAsyncCall(node); + } + + @Override + public boolean containsNonRemoteCall(RexNode node) { + return AsyncUtil.containsNonAsyncCall(node); + } + + @Override + public boolean isRemoteCall(RexNode node) { + return AsyncUtil.isAsyncCall(node); + } + + @Override + public boolean isNonRemoteCall(RexNode node) { + return AsyncUtil.isNonAsyncCall(node); + } + } + + private static boolean hasNestedCalls(List projects) { + return projects.stream() + .filter(AsyncUtil::containsAsyncCall) + .filter(expr -> expr instanceof RexCall) + .map(expr -> (RexCall) expr) + .anyMatch( + rexCall -> + rexCall.getOperands().stream() + .anyMatch(AsyncUtil::containsAsyncCall)); + } + + /** + * Splits nested call <- asyncCall chains so that nothing is immediately waiting on an async + * call in a single calc. + * + *

For Example: Calc(select=[syncCall(asyncCall()]) -> Source + * + *

becomes + * + *

Calc(select=[syncCall(f0)]) -> AsyncCalc(select=[asyncCall() as f0]) -> Source + */ + public static class AsyncCalcSplitNestedRule extends RemoteCalcSplitRuleBase { + + public AsyncCalcSplitNestedRule(RemoteCalcCallFinder callFinder) { + super("AsyncCalcSplitNestedRule", callFinder); + } + + @Override + public boolean matches(RelOptRuleCall call) { + FlinkLogicalCalc calc = call.rel(0); + + // Matches if we have nested remote calls + List projects = + calc.getProgram().getProjectList().stream() + .map(calc.getProgram()::expandLocalRef) + .collect(Collectors.toList()); + return hasNestedCalls(projects); + } + + // We convert not on the outermost call, but anything within it + @Override + public boolean needConvert(RexProgram program, RexNode node, Option matchState) { + return node instanceof RexCall + && !((RexCall) node) + .getOperands().stream().anyMatch(callFinder()::containsRemoteCall); + } + + @Override + public SplitComponents split(RexProgram program, ScalarFunctionSplitter splitter) { + return new SplitComponents( + JavaScalaConversionUtil.toScala(Optional.empty()), + JavaScalaConversionUtil.toScala( + Optional.ofNullable(program.getCondition()) + .map(program::expandLocalRef)), + JavaScalaConversionUtil.toScala( + program.getProjectList().stream() + .map(program::expandLocalRef) + .map(n -> n.accept(splitter)) + .collect(Collectors.toList()))); + } + } + + /** + * Splits async calls if there are multiple across projections, so that there's one per calc. + * This assumes that the nested rule has been run first, so there is just one per projection. + * + *

For Example: Calc(select=[asyncCall(), asyncCall()]) -> Source + * + *

becomes + * + *

AsyncCalc(select=[asyncCall(), f0]) -> AsyncCalc(select=[asyncCall() as f0]) -> Source + */ + public static class AsyncCalcSplitOnePerCalcRule + extends RemoteCalcSplitProjectionRuleBase { + + public AsyncCalcSplitOnePerCalcRule(RemoteCalcCallFinder callFinder) { + super("AsyncCalcSplitOnePerCalcRule", callFinder); + } + + @Override + public boolean matches(RelOptRuleCall call) { + FlinkLogicalCalc calc = call.rel(0); + List projects = + calc.getProgram().getProjectList().stream() + .map(calc.getProgram()::expandLocalRef) + .collect(Collectors.toList()); + + // If this has no nested calls, then this can be called to split up separate projections + // into two different calcs. We don't want the splitter to be called to with nested + // calls since it won't behave correctly, so this must be used in conjunction with the + // nested rule. + return !hasNestedCalls(projects) + && projects.stream().filter(callFinder()::containsRemoteCall).count() >= 2; + } + + @Override + public boolean needConvert(RexProgram program, RexNode node, Option matchState) { + if (AsyncUtil.containsAsyncCall(node) && !matchState.get().foundMatch) { + matchState.get().foundMatch = true; + return true; + } + return false; + } + + @Override + public Option getMatchState() { + return Option.apply(new State()); + } + + /** State object used to keep track of whether a match has been found yet. */ + public static class State { + boolean foundMatch = false; + } + } +} diff --git a/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/rules/logical/PythonCorrelateSplitRule.java b/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/rules/logical/PythonCorrelateSplitRule.java --- a/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/rules/logical/PythonCorrelateSplitRule.java +++ b/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/rules/logical/PythonCorrelateSplitRule.java @@ -245,7 +245,8 @@ private ScalarFunctionSplitter createScalarFunctionSplitter( // separate node return node instanceof RexFieldAccess; } - }); + }, + new PythonRemoteCalcCallFinder()); } @Override diff --git a/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/rules/physical/stream/StreamPhysicalAsyncCalcRule.java b/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/rules/physical/stream/StreamPhysicalAsyncCalcRule.java new file mode 100644 --- /dev/null +++ b/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/rules/physical/stream/StreamPhysicalAsyncCalcRule.java @@ -0,0 +1,64 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.flink.table.planner.plan.rules.physical.stream; + +import org.apache.flink.table.planner.plan.nodes.FlinkConventions; +import org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalCalc; +import org.apache.flink.table.planner.plan.nodes.physical.stream.StreamPhysicalAsyncCalc; +import org.apache.flink.table.planner.plan.utils.AsyncUtil; + +import org.apache.calcite.plan.RelOptRule; +import org.apache.calcite.plan.RelOptRuleCall; +import org.apache.calcite.plan.RelTraitSet; +import org.apache.calcite.rel.RelNode; +import org.apache.calcite.rel.convert.ConverterRule; +import org.apache.calcite.rex.RexProgram; +import org.checkerframework.checker.nullness.qual.Nullable; + +/** A physical rule for identifying logical async Calcs and converting it to a physical RelNode. */ +public class StreamPhysicalAsyncCalcRule extends ConverterRule { + public static final RelOptRule INSTANCE = + new StreamPhysicalAsyncCalcRule( + Config.INSTANCE.withConversion( + FlinkLogicalCalc.class, + FlinkConventions.LOGICAL(), + FlinkConventions.STREAM_PHYSICAL(), + "StreamPhysicalAsyncCalcRule")); + + protected StreamPhysicalAsyncCalcRule(Config config) { + super(config); + } + + @Override + public boolean matches(RelOptRuleCall call) { + FlinkLogicalCalc calc = call.rel(0); + RexProgram program = calc.getProgram(); + return program.getExprList().stream().anyMatch(AsyncUtil::containsAsyncCall); + } + + @Override + public @Nullable RelNode convert(RelNode rel) { + FlinkLogicalCalc calc = (FlinkLogicalCalc) rel; + RelTraitSet traitSet = rel.getTraitSet().replace(FlinkConventions.STREAM_PHYSICAL()); + RelNode newInput = RelOptRule.convert(calc.getInput(), FlinkConventions.STREAM_PHYSICAL()); + + return new StreamPhysicalAsyncCalc( + rel.getCluster(), traitSet, newInput, calc.getProgram(), rel.getRowType()); + } +} diff --git a/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/utils/AsyncUtil.java b/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/utils/AsyncUtil.java new file mode 100644 --- /dev/null +++ b/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/utils/AsyncUtil.java @@ -0,0 +1,188 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.flink.table.planner.plan.utils; + +import org.apache.flink.streaming.api.datastream.AsyncDataStream; +import org.apache.flink.streaming.api.functions.async.AsyncRetryStrategy; +import org.apache.flink.streaming.util.retryable.AsyncRetryStrategies; +import org.apache.flink.table.api.config.ExecutionConfigOptions; +import org.apache.flink.table.data.RowData; +import org.apache.flink.table.functions.FunctionDefinition; +import org.apache.flink.table.functions.FunctionKind; +import org.apache.flink.table.planner.plan.nodes.exec.ExecNodeConfig; +import org.apache.flink.table.planner.utils.ShortcutUtils; + +import org.apache.calcite.rex.RexCall; +import org.apache.calcite.rex.RexNode; + +import java.time.Duration; +import java.util.Objects; + +import static org.apache.flink.table.runtime.operators.calc.async.RetryPredicates.ANY_EXCEPTION; +import static org.apache.flink.table.runtime.operators.calc.async.RetryPredicates.EMPTY_RESPONSE; + +/** Contains utilities for {@link org.apache.flink.table.functions.AsyncScalarFunction}. */ +public class AsyncUtil { + + /** + * Checks whether it contains the specified kind of async function call in the specified node. + * + * @param node the RexNode to check + * @return true if it contains an async function call in the specified node. + */ + public static boolean containsAsyncCall(RexNode node) { + return node.accept(new FunctionFinder(true, true)); + } + + /** + * Checks whether it contains non-async function call in the specified node. + * + * @param node the RexNode to check + * @return true if it contains a non-async function call in the specified node. + */ + public static boolean containsNonAsyncCall(RexNode node) { + return node.accept(new FunctionFinder(false, true)); + } + + /** + * Checks whether the specified node is the specified kind of async function call. + * + * @param node the RexNode to check + * @return true if the specified node is an async function call. + */ + public static boolean isAsyncCall(RexNode node) { + return node.accept(new FunctionFinder(true, false)); + } + + /** + * Checks whether the specified node is a non-async function call. + * + * @param node the RexNode to check + * @return true if the specified node is a non-async function call. + */ + public static boolean isNonAsyncCall(RexNode node) { + return node.accept(new FunctionFinder(false, false)); + } + + /** + * Gets the options required to run the operator. + * + * @param config The config from which to fetch the options + * @return Extracted options + */ + public static AsyncUtil.Options getAsyncOptions(ExecNodeConfig config) { + return new AsyncUtil.Options( + config.get(ExecutionConfigOptions.TABLE_EXEC_ASYNC_SCALAR_BUFFER_CAPACITY), + config.get(ExecutionConfigOptions.TABLE_EXEC_ASYNC_SCALAR_TIMEOUT).toMillis(), + AsyncDataStream.OutputMode.ORDERED, + getResultRetryStrategy( + config.get(ExecutionConfigOptions.TABLE_EXEC_ASYNC_SCALAR_RETRY_STRATEGY), + config.get(ExecutionConfigOptions.TABLE_EXEC_ASYNC_SCALAR_RETRY_DELAY), + config.get(ExecutionConfigOptions.TABLE_EXEC_ASYNC_SCALAR_MAX_ATTEMPTS))); + } + + /** Options for configuring async behavior. */ + public static class Options { + + public final int asyncBufferCapacity; + public final long asyncTimeout; + public final AsyncDataStream.OutputMode asyncOutputMode; + public final AsyncRetryStrategy asyncRetryStrategy; + + public Options( + int asyncBufferCapacity, + long asyncTimeout, + AsyncDataStream.OutputMode asyncOutputMode, + AsyncRetryStrategy asyncRetryStrategy) { + this.asyncBufferCapacity = asyncBufferCapacity; + this.asyncTimeout = asyncTimeout; + this.asyncOutputMode = asyncOutputMode; + this.asyncRetryStrategy = asyncRetryStrategy; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Options that = (Options) o; + return asyncBufferCapacity == that.asyncBufferCapacity + && asyncTimeout == that.asyncTimeout + && asyncOutputMode == that.asyncOutputMode; + } + + @Override + public int hashCode() { + return Objects.hash(asyncBufferCapacity, asyncTimeout, asyncOutputMode); + } + + @Override + public String toString() { + return asyncOutputMode + ", " + asyncTimeout + "ms, " + asyncBufferCapacity; + } + } + + @SuppressWarnings("unchecked") + private static AsyncRetryStrategy getResultRetryStrategy( + ExecutionConfigOptions.RetryStrategy retryStrategy, + Duration retryDelay, + int retryMaxAttempts) { + // Only fixed delay is allowed at the moment, so just ignore the config. + if (retryStrategy == ExecutionConfigOptions.RetryStrategy.FIXED_DELAY) { + return new AsyncRetryStrategies.FixedDelayRetryStrategyBuilder( + retryMaxAttempts, retryDelay.toMillis()) + .ifResult(EMPTY_RESPONSE) + .ifException(ANY_EXCEPTION) + .build(); + } + return AsyncRetryStrategies.NO_RETRY_STRATEGY; + } + + private static class FunctionFinder extends RexDefaultVisitor { + + private final boolean findAsyncCall; + private final boolean recursive; + + public FunctionFinder(boolean findAsyncCall, boolean recursive) { + this.findAsyncCall = findAsyncCall; + this.recursive = recursive; + } + + @Override + public Boolean visitNode(RexNode rexNode) { + return false; + } + + private boolean isImmediateAsyncCall(RexCall call) { + FunctionDefinition definition = ShortcutUtils.unwrapFunctionDefinition(call); + return definition != null && definition.getKind() == FunctionKind.ASYNC_SCALAR; + } + + @Override + public Boolean visitCall(RexCall call) { + boolean isImmediateAsyncCall = isImmediateAsyncCall(call); + return findAsyncCall == isImmediateAsyncCall + || (recursive + && call.getOperands().stream().anyMatch(node -> node.accept(this))); + } + } +} diff --git a/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/utils/ExecNodeMetadataUtil.java b/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/utils/ExecNodeMetadataUtil.java --- a/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/utils/ExecNodeMetadataUtil.java +++ b/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/utils/ExecNodeMetadataUtil.java @@ -29,6 +29,7 @@ import org.apache.flink.table.planner.plan.nodes.exec.ExecNodeMetadata; import org.apache.flink.table.planner.plan.nodes.exec.MultipleExecNodeMetadata; import org.apache.flink.table.planner.plan.nodes.exec.serde.JsonSerdeUtil; +import org.apache.flink.table.planner.plan.nodes.exec.stream.StreamExecAsyncCalc; import org.apache.flink.table.planner.plan.nodes.exec.stream.StreamExecCalc; import org.apache.flink.table.planner.plan.nodes.exec.stream.StreamExecChangelogNormalize; import org.apache.flink.table.planner.plan.nodes.exec.stream.StreamExecCorrelate; @@ -139,6 +140,7 @@ private ExecNodeMetadataUtil() { add(StreamExecWindowRank.class); add(StreamExecWindowTableFunction.class); add(StreamExecPythonCalc.class); + add(StreamExecAsyncCalc.class); add(StreamExecPythonCorrelate.class); add(StreamExecPythonGroupAggregate.class); add(StreamExecPythonGroupWindowAggregate.class); diff --git a/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/codegen/ExpressionReducer.scala b/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/codegen/ExpressionReducer.scala --- a/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/codegen/ExpressionReducer.scala +++ b/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/codegen/ExpressionReducer.scala @@ -26,6 +26,7 @@ import org.apache.flink.table.functions.{FunctionContext, UserDefinedFunction} import org.apache.flink.table.planner.calcite.FlinkTypeFactory import org.apache.flink.table.planner.codegen.FunctionCodeGenerator.generateFunction import org.apache.flink.table.planner.functions.sql.FlinkSqlOperatorTable.{JSON_ARRAY, JSON_OBJECT} +import org.apache.flink.table.planner.plan.utils.AsyncUtil import org.apache.flink.table.planner.plan.utils.PythonUtil.containsPythonCall import org.apache.flink.table.planner.utils.JavaScalaConversionUtil.toScala import org.apache.flink.table.planner.utils.Logging @@ -65,9 +66,9 @@ class ExpressionReducer( constExprs: java.util.List[RexNode], reducedValues: java.util.List[RexNode]): Unit = { - val pythonUDFExprs = new ListBuffer[RexNode]() + val remoteUDFExprs = new ListBuffer[RexNode]() - val literals = skipAndValidateExprs(rexBuilder, constExprs, pythonUDFExprs) + val literals = skipAndValidateExprs(rexBuilder, constExprs, remoteUDFExprs) val literalTypes = literals.map(e => FlinkTypeFactory.toLogicalType(e.getType)) val resultType = RowType.of(literalTypes: _*) @@ -131,8 +132,8 @@ class ExpressionReducer( while (i < constExprs.size()) { val unreduced = constExprs.get(i) // use eq to compare reference - if (pythonUDFExprs.exists(_ eq unreduced)) { - // if contains python function then just insert the original expression. + if (remoteUDFExprs.exists(_ eq unreduced)) { + // if contains async function then just insert the original expression. reducedValues.add(unreduced) } else unreduced match { @@ -253,15 +254,15 @@ class ExpressionReducer( private def skipAndValidateExprs( rexBuilder: RexBuilder, constExprs: java.util.List[RexNode], - pythonUDFExprs: ListBuffer[RexNode]): List[RexNode] = { + remoteUDFExprs: ListBuffer[RexNode]): List[RexNode] = { constExprs.asScala .map(e => (e.getType.getSqlTypeName, e)) .flatMap { - // Skip expressions that contain python functions because it's quite expensive to - // call Python UDFs during optimization phase. They will be optimized during the runtime. - case (_, e) if containsPythonCall(e) => - pythonUDFExprs += e + // Skip expressions that contain python or async functions because it's quite expensive to + // call async UDFs during optimization phase. They will be optimized during the runtime. + case (_, e) if containsPythonCall(e) || AsyncUtil.containsAsyncCall(e) => + remoteUDFExprs += e None // we don't support object literals yet, we skip those constant expressions diff --git a/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/codegen/calls/BridgingFunctionGenUtil.scala b/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/codegen/calls/BridgingFunctionGenUtil.scala --- a/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/codegen/calls/BridgingFunctionGenUtil.scala +++ b/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/codegen/calls/BridgingFunctionGenUtil.scala @@ -27,7 +27,7 @@ import org.apache.flink.table.expressions.ApiExpressionUtils.{typeLiteral, unres import org.apache.flink.table.expressions.Expression import org.apache.flink.table.functions._ import org.apache.flink.table.functions.SpecializedFunction.{ExpressionEvaluator, ExpressionEvaluatorFactory} -import org.apache.flink.table.functions.UserDefinedFunctionHelper.{validateClassForRuntime, ASYNC_TABLE_EVAL, SCALAR_EVAL, TABLE_EVAL} +import org.apache.flink.table.functions.UserDefinedFunctionHelper.{validateClassForRuntime, ASYNC_SCALAR_EVAL, ASYNC_TABLE_EVAL, SCALAR_EVAL, TABLE_EVAL} import org.apache.flink.table.planner.calcite.{FlinkTypeFactory, RexFactory} import org.apache.flink.table.planner.codegen._ import org.apache.flink.table.planner.codegen.CodeGenUtils._ @@ -47,6 +47,8 @@ import org.apache.flink.table.types.logical.utils.LogicalTypeChecks.isCompositeT import org.apache.flink.table.types.utils.DataTypeUtils.{isInternal, validateInputDataType, validateOutputDataType} import org.apache.flink.util.Preconditions +import AsyncCodeGenerator.DEFAULT_DELEGATING_FUTURE_TERM + import java.util.concurrent.CompletableFuture import scala.collection.JavaConverters._ @@ -147,6 +149,13 @@ object BridgingFunctionGenUtil { skipIfArgsNull) } else if (udf.getKind == FunctionKind.ASYNC_TABLE) { generateAsyncTableFunctionCall(functionTerm, externalOperands, returnType) + } else if (udf.getKind == FunctionKind.ASYNC_SCALAR) { + generateAsyncScalarFunctionCall( + ctx, + functionTerm, + externalOperands, + returnType, + outputDataType) } else { generateScalarFunctionCall(ctx, functionTerm, externalOperands, outputDataType) } @@ -210,6 +219,28 @@ object BridgingFunctionGenUtil { GeneratedExpression(NO_CODE, NEVER_NULL, functionCallCode, outputType) } + private def generateAsyncScalarFunctionCall( + ctx: CodeGeneratorContext, + functionTerm: String, + externalOperands: Seq[GeneratedExpression], + outputType: LogicalType, + outputDataType: DataType): GeneratedExpression = { + val converterTerm = ctx.addReusableConverter(outputDataType) + val functionCallCode = + s""" + |${externalOperands.map(_.code).mkString("\n")} + |if (${externalOperands.map(_.nullTerm).mkString(" || ")}) { + | $DEFAULT_DELEGATING_FUTURE_TERM.createAsyncFuture($converterTerm).complete(null); + |} else { + | $functionTerm.eval( + | $DEFAULT_DELEGATING_FUTURE_TERM.createAsyncFuture($converterTerm), + | ${externalOperands.map(_.resultTerm).mkString(", ")}); + |} + |""".stripMargin + + GeneratedExpression(NO_CODE, NEVER_NULL, functionCallCode, outputType) + } + /** * Generates a collector that converts the output of a table function (possibly as an atomic type) * into an internal row type. Returns a collector term for referencing the collector. @@ -389,6 +420,13 @@ object BridgingFunctionGenUtil { functionName) } else if (udf.getKind == FunctionKind.SCALAR) { verifyImplementation(SCALAR_EVAL, argumentDataTypes, Some(outputDataType), udf, functionName) + } else if (udf.getKind == FunctionKind.ASYNC_SCALAR) { + verifyImplementation( + ASYNC_SCALAR_EVAL, + DataTypes.NULL.bridgedTo(classOf[CompletableFuture[_]]) +: argumentDataTypes, + None, + udf, + functionName) } else { throw new CodeGenException( s"Unsupported function kind '${udf.getKind}' for function '$functionName'.") diff --git a/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/rules/FlinkStreamRuleSets.scala b/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/rules/FlinkStreamRuleSets.scala --- a/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/rules/FlinkStreamRuleSets.scala +++ b/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/rules/FlinkStreamRuleSets.scala @@ -372,17 +372,48 @@ object FlinkStreamRuleSets { PushFilterInCalcIntoTableSourceScanRule.INSTANCE, // Rule that rewrites temporal join with extracted primary key TemporalJoinRewriteWithUniqueKeyRule.INSTANCE, - // Rule that splits python ScalarFunctions from java/scala ScalarFunctions. + // Avoids accessing a field from the result (condition). PythonCalcSplitRule.SPLIT_CONDITION_REX_FIELD, + // Avoids accessing a field from the result (projection). PythonCalcSplitRule.SPLIT_PROJECTION_REX_FIELD, + // Avoids dealing with a python call in the condition. PythonCalcSplitRule.SPLIT_CONDITION, + // Avoids dealing with Java calls in the same Calc as python calls. PythonCalcSplitRule.SPLIT_PROJECT, + // Splits calcs which contain both general Python functions and pandas Python functions PythonCalcSplitRule.SPLIT_PANDAS_IN_PROJECT, + // Avoid accessing a field as input to an async call with a single calc. PythonCalcSplitRule.EXPAND_PROJECT, + // Avoid having any condition in a python calc by pushing it first. PythonCalcSplitRule.PUSH_CONDITION, + // Orders the projections so that input references are first, followed by python calls. PythonCalcSplitRule.REWRITE_PROJECT, + // Renames the field names of the Flatten calc which is right after a calc representing a + // Python Map operation to the output names of the map function PythonMapRenameRule.INSTANCE, - PythonMapMergeRule.INSTANCE + // Merges Python calc used in Map operation, Flatten calcs and Python calcs used in Map + // xoperation together + PythonMapMergeRule.INSTANCE, + // Similar to the python rules above, the goal is to limit complexity of calcs which + // have async calls so that the implementation can be simplified to handle a single async call. + // Avoids accessing a field from an asynchronous result (condition). + AsyncCalcSplitRule.SPLIT_CONDITION_REX_FIELD, + // Avoids accessing a field from an asynchronous result (projection). + AsyncCalcSplitRule.SPLIT_PROJECTION_REX_FIELD, + // Avoids dealing with an async call in the condition. + AsyncCalcSplitRule.SPLIT_CONDITION, + // Avoids dealing with Java calls in the same Calc as Async calls. + AsyncCalcSplitRule.SPLIT_PROJECT, + // Avoid accessing a field as input to an async call with a single calc. + AsyncCalcSplitRule.EXPAND_PROJECT, + // Avoid having any condition in an async calc by pushing it first. + AsyncCalcSplitRule.PUSH_CONDITION, + // Orders the projections so that input references are first, followed by async calls. + AsyncCalcSplitRule.REWRITE_PROJECT, + // Avoid async calls which call async calls. + AsyncCalcSplitRule.NESTED_SPLIT, + // Avoid having async calls in multiple projections in a single calc. + AsyncCalcSplitRule.ONE_PER_CALC_SPLIT ) /** RuleSet to do physical optimize for stream */ @@ -400,6 +431,7 @@ object FlinkStreamRuleSets { // calc StreamPhysicalCalcRule.INSTANCE, StreamPhysicalPythonCalcRule.INSTANCE, + StreamPhysicalAsyncCalcRule.INSTANCE, // union StreamPhysicalUnionRule.INSTANCE, // sort diff --git a/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/rules/logical/PythonCalcSplitRule.scala b/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/rules/logical/PythonCalcSplitRule.scala --- a/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/rules/logical/PythonCalcSplitRule.scala +++ b/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/rules/logical/PythonCalcSplitRule.scala @@ -20,7 +20,7 @@ package org.apache.flink.table.planner.plan.rules.logical import org.apache.flink.table.functions.ScalarFunction import org.apache.flink.table.functions.python.PythonFunctionKind import org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalCalc -import org.apache.flink.table.planner.plan.utils.{InputRefVisitor, RexDefaultVisitor} +import org.apache.flink.table.planner.plan.utils.{InputRefVisitor, PythonUtil, RexDefaultVisitor} import org.apache.flink.table.planner.plan.utils.PythonUtil.{containsNonPythonCall, containsPythonCall, isNonPythonCall, isPythonCall} import org.apache.calcite.plan.{RelOptRule, RelOptRuleCall} @@ -34,245 +34,14 @@ import scala.collection.JavaConversions._ import scala.collection.JavaConverters._ import scala.collection.mutable -/** - * Base rule that splits [[FlinkLogicalCalc]] into multiple [[FlinkLogicalCalc]]s. It is mainly to - * ensure that each [[FlinkLogicalCalc]] only contains Java/Scala [[ScalarFunction]]s or Python - * [[ScalarFunction]]s. - */ -abstract class PythonCalcSplitRuleBase(description: String) - extends RelOptRule(operand(classOf[FlinkLogicalCalc], any), description) { - - override def onMatch(call: RelOptRuleCall): Unit = { - val calc: FlinkLogicalCalc = call.rel(0).asInstanceOf[FlinkLogicalCalc] - val input = calc.getInput - val rexBuilder = call.builder().getRexBuilder - val program = calc.getProgram - val extractedRexNodes = new mutable.ArrayBuffer[RexNode]() - - val extractedFunctionOffset = input.getRowType.getFieldCount - val splitter = new ScalarFunctionSplitter( - program, - rexBuilder, - extractedFunctionOffset, - extractedRexNodes, - new Function[RexNode, Boolean] { - override def apply(node: RexNode): Boolean = needConvert(program, node) - }) - - val (bottomCalcCondition, topCalcCondition, topCalcProjects) = split(program, splitter) - val accessedFields = - extractRefInputFields(topCalcProjects, topCalcCondition, extractedFunctionOffset) - - val bottomCalcProjects = - accessedFields.map(RexInputRef.of(_, input.getRowType)) ++ extractedRexNodes - val bottomCalcFieldNames = SqlValidatorUtil.uniquify( - accessedFields.map(i => input.getRowType.getFieldNames.get(i)).toSeq ++ - extractedRexNodes.indices.map("f" + _), - rexBuilder.getTypeFactory.getTypeSystem.isSchemaCaseSensitive - ) - - val bottomCalc = new FlinkLogicalCalc( - calc.getCluster, - calc.getTraitSet, - input, - RexProgram.create( - input.getRowType, - bottomCalcProjects.toList, - bottomCalcCondition.orNull, - bottomCalcFieldNames, - rexBuilder)) - - val inputRewriter = new ExtractedFunctionInputRewriter( - calc.getCluster.getRexBuilder, - extractedFunctionOffset, - accessedFields) - val topCalc = new FlinkLogicalCalc( - calc.getCluster, - calc.getTraitSet, - bottomCalc, - RexProgram.create( - bottomCalc.getRowType, - topCalcProjects.map(_.accept(inputRewriter)), - topCalcCondition.map(_.accept(inputRewriter)).orNull, - calc.getRowType, - rexBuilder)) - - call.transformTo(topCalc) - } - - /** Extracts the indices of the input fields referred by the specified projects and condition. */ - private def extractRefInputFields( - projects: Seq[RexNode], - condition: Option[RexNode], - inputFieldsCount: Int): Array[Int] = { - val visitor = new InputRefVisitor - - // extract referenced input fields from projections - projects.foreach(exp => exp.accept(visitor)) - - // extract referenced input fields from condition - condition.foreach(_.accept(visitor)) - - // fields of indexes greater than inputFieldsCount is the extracted functions and - // should be filtered as they are not from the original input - visitor.getFields.filter(_ < inputFieldsCount) - } - - /** Returns true if need to convert the specified node. */ - def needConvert(program: RexProgram, node: RexNode): Boolean - - /** - * Splits the specified [[RexProgram]] using the specified [[ScalarFunctionSplitter]]. It returns - * a triple of (bottom calc condition, top calc condition, top calc projects) as the split result. - */ - def split( - program: RexProgram, - splitter: ScalarFunctionSplitter): (Option[RexNode], Option[RexNode], Seq[RexNode]) -} - -/** - * Rule that splits [[FlinkLogicalCalc]]s which contain Python functions in the condition into - * multiple [[FlinkLogicalCalc]]s. After this rule is applied, there will be no Python functions in - * the condition of the [[FlinkLogicalCalc]]s. - */ -object PythonCalcSplitConditionRule - extends PythonCalcSplitRuleBase("PythonCalcSplitConditionRule") { - - override def matches(call: RelOptRuleCall): Boolean = { - val calc: FlinkLogicalCalc = call.rel(0).asInstanceOf[FlinkLogicalCalc] - - // matches if it contains Python functions in condition - Option(calc.getProgram.getCondition) - .map(calc.getProgram.expandLocalRef) - .exists(containsPythonCall(_)) - } - - override def needConvert(program: RexProgram, node: RexNode): Boolean = isPythonCall(node) - - override def split( - program: RexProgram, - splitter: ScalarFunctionSplitter): (Option[RexNode], Option[RexNode], Seq[RexNode]) = { - ( - None, - Option(program.getCondition).map(program.expandLocalRef(_).accept(splitter)), - program.getProjectList.map(program.expandLocalRef)) - } -} - -abstract class PythonCalcSplitProjectionRuleBase(description: String) - extends PythonCalcSplitRuleBase(description) { - - override def split( - program: RexProgram, - splitter: ScalarFunctionSplitter): (Option[RexNode], Option[RexNode], Seq[RexNode]) = { - ( - Option(program.getCondition).map(program.expandLocalRef), - None, - program.getProjectList.map(program.expandLocalRef(_).accept(splitter))) - } -} - -abstract class PythonCalcSplitRexFieldRuleBase(description: String) - extends PythonCalcSplitRuleBase(description) { - - override def needConvert(program: RexProgram, node: RexNode): Boolean = { - node match { - case x: RexFieldAccess => - x.getReferenceExpr match { - case y: RexLocalRef if containsPythonCall(program.expandLocalRef(y)) => true - case _ => false - } - case _ => false - } - } - - protected def containsFieldAccessAfterPythonCall(node: RexNode): Boolean = { - node match { - case call: RexCall => call.getOperands.exists(containsFieldAccessAfterPythonCall) - case x: RexFieldAccess => containsPythonCall(x.getReferenceExpr) - case _ => false - } - } -} - -/** - * Rule that splits the RexField with the input of Python function contained in the projection of - * [[FlinkLogicalCalc]]s. - */ -object PythonCalcSplitProjectionRexFieldRule - extends PythonCalcSplitRexFieldRuleBase("PythonCalcSplitProjectionRexFieldRule") { - - override def matches(call: RelOptRuleCall): Boolean = { - val calc: FlinkLogicalCalc = call.rel(0).asInstanceOf[FlinkLogicalCalc] - - val projects = calc.getProgram.getProjectList.map(calc.getProgram.expandLocalRef) - projects.exists(containsFieldAccessAfterPythonCall) - } - - override def split( - program: RexProgram, - splitter: ScalarFunctionSplitter): (Option[RexNode], Option[RexNode], Seq[RexNode]) = { - ( - Option(program.getCondition).map(program.expandLocalRef), - None, - program.getProjectList.map(_.accept(splitter))) - } -} - -/** - * Rule that splits the RexField with the input of Python function contained in the condition of - * [[FlinkLogicalCalc]]s. - */ -object PythonCalcSplitConditionRexFieldRule - extends PythonCalcSplitRexFieldRuleBase("PythonCalcSplitConditionRexFieldRule") { - - override def matches(call: RelOptRuleCall): Boolean = { - val calc: FlinkLogicalCalc = call.rel(0).asInstanceOf[FlinkLogicalCalc] - - Option(calc.getProgram.getCondition) - .map(calc.getProgram.expandLocalRef) - .exists(containsFieldAccessAfterPythonCall) - } - - override def split( - program: RexProgram, - splitter: ScalarFunctionSplitter): (Option[RexNode], Option[RexNode], Seq[RexNode]) = { - ( - None, - Option(program.getCondition).map(_.accept(splitter)), - program.getProjectList.map(_.accept(splitter))) - } -} - -/** - * Rule that splits [[FlinkLogicalCalc]]s which contain both Java functions and Python functions in - * the projection into multiple [[FlinkLogicalCalc]]s. After this rule is applied, it will only - * contain Python functions or Java functions in the projection of each [[FlinkLogicalCalc]]. - */ -object PythonCalcSplitProjectionRule - extends PythonCalcSplitProjectionRuleBase("PythonCalcSplitProjectionRule") { - - override def matches(call: RelOptRuleCall): Boolean = { - val calc: FlinkLogicalCalc = call.rel(0).asInstanceOf[FlinkLogicalCalc] - val projects = calc.getProgram.getProjectList.map(calc.getProgram.expandLocalRef) - - // matches if it contains both Python functions and Java functions in the projection - projects.exists(containsPythonCall(_)) && projects.exists(containsNonPythonCall) - } - - override def needConvert(program: RexProgram, node: RexNode): Boolean = { - program.getProjectList.map(program.expandLocalRef).exists(isNonPythonCall) == isPythonCall(node) - } -} - /** * Rule that splits [[FlinkLogicalCalc]]s which contain both general Python functions and pandas * Python functions in the projection into multiple [[FlinkLogicalCalc]]s. After this rule is * applied, it will only contain general Python functions or pandas Python functions in the * projection of each [[FlinkLogicalCalc]]. */ -object PythonCalcSplitPandasInProjectionRule - extends PythonCalcSplitProjectionRuleBase("PythonCalcSplitPandasInProjectionRule") { +class PythonCalcSplitPandasInProjectionRule(callFinder: RemoteCalcCallFinder) + extends RemoteCalcSplitProjectionRuleBase("PythonCalcSplitPandasInProjectionRule", callFinder) { override def matches(call: RelOptRuleCall): Boolean = { val calc: FlinkLogicalCalc = call.rel(0).asInstanceOf[FlinkLogicalCalc] @@ -284,7 +53,10 @@ object PythonCalcSplitPandasInProjectionRule projects.exists(containsPythonCall(_, PythonFunctionKind.PANDAS)) } - override def needConvert(program: RexProgram, node: RexNode): Boolean = { + override def needConvert( + program: RexProgram, + node: RexNode, + matchState: Option[Nothing]): Boolean = { program.getProjectList .map(program.expandLocalRef) .exists(isPythonCall(_, PythonFunctionKind.GENERAL)) == isPythonCall( @@ -293,222 +65,37 @@ object PythonCalcSplitPandasInProjectionRule } } -/** - * Rule that expands the RexFieldAccess inputs of Python functions contained in the projection of - * [[FlinkLogicalCalc]]s. - */ -object PythonCalcExpandProjectRule extends PythonCalcSplitRuleBase("PythonCalcExpandProjectRule") { - - override def matches(call: RelOptRuleCall): Boolean = { - val calc: FlinkLogicalCalc = call.rel(0).asInstanceOf[FlinkLogicalCalc] - val projects = calc.getProgram.getProjectList.map(calc.getProgram.expandLocalRef) - - projects.exists(containsPythonCall(_)) && projects.exists(containsFieldAccessInputs) +class PythonRemoteCalcCallFinder extends RemoteCalcCallFinder { + override def containsRemoteCall(node: RexNode): Boolean = { + PythonUtil.containsPythonCall(node) } - override def needConvert(program: RexProgram, node: RexNode): Boolean = - node.isInstanceOf[RexFieldAccess] - - override def split( - program: RexProgram, - splitter: ScalarFunctionSplitter): (Option[RexNode], Option[RexNode], Seq[RexNode]) = { - ( - Option(program.getCondition).map(program.expandLocalRef), - None, - program.getProjectList.map(program.expandLocalRef(_).accept(splitter))) - } - - private def containsFieldAccessInputs(node: RexNode): Boolean = { - node match { - case call: RexCall => call.getOperands.exists(containsFieldAccessInputs) - case _: RexFieldAccess => true - case _ => false - } + override def containsNonRemoteCall(node: RexNode): Boolean = { + PythonUtil.containsNonPythonCall(node) } -} - -/** - * Rule that pushes the condition of [[FlinkLogicalCalc]]s before it for the [[FlinkLogicalCalc]]s - * which contain Python functions in the projection. - */ -object PythonCalcPushConditionRule extends PythonCalcSplitRuleBase("PythonCalcPushConditionRule") { - - override def matches(call: RelOptRuleCall): Boolean = { - val calc: FlinkLogicalCalc = call.rel(0).asInstanceOf[FlinkLogicalCalc] - val projects = calc.getProgram.getProjectList.map(calc.getProgram.expandLocalRef) - // matches if all the following conditions hold true: - // 1) the condition is not null - // 2) it contains Python functions in the projection - calc.getProgram.getCondition != null && projects.exists(containsPythonCall(_)) + override def isRemoteCall(node: RexNode): Boolean = { + PythonUtil.isPythonCall(node) } - override def needConvert(program: RexProgram, node: RexNode): Boolean = isNonPythonCall(node) - - override def split( - program: RexProgram, - splitter: ScalarFunctionSplitter): (Option[RexNode], Option[RexNode], Seq[RexNode]) = { - ( - Option(program.getCondition).map(program.expandLocalRef), - None, - program.getProjectList.map(program.expandLocalRef)) + override def isNonRemoteCall(node: RexNode): Boolean = { + PythonUtil.isNonPythonCall(node) } } -/** - * Rule that ensures that it only contains [[RexInputRef]]s at the beginning of the project list and - * [[RexCall]]s at the end of the project list for [[FlinkLogicalCalc]]s which contain Python - * functions in the projection. This rule exists to keep DataStreamPythonCalc as simple as possible - * and ensures that it only needs to handle the Python function execution. - */ -object PythonCalcRewriteProjectionRule - extends PythonCalcSplitRuleBase("PythonCalcRewriteProjectionRule") { - - override def matches(call: RelOptRuleCall): Boolean = { - val calc: FlinkLogicalCalc = call.rel(0).asInstanceOf[FlinkLogicalCalc] - val projects = calc.getProgram.getProjectList.map(calc.getProgram.expandLocalRef) - - // matches if all the following conditions hold true: - // 1) it contains Python functions in the projection - // 2) it contains RexNodes besides RexInputRef and RexCall or - // not all the RexCalls lying at the end of the project list - projects.exists(containsPythonCall(_)) && - (projects.exists(expr => !expr.isInstanceOf[RexCall] && !expr.isInstanceOf[RexInputRef]) || - projects.indexWhere(_.isInstanceOf[RexCall]) < - projects.lastIndexWhere(_.isInstanceOf[RexInputRef])) - } - - override def needConvert(program: RexProgram, node: RexNode): Boolean = isPythonCall(node) - - override def split( - program: RexProgram, - splitter: ScalarFunctionSplitter): (Option[RexNode], Option[RexNode], Seq[RexNode]) = { - (None, None, program.getProjectList.map(program.expandLocalRef(_).accept(splitter))) - } -} - -private class ScalarFunctionSplitter( - program: RexProgram, - rexBuilder: RexBuilder, - extractedFunctionOffset: Int, - extractedRexNodes: mutable.ArrayBuffer[RexNode], - needConvert: Function[RexNode, Boolean]) - extends RexDefaultVisitor[RexNode] { - - private var fieldsRexCall: Map[Int, Int] = Map[Int, Int]() - - override def visitCall(call: RexCall): RexNode = { - if (needConvert(call)) { - getExtractedRexNode(call) - } else { - call.clone(call.getType, call.getOperands.asScala.map(_.accept(this))) - } - } - - override def visitFieldAccess(fieldAccess: RexFieldAccess): RexNode = { - if (needConvert(fieldAccess)) { - val expr = fieldAccess.getReferenceExpr - expr match { - case localRef: RexLocalRef if containsPythonCall(program.expandLocalRef(localRef)) => - getExtractedRexFieldAccess(fieldAccess, localRef.getIndex) - case _: RexCorrelVariable => - val field = fieldAccess.getField - new RexInputRef(field.getIndex, field.getType) - case _ => - val newFieldAccess = - rexBuilder.makeFieldAccess(expr.accept(this), fieldAccess.getField.getIndex) - getExtractedRexNode(newFieldAccess) - } - } else { - fieldAccess - } - } - - override def visitLocalRef(localRef: RexLocalRef): RexNode = { - program.getExprList.get(localRef.getIndex).accept(this) - } - - override def visitNode(rexNode: RexNode): RexNode = rexNode - - private def getExtractedRexNode(node: RexNode): RexNode = { - val newNode = new RexInputRef(extractedFunctionOffset + extractedRexNodes.length, node.getType) - extractedRexNodes.append(node) - newNode - } - - private def getExtractedRexFieldAccess(node: RexFieldAccess, rexCallIndex: Int): RexNode = { - val pythonCall: RexCall = - program.expandLocalRef(node.getReferenceExpr.asInstanceOf[RexLocalRef]).asInstanceOf[RexCall] - if (!fieldsRexCall.contains(rexCallIndex)) { - extractedRexNodes.append(pythonCall) - fieldsRexCall += rexCallIndex -> (extractedFunctionOffset + extractedRexNodes.length - 1) - } - rexBuilder.makeFieldAccess( - new RexInputRef(fieldsRexCall(rexCallIndex), pythonCall.getType), - node.getField.getIndex) - } -} - -/** - * Rewrite field accesses of a RexNode as not all the fields from the original input are forwarded: - * 1) Fields of index greater than or equal to extractedFunctionOffset refer to the extracted - * function. 2) Fields of index less than extractedFunctionOffset refer to the original input field. - * - * @param rexBuilder - * the RexBuilder - * @param extractedFunctionOffset - * the original start offset of the extracted functions - * @param accessedFields - * the accessed fields which will be forwarded - */ -private class ExtractedFunctionInputRewriter( - rexBuilder: RexBuilder, - extractedFunctionOffset: Int, - accessedFields: Array[Int]) - extends RexDefaultVisitor[RexNode] { - - /** old input fields ref index -> new input fields ref index mappings */ - private val fieldMap: Map[Int, Int] = accessedFields.zipWithIndex.toMap - - override def visitInputRef(inputRef: RexInputRef): RexNode = { - if (inputRef.getIndex >= extractedFunctionOffset) { - new RexInputRef( - inputRef.getIndex - extractedFunctionOffset + accessedFields.length, - inputRef.getType) - } else { - new RexInputRef( - fieldMap.getOrElse( - inputRef.getIndex, - throw new IllegalArgumentException("input field contains invalid index")), - inputRef.getType) - } - } - - override def visitCall(call: RexCall): RexNode = { - call.clone(call.getType, call.getOperands.asScala.map(_.accept(this))) - } - - override def visitFieldAccess(fieldAccess: RexFieldAccess): RexNode = { - rexBuilder.makeFieldAccess( - fieldAccess.getReferenceExpr.accept(this), - fieldAccess.getField.getIndex) - } - - override def visitNode(rexNode: RexNode): RexNode = rexNode -} - object PythonCalcSplitRule { /** * These rules should be applied sequentially in the order of SPLIT_CONDITION, SPLIT_PROJECT, * SPLIT_PANDAS_IN_PROJECT, EXPAND_PROJECT, PUSH_CONDITION and REWRITE_PROJECT. */ - val SPLIT_CONDITION: RelOptRule = PythonCalcSplitConditionRule - val SPLIT_PROJECT: RelOptRule = PythonCalcSplitProjectionRule - val SPLIT_PANDAS_IN_PROJECT: RelOptRule = PythonCalcSplitPandasInProjectionRule - val SPLIT_PROJECTION_REX_FIELD: RelOptRule = PythonCalcSplitProjectionRexFieldRule - val SPLIT_CONDITION_REX_FIELD: RelOptRule = PythonCalcSplitConditionRexFieldRule - val EXPAND_PROJECT: RelOptRule = PythonCalcExpandProjectRule - val PUSH_CONDITION: RelOptRule = PythonCalcPushConditionRule - val REWRITE_PROJECT: RelOptRule = PythonCalcRewriteProjectionRule + private val callFinder = new PythonRemoteCalcCallFinder() + val SPLIT_CONDITION: RelOptRule = new RemoteCalcSplitConditionRule(callFinder) + val SPLIT_PROJECT: RelOptRule = new RemoteCalcSplitProjectionRule(callFinder) + val SPLIT_PANDAS_IN_PROJECT: RelOptRule = new PythonCalcSplitPandasInProjectionRule(callFinder) + val SPLIT_PROJECTION_REX_FIELD: RelOptRule = new RemoteCalcSplitProjectionRexFieldRule(callFinder) + val SPLIT_CONDITION_REX_FIELD: RelOptRule = new RemoteCalcSplitConditionRexFieldRule(callFinder) + val EXPAND_PROJECT: RelOptRule = new RemoteCalcExpandProjectRule(callFinder) + val PUSH_CONDITION: RelOptRule = new RemoteCalcPushConditionRule(callFinder) + val REWRITE_PROJECT: RelOptRule = new RemoteCalcRewriteProjectionRule(callFinder) } diff --git a/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/rules/logical/RemoteCalcCallFinder.java b/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/rules/logical/RemoteCalcCallFinder.java new file mode 100644 --- /dev/null +++ b/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/rules/logical/RemoteCalcCallFinder.java @@ -0,0 +1,37 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.flink.table.planner.plan.rules.logical; + +import org.apache.calcite.rex.RexNode; + +/** + * Finds whether a {@link RexNode} contains remote calls or not. + */ +public interface RemoteCalcCallFinder { + + // If the node contains directly or indirectly a remote call. + boolean containsRemoteCall(RexNode node); + // If the node contains directly or indirectly a non-remote call. + boolean containsNonRemoteCall(RexNode node); + // If the node contains directly a remote call. + boolean isRemoteCall(RexNode node); + + // If the node contains directly a non-remote call. + boolean isNonRemoteCall(RexNode node); +} diff --git a/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/rules/logical/RemoteCalcSplitRule.scala b/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/rules/logical/RemoteCalcSplitRule.scala new file mode 100644 --- /dev/null +++ b/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/rules/logical/RemoteCalcSplitRule.scala @@ -0,0 +1,525 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.flink.table.planner.plan.rules.logical + +import org.apache.flink.table.functions.ScalarFunction +import org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalCalc +import org.apache.flink.table.planner.plan.utils.{InputRefVisitor, RexDefaultVisitor} + +import org.apache.calcite.plan.{RelOptRule, RelOptRuleCall} +import org.apache.calcite.plan.RelOptRule.{any, operand} +import org.apache.calcite.rex.{RexBuilder, RexCall, RexCorrelVariable, RexFieldAccess, RexInputRef, RexLocalRef, RexNode, RexProgram} +import org.apache.calcite.sql.validate.SqlValidatorUtil + +import java.util.function.Function + +import scala.collection.JavaConversions._ +import scala.collection.JavaConverters._ +import scala.collection.mutable + +/** + * Base rule that splits [[FlinkLogicalCalc]] into multiple [[FlinkLogicalCalc]]s. It is mainly to + * ensure that each [[FlinkLogicalCalc]] only contains Java/Scala [[ScalarFunction]]s or Remote + * [[ScalarFunction]]s. + */ +abstract class RemoteCalcSplitRuleBase[T]( + description: String, + protected val callFinder: RemoteCalcCallFinder) + extends RelOptRule(operand(classOf[FlinkLogicalCalc], any), description) { + + // Consider the rules to be equal if they are the same class and their call finders are the same + // class. + override def equals(obj: Any): Boolean = { + obj match { + case base: RemoteCalcSplitRuleBase[_] => + super.equals(base) && callFinder.getClass.equals(base.callFinder.getClass) + case _ => false + } + } + + override def onMatch(call: RelOptRuleCall): Unit = { + val calc: FlinkLogicalCalc = call.rel(0).asInstanceOf[FlinkLogicalCalc] + val input = calc.getInput + val rexBuilder = call.builder().getRexBuilder + val program = calc.getProgram + val extractedRexNodes = new mutable.ArrayBuffer[RexNode]() + + val extractedFunctionOffset = input.getRowType.getFieldCount + val matchState = getMatchState; + val splitter = new ScalarFunctionSplitter( + program, + rexBuilder, + extractedFunctionOffset, + extractedRexNodes, + new Function[RexNode, Boolean] { + override def apply(node: RexNode): Boolean = needConvert(program, node, matchState) + }, + callFinder) + + val splitComponents = split(program, splitter) + val accessedFields = + extractRefInputFields( + splitComponents.topCalcProjects, + splitComponents.topCalcCondition, + extractedFunctionOffset) + + val bottomCalcProjects = + accessedFields.map(RexInputRef.of(_, input.getRowType)) ++ extractedRexNodes + val bottomCalcFieldNames = SqlValidatorUtil.uniquify( + accessedFields.map(i => input.getRowType.getFieldNames.get(i)).toSeq ++ + extractedRexNodes.indices.map("f" + _), + rexBuilder.getTypeFactory.getTypeSystem.isSchemaCaseSensitive + ) + + val bottomCalc = new FlinkLogicalCalc( + calc.getCluster, + calc.getTraitSet, + input, + RexProgram.create( + input.getRowType, + bottomCalcProjects.toList, + splitComponents.bottomCalcCondition.orNull, + bottomCalcFieldNames, + rexBuilder)) + + val inputRewriter = new ExtractedFunctionInputRewriter( + calc.getCluster.getRexBuilder, + extractedFunctionOffset, + accessedFields) + val topCalc = new FlinkLogicalCalc( + calc.getCluster, + calc.getTraitSet, + bottomCalc, + RexProgram.create( + bottomCalc.getRowType, + splitComponents.topCalcProjects.map(_.accept(inputRewriter)), + splitComponents.topCalcCondition.map(_.accept(inputRewriter)).orNull, + calc.getRowType, + rexBuilder + )) + + call.transformTo(topCalc) + } + + /** Extracts the indices of the input fields referred by the specified projects and condition. */ + private def extractRefInputFields( + projects: Seq[RexNode], + condition: Option[RexNode], + inputFieldsCount: Int): Array[Int] = { + val visitor = new InputRefVisitor + + // extract referenced input fields from projections + projects.foreach(exp => exp.accept(visitor)) + + // extract referenced input fields from condition + condition.foreach(_.accept(visitor)) + + // fields of indexes greater than inputFieldsCount is the extracted functions and + // should be filtered as they are not from the original input + visitor.getFields.filter(_ < inputFieldsCount) + } + + /** Returns true if need to convert the specified node. */ + def getMatchState: Option[T] = { + Option.empty + } + + /** Returns true if need to convert the specified node. */ + def needConvert(program: RexProgram, node: RexNode, matchState: Option[T]): Boolean + + /** + * Splits the specified [[RexProgram]] using the specified [[ScalarFunctionSplitter]]. It returns + * a triple of (bottom calc condition, top calc condition, top calc projects) as the split result. + */ + def split(program: RexProgram, splitter: ScalarFunctionSplitter): SplitComponents +} + +/** + * The components for splitting a single calc into two calcs. + * + * @param bottomCalcCondition + * Which RexNode should be a condition in the bottom calc + * @param topCalcCondition + * Which RexNode should be a condition in the top calc + * @param topCalcProjects + * Which RexNodes should be projections in the top calc + */ +class SplitComponents( + var bottomCalcCondition: Option[RexNode], + var topCalcCondition: Option[RexNode], + var topCalcProjects: Seq[RexNode]) {} + +/** + * Rule that splits [[FlinkLogicalCalc]]s which contain Remote functions in the condition into + * multiple [[FlinkLogicalCalc]]s. After this rule is applied, there will be no Remote functions in + * the condition of the [[FlinkLogicalCalc]]s. + */ +class RemoteCalcSplitConditionRule(callFinder: RemoteCalcCallFinder) + extends RemoteCalcSplitRuleBase("RemoteCalcSplitConditionRule", callFinder) { + + override def matches(call: RelOptRuleCall): Boolean = { + val calc: FlinkLogicalCalc = call.rel(0).asInstanceOf[FlinkLogicalCalc] + + // matches if it contains Remote functions in condition + Option(calc.getProgram.getCondition) + .map(calc.getProgram.expandLocalRef) + .exists(callFinder.containsRemoteCall) + } + + override def needConvert( + program: RexProgram, + node: RexNode, + matchState: Option[Nothing]): Boolean = + callFinder.isRemoteCall(node) + + override def split(program: RexProgram, splitter: ScalarFunctionSplitter): SplitComponents = { + new SplitComponents( + None, + Option(program.getCondition).map(program.expandLocalRef(_).accept(splitter)), + program.getProjectList.map(program.expandLocalRef)) + } +} + +abstract class RemoteCalcSplitProjectionRuleBase[T]( + description: String, + callFinder: RemoteCalcCallFinder) + extends RemoteCalcSplitRuleBase[T](description, callFinder) { + + override def split(program: RexProgram, splitter: ScalarFunctionSplitter): SplitComponents = { + new SplitComponents( + Option(program.getCondition).map(program.expandLocalRef), + None, + program.getProjectList.map(program.expandLocalRef(_).accept(splitter))) + } +} + +abstract class RemoteCalcSplitRexFieldRuleBase( + description: String, + callFinder: RemoteCalcCallFinder) + extends RemoteCalcSplitRuleBase(description, callFinder) { + + override def needConvert( + program: RexProgram, + node: RexNode, + matchState: Option[Nothing]): Boolean = { + node match { + case x: RexFieldAccess => + x.getReferenceExpr match { + case y: RexLocalRef if callFinder.containsRemoteCall(program.expandLocalRef(y)) => true + case _ => false + } + case _ => false + } + } + + protected def containsFieldAccessAfterRemoteCall(node: RexNode): Boolean = { + node match { + case call: RexCall => call.getOperands.exists(containsFieldAccessAfterRemoteCall) + case x: RexFieldAccess => callFinder.containsRemoteCall(x.getReferenceExpr) + case _ => false + } + } +} + +/** + * Rule that splits the RexField with the input of Remote function contained in the projection of + * [[FlinkLogicalCalc]]s. + */ +class RemoteCalcSplitProjectionRexFieldRule(callFinder: RemoteCalcCallFinder) + extends RemoteCalcSplitRexFieldRuleBase("RemoteCalcSplitProjectionRexFieldRule", callFinder) { + + override def matches(call: RelOptRuleCall): Boolean = { + val calc: FlinkLogicalCalc = call.rel(0).asInstanceOf[FlinkLogicalCalc] + + val projects = calc.getProgram.getProjectList.map(calc.getProgram.expandLocalRef) + projects.exists(containsFieldAccessAfterRemoteCall) + } + + override def split(program: RexProgram, splitter: ScalarFunctionSplitter): SplitComponents = { + new SplitComponents( + Option(program.getCondition).map(program.expandLocalRef), + None, + program.getProjectList.map(_.accept(splitter))) + } +} + +/** + * Rule that splits the RexField with the input of Remote function contained in the condition of + * [[FlinkLogicalCalc]]s. + */ +class RemoteCalcSplitConditionRexFieldRule(callFinder: RemoteCalcCallFinder) + extends RemoteCalcSplitRexFieldRuleBase("RemoteCalcSplitConditionRexFieldRule", callFinder) { + + override def matches(call: RelOptRuleCall): Boolean = { + val calc: FlinkLogicalCalc = call.rel(0).asInstanceOf[FlinkLogicalCalc] + + Option(calc.getProgram.getCondition) + .map(calc.getProgram.expandLocalRef) + .exists(containsFieldAccessAfterRemoteCall) + } + + override def split(program: RexProgram, splitter: ScalarFunctionSplitter): SplitComponents = { + new SplitComponents( + None, + Option(program.getCondition).map(_.accept(splitter)), + program.getProjectList.map(_.accept(splitter))) + } +} + +/** + * Rule that splits [[FlinkLogicalCalc]]s which contain both Java functions and Remote functions in + * the projection into multiple [[FlinkLogicalCalc]]s. After this rule is applied, it will only + * contain Remote functions or Java functions in the projection of each [[FlinkLogicalCalc]]. + */ +class RemoteCalcSplitProjectionRule(callFinder: RemoteCalcCallFinder) + extends RemoteCalcSplitProjectionRuleBase("RemoteCalcSplitProjectionRule", callFinder) { + + override def matches(call: RelOptRuleCall): Boolean = { + val calc: FlinkLogicalCalc = call.rel(0).asInstanceOf[FlinkLogicalCalc] + val projects = calc.getProgram.getProjectList.map(calc.getProgram.expandLocalRef) + + // matches if it contains both Remote functions and Java functions in the projection + projects.exists(callFinder.containsRemoteCall) && projects.exists( + callFinder.containsNonRemoteCall) + } + + override def needConvert( + program: RexProgram, + node: RexNode, + matchState: Option[Nothing]): Boolean = { + program.getProjectList + .map(program.expandLocalRef) + .exists(callFinder.isNonRemoteCall) == callFinder.isRemoteCall(node) + } +} + +/** + * Rule that expands the RexFieldAccess inputs of Remote functions contained in the projection of + * [[FlinkLogicalCalc]]s. + */ +class RemoteCalcExpandProjectRule(callFinder: RemoteCalcCallFinder) + extends RemoteCalcSplitRuleBase("RemoteCalcExpandProjectRule", callFinder) { + + override def matches(call: RelOptRuleCall): Boolean = { + val calc: FlinkLogicalCalc = call.rel(0).asInstanceOf[FlinkLogicalCalc] + val projects = calc.getProgram.getProjectList.map(calc.getProgram.expandLocalRef) + + projects.exists(callFinder.containsRemoteCall) && projects.exists(containsFieldAccessInputs) + } + + override def needConvert( + program: RexProgram, + node: RexNode, + matchState: Option[Nothing]): Boolean = + node.isInstanceOf[RexFieldAccess] + + override def split(program: RexProgram, splitter: ScalarFunctionSplitter): SplitComponents = { + new SplitComponents( + Option(program.getCondition).map(program.expandLocalRef), + None, + program.getProjectList.map(program.expandLocalRef(_).accept(splitter))) + } + + private def containsFieldAccessInputs(node: RexNode): Boolean = { + node match { + case call: RexCall => call.getOperands.exists(containsFieldAccessInputs) + case _: RexFieldAccess => true + case _ => false + } + } +} + +/** + * Rule that pushes the condition of [[FlinkLogicalCalc]]s before it for the [[FlinkLogicalCalc]]s + * which contain Remote functions in the projection. + */ +class RemoteCalcPushConditionRule(callFinder: RemoteCalcCallFinder) + extends RemoteCalcSplitRuleBase("RemoteCalcPushConditionRule", callFinder) { + + override def matches(call: RelOptRuleCall): Boolean = { + val calc: FlinkLogicalCalc = call.rel(0).asInstanceOf[FlinkLogicalCalc] + val projects = calc.getProgram.getProjectList.map(calc.getProgram.expandLocalRef) + + // matches if all the following conditions hold true: + // 1) the condition is not null + // 2) it contains Remote functions in the projection + calc.getProgram.getCondition != null && projects.exists(callFinder.containsRemoteCall) + } + + override def needConvert( + program: RexProgram, + node: RexNode, + matchState: Option[Nothing]): Boolean = + callFinder.isNonRemoteCall(node) + + override def split(program: RexProgram, splitter: ScalarFunctionSplitter): SplitComponents = { + new SplitComponents( + Option(program.getCondition).map(program.expandLocalRef), + None, + program.getProjectList.map(program.expandLocalRef)) + } +} + +/** + * Rule that ensures that it only contains [[RexInputRef]]s at the beginning of the project list and + * [[RexCall]]s at the end of the project list for [[FlinkLogicalCalc]]s which contain Remote + * functions in the projection. This rule exists to keep implementations as simple as possible and + * ensures that it only needs to handle the Remote function execution. + */ +class RemoteCalcRewriteProjectionRule(callFinder: RemoteCalcCallFinder) + extends RemoteCalcSplitRuleBase("RemoteCalcRewriteProjectionRule", callFinder) { + + override def matches(call: RelOptRuleCall): Boolean = { + val calc: FlinkLogicalCalc = call.rel(0).asInstanceOf[FlinkLogicalCalc] + val projects = calc.getProgram.getProjectList.map(calc.getProgram.expandLocalRef) + + // matches if all the following conditions hold true: + // 1) it contains Remote functions in the projection + // 2) it contains RexNodes besides RexInputRef and RexCall or + // not all the RexCalls lying at the end of the project list + projects.exists(callFinder.containsRemoteCall) && + (projects.exists(expr => !expr.isInstanceOf[RexCall] && !expr.isInstanceOf[RexInputRef]) || + projects.indexWhere(_.isInstanceOf[RexCall]) < + projects.lastIndexWhere(_.isInstanceOf[RexInputRef])) + } + + override def needConvert( + program: RexProgram, + node: RexNode, + matchState: Option[Nothing]): Boolean = + callFinder.isRemoteCall(node) + + override def split(program: RexProgram, splitter: ScalarFunctionSplitter): SplitComponents = { + new SplitComponents( + None, + None, + program.getProjectList.map(program.expandLocalRef(_).accept(splitter))) + } +} + +class ScalarFunctionSplitter( + program: RexProgram, + rexBuilder: RexBuilder, + extractedFunctionOffset: Int, + extractedRexNodes: mutable.ArrayBuffer[RexNode], + needConvert: Function[RexNode, Boolean], + callFinder: RemoteCalcCallFinder) + extends RexDefaultVisitor[RexNode] { + + private var fieldsRexCall: Map[Int, Int] = Map[Int, Int]() + + override def visitCall(call: RexCall): RexNode = { + if (needConvert(call)) { + getExtractedRexNode(call) + } else { + call.clone(call.getType, call.getOperands.asScala.map(_.accept(this))) + } + } + + override def visitFieldAccess(fieldAccess: RexFieldAccess): RexNode = { + if (needConvert(fieldAccess)) { + val expr = fieldAccess.getReferenceExpr + expr match { + case localRef: RexLocalRef + if callFinder.containsRemoteCall(program.expandLocalRef(localRef)) => + getExtractedRexFieldAccess(fieldAccess, localRef.getIndex) + case _: RexCorrelVariable => + val field = fieldAccess.getField + new RexInputRef(field.getIndex, field.getType) + case _ => + val newFieldAccess = + rexBuilder.makeFieldAccess(expr.accept(this), fieldAccess.getField.getIndex) + getExtractedRexNode(newFieldAccess) + } + } else { + fieldAccess + } + } + + override def visitLocalRef(localRef: RexLocalRef): RexNode = { + program.getExprList.get(localRef.getIndex).accept(this) + } + + override def visitNode(rexNode: RexNode): RexNode = rexNode + + private def getExtractedRexNode(node: RexNode): RexNode = { + val newNode = new RexInputRef(extractedFunctionOffset + extractedRexNodes.length, node.getType) + extractedRexNodes.append(node) + newNode + } + + private def getExtractedRexFieldAccess(node: RexFieldAccess, rexCallIndex: Int): RexNode = { + val remoteCall: RexCall = + program.expandLocalRef(node.getReferenceExpr.asInstanceOf[RexLocalRef]).asInstanceOf[RexCall] + if (!fieldsRexCall.contains(rexCallIndex)) { + extractedRexNodes.append(remoteCall) + fieldsRexCall += rexCallIndex -> (extractedFunctionOffset + extractedRexNodes.length - 1) + } + rexBuilder.makeFieldAccess( + new RexInputRef(fieldsRexCall(rexCallIndex), remoteCall.getType), + node.getField.getIndex) + } +} + +/** + * Rewrite field accesses of a RexNode as not all the fields from the original input are forwarded: + * 1) Fields of index greater than or equal to extractedFunctionOffset refer to the extracted + * function. 2) Fields of index less than extractedFunctionOffset refer to the original input field. + * + * @param rexBuilder + * the RexBuilder + * @param extractedFunctionOffset + * the original start offset of the extracted functions + * @param accessedFields + * the accessed fields which will be forwarded + */ +private class ExtractedFunctionInputRewriter( + rexBuilder: RexBuilder, + extractedFunctionOffset: Int, + accessedFields: Array[Int]) + extends RexDefaultVisitor[RexNode] { + + /** old input fields ref index -> new input fields ref index mappings */ + private val fieldMap: Map[Int, Int] = accessedFields.zipWithIndex.toMap + + override def visitInputRef(inputRef: RexInputRef): RexNode = { + if (inputRef.getIndex >= extractedFunctionOffset) { + new RexInputRef( + inputRef.getIndex - extractedFunctionOffset + accessedFields.length, + inputRef.getType) + } else { + new RexInputRef( + fieldMap.getOrElse( + inputRef.getIndex, + throw new IllegalArgumentException("input field contains invalid index")), + inputRef.getType) + } + } + + override def visitCall(call: RexCall): RexNode = { + call.clone(call.getType, call.getOperands.asScala.map(_.accept(this))) + } + + override def visitFieldAccess(fieldAccess: RexFieldAccess): RexNode = { + rexBuilder.makeFieldAccess( + fieldAccess.getReferenceExpr.accept(this), + fieldAccess.getField.getIndex) + } + + override def visitNode(rexNode: RexNode): RexNode = rexNode +} diff --git a/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/rules/physical/stream/StreamPhysicalCalcRule.scala b/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/rules/physical/stream/StreamPhysicalCalcRule.scala --- a/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/rules/physical/stream/StreamPhysicalCalcRule.scala +++ b/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/rules/physical/stream/StreamPhysicalCalcRule.scala @@ -20,6 +20,8 @@ package org.apache.flink.table.planner.plan.rules.physical.stream import org.apache.flink.table.planner.plan.nodes.FlinkConventions import org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalCalc import org.apache.flink.table.planner.plan.nodes.physical.stream.StreamPhysicalCalc +import org.apache.flink.table.planner.plan.utils.AsyncUtil +import org.apache.flink.table.planner.plan.utils.AsyncUtil.containsAsyncCall import org.apache.flink.table.planner.plan.utils.PythonUtil.containsPythonCall import org.apache.calcite.plan.{RelOptRule, RelOptRuleCall, RelTraitSet} @@ -35,7 +37,8 @@ class StreamPhysicalCalcRule(config: Config) extends ConverterRule(config) { override def matches(call: RelOptRuleCall): Boolean = { val calc: FlinkLogicalCalc = call.rel(0) val program = calc.getProgram - !program.getExprList.asScala.exists(containsPythonCall(_)) + !program.getExprList.asScala.exists(containsPythonCall(_)) && + !program.getExprList.asScala.exists(containsAsyncCall) } def convert(rel: RelNode): RelNode = { diff --git a/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/calc/async/AsyncFunctionRunner.java b/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/calc/async/AsyncFunctionRunner.java new file mode 100644 --- /dev/null +++ b/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/calc/async/AsyncFunctionRunner.java @@ -0,0 +1,68 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.flink.table.runtime.operators.calc.async; + +import org.apache.flink.api.common.functions.OpenContext; +import org.apache.flink.api.common.functions.util.FunctionUtils; +import org.apache.flink.streaming.api.functions.async.AsyncFunction; +import org.apache.flink.streaming.api.functions.async.ResultFuture; +import org.apache.flink.streaming.api.functions.async.RichAsyncFunction; +import org.apache.flink.table.data.RowData; +import org.apache.flink.table.runtime.generated.GeneratedFunction; + +/** + * Async function runner for {@link org.apache.flink.table.functions.AsyncScalarFunction}, which + * takes the generated function, instantiates it, and then calls its lifecycle methods. + */ +public class AsyncFunctionRunner extends RichAsyncFunction { + + private static final long serialVersionUID = -6664660022391632123L; + + private final GeneratedFunction> generatedFetcher; + + private transient AsyncFunction fetcher; + + public AsyncFunctionRunner( + GeneratedFunction> generatedFetcher) { + this.generatedFetcher = generatedFetcher; + } + + @Override + public void open(OpenContext openContext) throws Exception { + super.open(openContext); + fetcher = generatedFetcher.newInstance(getRuntimeContext().getUserCodeClassLoader()); + FunctionUtils.setFunctionRuntimeContext(fetcher, getRuntimeContext()); + FunctionUtils.openFunction(fetcher, openContext); + } + + @Override + public void asyncInvoke(RowData input, ResultFuture resultFuture) { + try { + fetcher.asyncInvoke(input, resultFuture); + } catch (Throwable t) { + resultFuture.completeExceptionally(t); + } + } + + @Override + public void close() throws Exception { + super.close(); + FunctionUtils.closeFunction(fetcher); + } +} diff --git a/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/calc/async/DelegatingAsyncResultFuture.java b/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/calc/async/DelegatingAsyncResultFuture.java new file mode 100644 --- /dev/null +++ b/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/calc/async/DelegatingAsyncResultFuture.java @@ -0,0 +1,84 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.flink.table.runtime.operators.calc.async; + +import org.apache.flink.streaming.api.functions.async.ResultFuture; +import org.apache.flink.table.data.RowData; +import org.apache.flink.table.data.conversion.DataStructureConverter; +import org.apache.flink.util.Preconditions; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.function.BiConsumer; +import java.util.function.Function; + +/** + * Inspired by {@link org.apache.flink.table.runtime.operators.join.lookup.DelegatingResultFuture} + * for {@link org.apache.flink.table.functions.AsyncScalarFunction}. + */ +public class DelegatingAsyncResultFuture implements BiConsumer { + + private final ResultFuture delegatedResultFuture; + private final List synchronousResults = new ArrayList<>(); + private Function outputFactory; + private CompletableFuture future; + private CompletableFuture convertedFuture; + + public DelegatingAsyncResultFuture(ResultFuture delegatedResultFuture) { + this.delegatedResultFuture = delegatedResultFuture; + } + + public synchronized void addSynchronousResult(Object object) { + synchronousResults.add(object); + } + + public synchronized Object getSynchronousResult(int index) { + return synchronousResults.get(index); + } + + public void setOutputFactory(Function outputFactory) { + this.outputFactory = outputFactory; + } + + public CompletableFuture createAsyncFuture( + DataStructureConverter converter) { + Preconditions.checkState(future == null); + Preconditions.checkState(convertedFuture == null); + Preconditions.checkNotNull(outputFactory); + future = new CompletableFuture<>(); + convertedFuture = future.thenApply(converter::toInternal); + this.convertedFuture.whenComplete(this); + return future; + } + + @Override + public void accept(Object o, Throwable throwable) { + if (throwable != null) { + delegatedResultFuture.completeExceptionally(throwable); + } else { + try { + RowData rowData = outputFactory.apply(o); + delegatedResultFuture.complete(java.util.Collections.singleton(rowData)); + } catch (Throwable t) { + delegatedResultFuture.completeExceptionally(t); + } + } + } +} diff --git a/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/calc/async/RetryPredicates.java b/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/calc/async/RetryPredicates.java new file mode 100644 --- /dev/null +++ b/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/calc/async/RetryPredicates.java @@ -0,0 +1,55 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.flink.table.runtime.operators.calc.async; + +import org.apache.flink.table.data.RowData; + +import java.io.Serializable; +import java.util.Collection; +import java.util.function.Predicate; + +/** Contains retry predicates used to determine if a result or error should result in a retry. */ +public class RetryPredicates { + + public static final EmptyResponseResultStrategy EMPTY_RESPONSE = + new EmptyResponseResultStrategy(); + public static final Predicate ANY_EXCEPTION = new AnyExceptionStrategy(); + + /** Returns true if the response is null or empty. */ + public static class EmptyResponseResultStrategy + implements Predicate>, Serializable { + private static final long serialVersionUID = 5065281655787318565L; + + @Override + public boolean test(Collection c) { + return null == c || c.isEmpty(); + } + } + + /** Returns true for any exception. */ + public static class AnyExceptionStrategy implements Predicate, Serializable { + + private static final long serialVersionUID = -46468466280154192L; + + @Override + public boolean test(Throwable throwable) { + return true; + } + } +}