twalthr commented on code in PR #23975:
URL: https://github.com/apache/flink/pull/23975#discussion_r1442740953
##########
flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/config/ExecutionConfigOptions.java:
##########
@@ -692,6 +734,14 @@ public enum AsyncOutputMode {
ALLOW_UNORDERED
}
+ /** Retry strategy in the case of failure. */
+ @Experimental
Review Comment:
drop the annotation, it should be well tested already
##########
docs/layouts/shortcodes/generated/execution_config_configuration.html:
##########
@@ -26,6 +26,36 @@
<td>Duration</td>
<td>The async timeout for the asynchronous operation to
complete.</td>
</tr>
+ <tr>
+ <td><h5>table.exec.async-scalar.buffer-capacity</h5><br> <span
class="label label-primary">Streaming</span></td>
+ <td style="word-wrap: break-word;">10</td>
+ <td>Integer</td>
+ <td>The max number of async i/o operation that the async lookup
join can trigger.</td>
+ </tr>
+ <tr>
+ <td><h5>table.exec.async-scalar.max-attempts</h5><br> <span
class="label label-primary">Streaming</span></td>
+ <td style="word-wrap: break-word;">3</td>
+ <td>Integer</td>
+ <td>The max number of async retry attempts to make when </td>
Review Comment:
incomplete sentence
##########
docs/layouts/shortcodes/generated/execution_config_configuration.html:
##########
@@ -26,6 +26,36 @@
<td>Duration</td>
<td>The async timeout for the asynchronous operation to
complete.</td>
</tr>
+ <tr>
+ <td><h5>table.exec.async-scalar.buffer-capacity</h5><br> <span
class="label label-primary">Streaming</span></td>
+ <td style="word-wrap: break-word;">10</td>
+ <td>Integer</td>
+ <td>The max number of async i/o operation that the async lookup
join can trigger.</td>
+ </tr>
+ <tr>
+ <td><h5>table.exec.async-scalar.max-attempts</h5><br> <span
class="label label-primary">Streaming</span></td>
+ <td style="word-wrap: break-word;">3</td>
+ <td>Integer</td>
+ <td>The max number of async retry attempts to make when </td>
+ </tr>
+ <tr>
+ <td><h5>table.exec.async-scalar.retry-delay</h5><br> <span
class="label label-primary">Streaming</span></td>
+ <td style="word-wrap: break-word;">100 ms</td>
+ <td>Duration</td>
+ <td>The delay to wait before trying again.</td>
+ </tr>
+ <tr>
+ <td><h5>table.exec.async-scalar.retry-strategy</h5><br> <span
class="label label-primary">Streaming</span></td>
+ <td style="word-wrap: break-word;">FIXED_DELAY</td>
+ <td><p>Enum</p></td>
+ <td>Restart strategy which will be used, FIXED_DELAY by
default.<br /><br />Possible values:<ul><li>"FIXED_DELAY"</li></ul></td>
Review Comment:
an enum with just 1 value makes not much sense, what other strategies can we
offer. I see at least a "no retry" one?
##########
flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/UserDefinedFunctionHelper.java:
##########
@@ -67,6 +67,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";
Review Comment:
Add special validation for this method to check that the return type is
always void and the first arg is always CompletableFuture. Otherwise users
might get a weird error for `eval(int i)` in DataTypeExtractor.
##########
flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/extraction/DataTypeExtractor.java:
##########
@@ -155,6 +157,48 @@ 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];
+ // Trusty library allows to resolve generic types where the type
resolves to a type with
+ // generic parameters...
+ parameterType =
TypeToken.of(baseClass).resolveType(parameterType).getType();
Review Comment:
Can you give a concrete example where this line is necessary? Personally, I
would like to avoid deps to Guava in these crucial utils.
`extractDataTypeWithClassContext` is able to perform the same purpose and
resolve vars.
I think we can drop this line if we validate for a CompletableFuture in the
helper as mentioned above.
##########
flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/AsyncScalarFunction.java:
##########
@@ -0,0 +1,104 @@
+/*
+ * 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.Experimental;
+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.
+ *
+ * <p>The behavior of a {@link AsyncScalarFunction} can be defined by
implementing a custom
+ * evaluation method. An evaluation method must be declared publicly and named
<code>eval</code>.
+ * Evaluation methods can also be overloaded by implementing multiple methods
named <code>eval
+ * </code>. 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.
+ *
+ * <p>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.
+ *
+ * <p>The following examples show how to specify an async scalar function:
+ *
+ * <pre>{@code
+ * // a function that accepts two INT arguments and computes a sum
+ * class SumFunction extends AsyncScalarFunction {
+ * public void eval(CompletableFuture<Integer> 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<String> future, int i) {
+ * return future.complete(String.valueOf(i));
+ * }
+ * public void eval(CompletableFuture<String> 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<String> 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<String> 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<BigDecimal> future,
+ * Long... values) {
+ * // ...
+ * }
+ * }
+ * }</pre>
+ *
+ * <p>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).
+ */
+@Experimental
+public class AsyncScalarFunction extends UserDefinedFunction {
Review Comment:
Add a reference to this function in the "see also" section of
`UserDefinedFunction`.
##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/codegen/AsyncCodeGenerator.java:
##########
@@ -0,0 +1,227 @@
+/*
+ * 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.api.ValidationException;
+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.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 outRowClass The class used to generate the output 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<AsyncFunction<RowData, RowData>>
generateFunction(
+ String name,
+ RowType inputType,
+ RowType returnType,
+ Class<? extends RowData> outRowClass,
+ List<RexNode> calcProjection,
+ boolean retainHeader,
+ ReadableConfig tableConfig,
+ ClassLoader classLoader) {
+ CodeGeneratorContext ctx = new CodeGeneratorContext(tableConfig,
classLoader);
+ String processCode =
+ generateProcessCode(
+ ctx,
+ inputType,
+ returnType,
+ outRowClass,
+ 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<AsyncFunction<RowData, RowData>> getFunctionClass() {
+ return (Class<AsyncFunction<RowData, RowData>>) (Object)
AsyncFunction.class;
+ }
+
+ private static String generateProcessCode(
+ CodeGeneratorContext ctx,
+ RowType inputType,
+ RowType outRowType,
+ Class<? extends RowData> outRowClass,
+ List<RexNode> 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<GeneratedExpression> 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<String, String> values = new HashMap<>();
+ values.put("delegatingFuture", delegatingFutureTerm);
+ values.put("collectorTerm", collectorTerm);
+ values.put("typeTerm", outRowClass.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
org.apache.flink.table.runtime.operators.calc.async.DelegatingAsyncResultFuture
${delegatingFuture} ",
Review Comment:
Use DelegatingAsyncResultFuture.class.getName() utilities instead otherwise
refactoring or moving classes might become harder for someone else.
##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/common/CommonExecAsyncCalc.java:
##########
@@ -0,0 +1,175 @@
+/*
+ * 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.GenericRowData;
+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 org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+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<RowData>
+ implements SingleTransformationTranslator<RowData> {
+
+ private static final Logger LOG =
LoggerFactory.getLogger(CommonExecAsyncCalc.class);
+
+ public static final String ASYNC_CALC_TRANSFORMATION = "async-calc";
+
+ public static final String FIELD_NAME_PROJECTION = "projection";
+
+ public static final String FIELD_NAME_SYNC_MODE = "syncMode";
+
+ @JsonProperty(FIELD_NAME_PROJECTION)
+ private final List<RexNode> projection;
+
+ public CommonExecAsyncCalc(
+ int id,
+ ExecNodeContext context,
+ ReadableConfig persistedConfig,
+ List<RexNode> projection,
+ List<InputProperty> 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<RowData> translateToPlanInternal(
+ PlannerBase planner, ExecNodeConfig config) {
+ final ExecEdge inputEdge = getInputEdges().get(0);
+ final Transformation<RowData> inputTransform =
+ (Transformation<RowData>) inputEdge.translateToPlan(planner);
+ return createAsyncOneInputTransformation(
+ inputTransform, config,
planner.getFlinkContext().getClassLoader());
+ }
+
+ private OneInputTransformation<RowData, RowData>
createAsyncOneInputTransformation(
+ Transformation<RowData> inputTransform,
+ ExecNodeConfig config,
+ ClassLoader classLoader) {
+ List<RexCall> asyncRexCalls =
+ projection.stream()
+ .filter(x -> x instanceof RexCall)
+ .map(x -> (RexCall) x)
+ .collect(Collectors.toList());
+
+ List<Integer> forwardedFields =
+ projection.stream()
+ .filter(x -> x instanceof RexInputRef)
+ .map(x -> ((RexInputRef) x).getIndex())
+ .collect(Collectors.toList());
+ InternalTypeInfo<RowData> asyncOperatorInputTypeInfo =
+ (InternalTypeInfo<RowData>) inputTransform.getOutputType();
+ LogicalType[] inputLogicalTypes =
+ ((InternalTypeInfo<RowData>)
inputTransform.getOutputType()).toRowFieldTypes();
Review Comment:
`toRowFieldTypes` is deprecated, you can get the types from inputEdge.
##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/common/CommonExecAsyncCalc.java:
##########
@@ -0,0 +1,175 @@
+/*
+ * 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.GenericRowData;
+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 org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+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<RowData>
+ implements SingleTransformationTranslator<RowData> {
+
+ private static final Logger LOG =
LoggerFactory.getLogger(CommonExecAsyncCalc.class);
+
+ public static final String ASYNC_CALC_TRANSFORMATION = "async-calc";
+
+ public static final String FIELD_NAME_PROJECTION = "projection";
+
+ public static final String FIELD_NAME_SYNC_MODE = "syncMode";
+
+ @JsonProperty(FIELD_NAME_PROJECTION)
+ private final List<RexNode> projection;
+
+ public CommonExecAsyncCalc(
+ int id,
+ ExecNodeContext context,
+ ReadableConfig persistedConfig,
+ List<RexNode> projection,
+ List<InputProperty> 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<RowData> translateToPlanInternal(
+ PlannerBase planner, ExecNodeConfig config) {
+ final ExecEdge inputEdge = getInputEdges().get(0);
+ final Transformation<RowData> inputTransform =
+ (Transformation<RowData>) inputEdge.translateToPlan(planner);
+ return createAsyncOneInputTransformation(
+ inputTransform, config,
planner.getFlinkContext().getClassLoader());
+ }
+
+ private OneInputTransformation<RowData, RowData>
createAsyncOneInputTransformation(
+ Transformation<RowData> inputTransform,
+ ExecNodeConfig config,
+ ClassLoader classLoader) {
+ List<RexCall> asyncRexCalls =
+ projection.stream()
+ .filter(x -> x instanceof RexCall)
+ .map(x -> (RexCall) x)
+ .collect(Collectors.toList());
+
+ List<Integer> forwardedFields =
+ projection.stream()
+ .filter(x -> x instanceof RexInputRef)
+ .map(x -> ((RexInputRef) x).getIndex())
+ .collect(Collectors.toList());
+ InternalTypeInfo<RowData> asyncOperatorInputTypeInfo =
+ (InternalTypeInfo<RowData>) inputTransform.getOutputType();
+ LogicalType[] inputLogicalTypes =
+ ((InternalTypeInfo<RowData>)
inputTransform.getOutputType()).toRowFieldTypes();
+
+ List<LogicalType> forwardedFieldsLogicalTypes =
+ forwardedFields.stream()
+ .map(i -> inputLogicalTypes[i])
+ .collect(Collectors.toList());
+ List<LogicalType> asyncCallLogicalTypes =
+ asyncRexCalls.stream()
+ .map(node ->
FlinkTypeFactory.toLogicalType(node.getType()))
+ .collect(Collectors.toList());
+ List<LogicalType> fieldsLogicalTypes = new ArrayList<>();
+ fieldsLogicalTypes.addAll(forwardedFieldsLogicalTypes);
+ fieldsLogicalTypes.addAll(asyncCallLogicalTypes);
+ InternalTypeInfo<RowData> asyncOperatorResultTypeInfo =
+ InternalTypeInfo.ofFields(fieldsLogicalTypes.toArray(new
LogicalType[0]));
+ OneInputStreamOperatorFactory<RowData, RowData> factory =
+ getAsyncFunctionOperator(config, classLoader,
asyncOperatorInputTypeInfo);
+ return ExecNodeUtil.createOneInputTransformation(
+ inputTransform,
+ createTransformationMeta(ASYNC_CALC_TRANSFORMATION, config),
+ factory,
+ asyncOperatorResultTypeInfo,
+ inputTransform.getParallelism(),
+ false);
+ }
+
+ private OneInputStreamOperatorFactory<RowData, RowData>
getAsyncFunctionOperator(
+ ExecNodeConfig config,
+ ClassLoader classLoader,
+ InternalTypeInfo<RowData> inputRowTypeInfo) {
+
+ List<LogicalType> resultTypes =
+ projection.stream()
+ .map(node ->
FlinkTypeFactory.toLogicalType(node.getType()))
+ .collect(Collectors.toList());
Review Comment:
create the RowType first and then pass it to the InternalTypeInfo, all code
should use LogicalTypes other types (i.e. InternalTypeInfo) are just derived
from the source of truth
##########
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.api.TableException;
+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 AsyncScalarFunctions. */
+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<RexNode> projection =
+ calcProgram.getProjectList().stream()
+ .map(calcProgram::expandLocalRef)
+ .collect(Collectors.toList());
+ if (calcProgram.getCondition() != null) {
+ throw new TableException("The condition of StreamPhysicalAsyncCalc
should be null.");
Review Comment:
`TableException` will bubble to the user. Rather use `IllegalState` or
`UnsupportedOperation`
##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/rules/logical/AsyncCalcSplitRule.java:
##########
@@ -0,0 +1,194 @@
+/*
+ * 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;
+import scala.Tuple3;
+import scala.collection.Seq;
+
+/**
+ * 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
+ * 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<RexNode> 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.
+ */
+ public static class AsyncCalcSplitNestedRule extends
RemoteCalcSplitRuleBase<Void> {
+
+ 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<RexNode> 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<Void> matchState) {
+ return node instanceof RexCall
+ && !((RexCall) node)
+
.getOperands().stream().anyMatch(callFinder()::containsRemoteCall);
+ }
+
+ @Override
+ public Tuple3<Option<RexNode>, Option<RexNode>, Seq<RexNode>> split(
Review Comment:
Never use Tuple3 or Pair. Use a little helper POJO so that the reader knows
what the components are. Nobody forces to use getters or constructors.
```
class Pojo {
T1 field;
T2 field;
T3 field;
}
```
##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/rules/logical/AsyncCalcSplitRule.java:
##########
@@ -0,0 +1,194 @@
+/*
+ * 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;
+import scala.Tuple3;
+import scala.collection.Seq;
+
+/**
+ * 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
Review Comment:
could you elaborate here what the rules do? I can't easily follow based on a
single sentence:
Some more examples such as:
```
Calc[syncCall(), asyncCall(), syncCall(asyncCall())]
-> Source
becomes
AsyncCalc[syncCall(), asyncCall(), syncCall(asyncCall())]
-> AsyncCalc[syncCall(), asyncCall(), syncCall(asyncCall())]
-> Source
```
##########
flink-connectors/flink-connector-hive/src/main/java/org/apache/flink/table/endpoint/hive/util/OperationExecutorFactory.java:
##########
@@ -579,6 +579,7 @@ private static List<Type> getSupportedHiveType() {
private static int toFunctionResult(FunctionKind kind) {
switch (kind) {
case SCALAR:
+ case ASYNC_SCALAR:
Review Comment:
drop this? Hive doesn't support this function, or at least Hive experts
should review this.
##########
flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/AsyncScalarFunction.java:
##########
@@ -0,0 +1,104 @@
+/*
+ * 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.Experimental;
+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.
+ *
+ * <p>The behavior of a {@link AsyncScalarFunction} can be defined by
implementing a custom
+ * evaluation method. An evaluation method must be declared publicly and named
<code>eval</code>.
+ * Evaluation methods can also be overloaded by implementing multiple methods
named <code>eval
+ * </code>. 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.
+ *
+ * <p>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.
+ *
+ * <p>The following examples show how to specify an async scalar function:
+ *
+ * <pre>{@code
+ * // a function that accepts two INT arguments and computes a sum
+ * class SumFunction extends AsyncScalarFunction {
+ * public void eval(CompletableFuture<Integer> 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<String> future, int i) {
+ * return future.complete(String.valueOf(i));
+ * }
+ * public void eval(CompletableFuture<String> 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<String> 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<String> 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<BigDecimal> future,
+ * Long... values) {
+ * // ...
+ * }
+ * }
+ * }</pre>
+ *
+ * <p>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).
+ */
+@Experimental
+public class AsyncScalarFunction extends UserDefinedFunction {
+ @Override
+ public final FunctionKind getKind() {
+ return FunctionKind.ASYNC_SCALAR;
+ }
+
+ @Override
+ public TypeInference getTypeInference(DataTypeFactory typeFactory) {
+ TypeInference val =
TypeInferenceExtractor.forAsyncScalarFunction(typeFactory, getClass());
Review Comment:
inline variable with return, InitelliJ default settings will print a warning
otherwise
##########
flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/UserDefinedFunctionHelper.java:
##########
@@ -67,6 +67,8 @@ public final class UserDefinedFunctionHelper {
public static final String SCALAR_EVAL = "eval";
+ public static final String ASYNC_SCALAR_EVAL = "eval";
Review Comment:
update `validateImplementationMethods` and add test for it in
`UserDefinedFunctionHelperTest`
##########
flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/AsyncScalarFunction.java:
##########
@@ -0,0 +1,104 @@
+/*
+ * 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.Experimental;
+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.
+ *
+ * <p>The behavior of a {@link AsyncScalarFunction} can be defined by
implementing a custom
+ * evaluation method. An evaluation method must be declared publicly and named
<code>eval</code>.
+ * Evaluation methods can also be overloaded by implementing multiple methods
named <code>eval
+ * </code>. 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.
+ *
+ * <p>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.
+ *
+ * <p>The following examples show how to specify an async scalar function:
+ *
+ * <pre>{@code
+ * // a function that accepts two INT arguments and computes a sum
+ * class SumFunction extends AsyncScalarFunction {
+ * public void eval(CompletableFuture<Integer> 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<String> future, int i) {
+ * return future.complete(String.valueOf(i));
+ * }
+ * public void eval(CompletableFuture<String> 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<String> 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<String> 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<BigDecimal> future,
+ * Long... values) {
+ * // ...
+ * }
+ * }
+ * }</pre>
+ *
+ * <p>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).
+ */
+@Experimental
Review Comment:
Let's mark it @PublicEvoling, we should trust in our implementation.
##########
flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/extraction/FunctionMappingExtractor.java:
##########
@@ -208,6 +249,32 @@ 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];
+ // Trusty library allows to resolve generic types where the type
resolves to a type with
+ // generic parameters...
+ genericType =
TypeToken.of(baseClass).resolveType(genericType).getType();
Review Comment:
Same comment as above. Let's not overly complicate the implementation. The
first parameter should be a CompletableFuture, not a variable. Everything else
is handled in a unified extraction process in `DataTypeExtractor`
##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/codegen/AsyncCodeGenerator.java:
##########
@@ -0,0 +1,227 @@
+/*
+ * 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.api.ValidationException;
+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.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 outRowClass The class used to generate the output 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<AsyncFunction<RowData, RowData>>
generateFunction(
+ String name,
+ RowType inputType,
+ RowType returnType,
+ Class<? extends RowData> outRowClass,
+ List<RexNode> calcProjection,
+ boolean retainHeader,
+ ReadableConfig tableConfig,
+ ClassLoader classLoader) {
+ CodeGeneratorContext ctx = new CodeGeneratorContext(tableConfig,
classLoader);
+ String processCode =
+ generateProcessCode(
+ ctx,
+ inputType,
+ returnType,
+ outRowClass,
+ 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<AsyncFunction<RowData, RowData>> getFunctionClass() {
+ return (Class<AsyncFunction<RowData, RowData>>) (Object)
AsyncFunction.class;
+ }
+
+ private static String generateProcessCode(
+ CodeGeneratorContext ctx,
+ RowType inputType,
+ RowType outRowType,
+ Class<? extends RowData> outRowClass,
+ List<RexNode> 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<GeneratedExpression> 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<String, String> values = new HashMap<>();
+ values.put("delegatingFuture", delegatingFutureTerm);
+ values.put("collectorTerm", collectorTerm);
+ values.put("typeTerm", outRowClass.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(
Review Comment:
It would have been fine to use Scala here. But great that you use Java. The
less Scala the better.
##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/codegen/AsyncCodeGenerator.java:
##########
@@ -0,0 +1,227 @@
+/*
+ * 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.api.ValidationException;
+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.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 outRowClass The class used to generate the output 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<AsyncFunction<RowData, RowData>>
generateFunction(
+ String name,
+ RowType inputType,
+ RowType returnType,
+ Class<? extends RowData> outRowClass,
+ List<RexNode> calcProjection,
+ boolean retainHeader,
+ ReadableConfig tableConfig,
+ ClassLoader classLoader) {
+ CodeGeneratorContext ctx = new CodeGeneratorContext(tableConfig,
classLoader);
+ String processCode =
+ generateProcessCode(
+ ctx,
+ inputType,
+ returnType,
+ outRowClass,
+ 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<AsyncFunction<RowData, RowData>> getFunctionClass() {
+ return (Class<AsyncFunction<RowData, RowData>>) (Object)
AsyncFunction.class;
+ }
+
+ private static String generateProcessCode(
+ CodeGeneratorContext ctx,
+ RowType inputType,
+ RowType outRowType,
+ Class<? extends RowData> outRowClass,
Review Comment:
Seems this is always GenericRowData? Remove parameter.
##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/common/CommonExecAsyncCalc.java:
##########
@@ -0,0 +1,175 @@
+/*
+ * 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.GenericRowData;
+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 org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+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<RowData>
+ implements SingleTransformationTranslator<RowData> {
+
+ private static final Logger LOG =
LoggerFactory.getLogger(CommonExecAsyncCalc.class);
+
+ public static final String ASYNC_CALC_TRANSFORMATION = "async-calc";
+
+ public static final String FIELD_NAME_PROJECTION = "projection";
+
+ public static final String FIELD_NAME_SYNC_MODE = "syncMode";
Review Comment:
please make this class warning free, the IDE says unused same for the LOG
##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/stream/StreamExecAsyncCalc.java:
##########
@@ -0,0 +1,75 @@
+/*
+ * 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 AsyncScalarFunctions. */
+@ExecNodeMetadata(
+ name = "stream-exec-async-calc",
+ version = 1,
+ producedTransformations =
CommonExecAsyncCalc.ASYNC_CALC_TRANSFORMATION,
+ minPlanVersion = FlinkVersion.v1_17,
+ minStateVersion = FlinkVersion.v1_17)
Review Comment:
add the config options that this execnode consumes (i.e. all newly added
options from execution config)
##########
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.api.TableException;
+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 AsyncScalarFunctions. */
Review Comment:
nit: Use JavaDoc to `{@link}` link to AsyncScalarFunctions if an interested
reader wants to learn more. Also in StreamExecNode.
##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/codegen/AsyncCodeGenerator.java:
##########
@@ -0,0 +1,227 @@
+/*
+ * 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.api.ValidationException;
+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.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 outRowClass The class used to generate the output 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<AsyncFunction<RowData, RowData>>
generateFunction(
+ String name,
+ RowType inputType,
+ RowType returnType,
+ Class<? extends RowData> outRowClass,
+ List<RexNode> calcProjection,
+ boolean retainHeader,
+ ReadableConfig tableConfig,
+ ClassLoader classLoader) {
+ CodeGeneratorContext ctx = new CodeGeneratorContext(tableConfig,
classLoader);
+ String processCode =
+ generateProcessCode(
+ ctx,
+ inputType,
+ returnType,
+ outRowClass,
+ 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<AsyncFunction<RowData, RowData>> getFunctionClass() {
+ return (Class<AsyncFunction<RowData, RowData>>) (Object)
AsyncFunction.class;
+ }
+
+ private static String generateProcessCode(
+ CodeGeneratorContext ctx,
+ RowType inputType,
+ RowType outRowType,
+ Class<? extends RowData> outRowClass,
+ List<RexNode> 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<GeneratedExpression> 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<String, String> values = new HashMap<>();
+ values.put("delegatingFuture", delegatingFutureTerm);
+ values.put("collectorTerm", collectorTerm);
+ values.put("typeTerm", outRowClass.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
org.apache.flink.table.runtime.operators.calc.async.DelegatingAsyncResultFuture
${delegatingFuture} ",
+ " = new
org.apache.flink.table.runtime.operators.calc.async.DelegatingAsyncResultFuture(${collectorTerm});",
+ "final org.apache.flink.types.RowKind rowKind =
${inputTerm}.getRowKind();\n",
+ "try {",
+ " java.util.function.Function<Object,
${typeTerm}> outputFactory = ",
+ " new java.util.function.Function<Object,
${typeTerm}>() {",
+ " @Override",
+ " public ${typeTerm} apply(Object resultObject)
{",
+ " final ${typeTerm} ${recordTerm} = new
${typeTerm}(${fieldCount});",
+ " ${outputs}",
+ " return ${recordTerm};",
+ " }",
+ " };",
+ "",
+ "
${delegatingFuture}.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<Void> {
+ 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 ValidationException(
Review Comment:
The validator made sense for TableFunctions, not so much for scalar
functions. If you wanna keep this I would at least change the exception type to
a CodeGenException. ValidationExceptions are intended to bubble to the user.
##########
flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/codegen/calls/BridgingFunctionGenUtil.scala:
##########
@@ -380,7 +411,9 @@ object BridgingFunctionGenUtil {
functionName: String): Unit = {
if (udf.getKind == FunctionKind.TABLE) {
verifyImplementation(TABLE_EVAL, argumentDataTypes, None, udf,
functionName)
- } else if (udf.getKind == FunctionKind.ASYNC_TABLE) {
+ } else if (
+ udf.getKind == FunctionKind.ASYNC_TABLE || udf.getKind ==
FunctionKind.ASYNC_SCALAR
Review Comment:
use a dedicated branch: don't share `ASYNC_TABLE_EVAL` and other parameters
##########
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.api.TableException;
+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 AsyncScalarFunctions. */
+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<RexNode> projection =
+ calcProgram.getProjectList().stream()
+ .map(calcProgram::expandLocalRef)
+ .collect(Collectors.toList());
+ if (calcProgram.getCondition() != null) {
+ throw new TableException("The condition of StreamPhysicalAsyncCalc
should be null.");
+ }
+ if (projection.stream().filter(AsyncUtil::containsAsyncCall).count() >
1) {
+ throw new TableException(
+ "Only a single async projection is allowed in " +
"StreamPhysicalAsyncCalc.");
Review Comment:
Why is that?
##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/common/CommonExecAsyncCalc.java:
##########
@@ -0,0 +1,175 @@
+/*
+ * 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.GenericRowData;
+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 org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+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<RowData>
+ implements SingleTransformationTranslator<RowData> {
+
+ private static final Logger LOG =
LoggerFactory.getLogger(CommonExecAsyncCalc.class);
+
+ public static final String ASYNC_CALC_TRANSFORMATION = "async-calc";
+
+ public static final String FIELD_NAME_PROJECTION = "projection";
+
+ public static final String FIELD_NAME_SYNC_MODE = "syncMode";
+
+ @JsonProperty(FIELD_NAME_PROJECTION)
+ private final List<RexNode> projection;
+
+ public CommonExecAsyncCalc(
+ int id,
+ ExecNodeContext context,
+ ReadableConfig persistedConfig,
+ List<RexNode> projection,
Review Comment:
This is called Calc for a educated reader this means projection+filter. But
where is the filter condition?
##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/stream/StreamExecAsyncCalc.java:
##########
@@ -0,0 +1,75 @@
+/*
+ * 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 AsyncScalarFunctions. */
+@ExecNodeMetadata(
+ name = "stream-exec-async-calc",
+ version = 1,
+ producedTransformations =
CommonExecAsyncCalc.ASYNC_CALC_TRANSFORMATION,
+ minPlanVersion = FlinkVersion.v1_17,
Review Comment:
1.19
##########
flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/codegen/ExpressionReducer.scala:
##########
@@ -65,9 +66,9 @@ class ExpressionReducer(
constExprs: java.util.List[RexNode],
reducedValues: java.util.List[RexNode]): Unit = {
- val pythonUDFExprs = new ListBuffer[RexNode]()
+ val asyncUDFExprs = new ListBuffer[RexNode]()
Review Comment:
you mean `remote`, right? for consistent terminology: remote = python + async
##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/utils/AsyncUtil.java:
##########
@@ -0,0 +1,216 @@
+/*
+ * 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.AsyncScalarFunction;
+import org.apache.flink.table.functions.FunctionDefinition;
+import org.apache.flink.table.planner.functions.bridging.BridgingSqlFunction;
+import org.apache.flink.table.planner.plan.nodes.exec.ExecNodeConfig;
+
+import
org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonCreator;
+
+import org.apache.calcite.rex.RexCall;
+import org.apache.calcite.rex.RexNode;
+
+import java.io.Serializable;
+import java.time.Duration;
+import java.util.Collection;
+import java.util.Objects;
+import java.util.function.Predicate;
+
+/** Contains utilities for AsyncScalarFunctions. */
+public class AsyncUtil {
+
+ private static final EmptyResponseResultStrategy EMPTY_RESPONSE =
+ new EmptyResponseResultStrategy();
+ private static final Predicate<Throwable> ANY_EXCEPTION = new
AnyExceptionStrategy();
+
+ /**
+ * 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<RowData> asyncRetryStrategy;
+
+ @JsonCreator
Review Comment:
Do we need a dedicated JSON serialization for this? Can't we just restore
the instances using the properties from `ExecNodeConfig`? I think we do this
already, right?
##########
flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/rules/physical/stream/StreamPhysicalCalcRule.scala:
##########
@@ -35,7 +36,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(AsyncUtil.containsAsyncCall)
Review Comment:
nit: for consistency also perform a static import, or remove the static
import for PythonUtil
##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/utils/AsyncUtil.java:
##########
@@ -0,0 +1,216 @@
+/*
+ * 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.AsyncScalarFunction;
+import org.apache.flink.table.functions.FunctionDefinition;
+import org.apache.flink.table.planner.functions.bridging.BridgingSqlFunction;
+import org.apache.flink.table.planner.plan.nodes.exec.ExecNodeConfig;
+
+import
org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonCreator;
+
+import org.apache.calcite.rex.RexCall;
+import org.apache.calcite.rex.RexNode;
+
+import java.io.Serializable;
+import java.time.Duration;
+import java.util.Collection;
+import java.util.Objects;
+import java.util.function.Predicate;
+
+/** Contains utilities for AsyncScalarFunctions. */
+public class AsyncUtil {
+
+ private static final EmptyResponseResultStrategy EMPTY_RESPONSE =
+ new EmptyResponseResultStrategy();
+ private static final Predicate<Throwable> ANY_EXCEPTION = new
AnyExceptionStrategy();
+
+ /**
+ * 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<RowData> asyncRetryStrategy;
+
+ @JsonCreator
+ public Options(
+ int asyncBufferCapacity,
+ long asyncTimeout,
+ AsyncDataStream.OutputMode asyncOutputMode,
+ AsyncRetryStrategy<RowData> 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;
+ }
+ }
+
+ private static AsyncRetryStrategy<RowData> getResultRetryStrategy(
+ ExecutionConfigOptions.RetryStrategy retryStrategy,
+ Duration retryDelay,
+ int retryMaxAttempts) {
+ // Only fixed delay is allowed at the moment, so just ignore the
config.
+ return new
AsyncRetryStrategies.FixedDelayRetryStrategyBuilder<RowData>(
+ retryMaxAttempts, retryDelay.toMillis())
+ .ifResult(EMPTY_RESPONSE)
+ .ifException(ANY_EXCEPTION)
+ .build();
+ // return NO_RETRY_STRATEGY;
+ }
+
+ private static class FunctionFinder extends RexDefaultVisitor<Boolean> {
+
+ 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) {
+ if (!(call.getOperator() instanceof BridgingSqlFunction)) {
+ return false;
+ }
+ FunctionDefinition definition =
+ ((BridgingSqlFunction) call.getOperator()).getDefinition();
+ return
AsyncScalarFunction.class.isAssignableFrom(definition.getClass());
+ }
+
+ @Override
+ public Boolean visitCall(RexCall call) {
+ boolean isImmediateAsyncCall = isImmediateAsyncCall(call);
+ return findAsyncCall == isImmediateAsyncCall
+ || (recursive
+ && call.getOperands().stream().anyMatch(node ->
node.accept(this)));
+ }
+ }
+
+ private static class EmptyResponseResultStrategy
+ implements Predicate<Collection<RowData>>, Serializable {
+ private static final long serialVersionUID = 5065281655787318565L;
+
+ @Override
+ public boolean test(Collection<RowData> c) {
+ return null == c || c.isEmpty();
+ }
+ }
+
+ private static class AnyExceptionStrategy implements Predicate<Throwable>,
Serializable {
Review Comment:
this and EmptyResponseResultStrategy seem to be runtime code and should into
`flink-table-runtime`. basically all classes that a TaskManager need should go
there ideally.
##########
flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/rules/FlinkStreamRuleSets.scala:
##########
@@ -382,7 +382,16 @@ object FlinkStreamRuleSets {
PythonCalcSplitRule.PUSH_CONDITION,
PythonCalcSplitRule.REWRITE_PROJECT,
PythonMapRenameRule.INSTANCE,
- PythonMapMergeRule.INSTANCE
+ PythonMapMergeRule.INSTANCE,
+ AsyncCalcSplitRule.SPLIT_CONDITION_REX_FIELD,
+ AsyncCalcSplitRule.SPLIT_PROJECTION_REX_FIELD,
+ AsyncCalcSplitRule.SPLIT_CONDITION,
+ AsyncCalcSplitRule.SPLIT_PROJECT,
+ AsyncCalcSplitRule.EXPAND_PROJECT,
+ AsyncCalcSplitRule.PUSH_CONDITION,
+ AsyncCalcSplitRule.REWRITE_PROJECT,
+ AsyncCalcSplitRule.NESTED_SPLIT,
Review Comment:
I don't know why Python people stopped the habit of adding inline comments.
But a sentence per rule would help a lot to keep this class maintainable. Could
you also add them to the Python ones? Esp. the "why" is interesting, e.g. "why
one calc per split?"
##########
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/codegen/AsyncCodeGeneratorTest.java:
##########
@@ -0,0 +1,228 @@
+/*
+ * 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.Configuration;
+import org.apache.flink.streaming.api.functions.async.AsyncFunction;
+import org.apache.flink.streaming.api.functions.async.ResultFuture;
+import org.apache.flink.table.annotation.DataTypeHint;
+import org.apache.flink.table.catalog.UnresolvedIdentifier;
+import org.apache.flink.table.data.DecimalData;
+import org.apache.flink.table.data.GenericRowData;
+import org.apache.flink.table.data.RowData;
+import org.apache.flink.table.data.StringData;
+import org.apache.flink.table.data.TimestampData;
+import org.apache.flink.table.functions.AsyncScalarFunction;
+import org.apache.flink.table.planner.calcite.FlinkContext;
+import org.apache.flink.table.planner.calcite.SqlToRexConverter;
+import org.apache.flink.table.planner.utils.JavaScalaConversionUtil;
+import org.apache.flink.table.planner.utils.PlannerMocks;
+import org.apache.flink.table.runtime.generated.GeneratedFunction;
+import org.apache.flink.table.types.logical.BigIntType;
+import org.apache.flink.table.types.logical.DecimalType;
+import org.apache.flink.table.types.logical.IntType;
+import org.apache.flink.table.types.logical.RowType;
+import org.apache.flink.table.types.logical.TimestampType;
+import org.apache.flink.table.types.logical.VarCharType;
+import org.apache.flink.table.utils.CatalogManagerMocks;
+
+import org.apache.flink.shaded.guava31.com.google.common.collect.ImmutableList;
+
+import org.apache.calcite.rel.type.RelDataType;
+import org.apache.calcite.rex.RexNode;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.math.BigDecimal;
+import java.time.Instant;
+import java.util.Collection;
+import java.util.List;
+import java.util.concurrent.CompletableFuture;
+import java.util.stream.Collectors;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/** Test for {@link AsyncCodeGenerator}. */
+public class AsyncCodeGeneratorTest {
+
+ private static final RowType INPUT_TYPE =
+ RowType.of(new IntType(), new BigIntType(), new VarCharType());
+
+ private PlannerMocks plannerMocks;
+ private SqlToRexConverter converter;
+
+ private RelDataType tableRowType;
+
+ @BeforeEach
+ public void before() {
+ plannerMocks = PlannerMocks.create();
+ tableRowType =
+ plannerMocks
+ .getPlannerContext()
+ .getTypeFactory()
+ .buildRelNodeRowType(
+
JavaScalaConversionUtil.toScala(ImmutableList.of("f1", "f2", "f3")),
+ JavaScalaConversionUtil.toScala(
+ ImmutableList.of(
+ new IntType(),
+ new BigIntType(),
+ new VarCharType())));
+ converter =
+ plannerMocks
Review Comment:
You might find `ShortcutUtils` useful ;-)
##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/utils/AsyncUtil.java:
##########
@@ -0,0 +1,216 @@
+/*
+ * 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.AsyncScalarFunction;
+import org.apache.flink.table.functions.FunctionDefinition;
+import org.apache.flink.table.planner.functions.bridging.BridgingSqlFunction;
+import org.apache.flink.table.planner.plan.nodes.exec.ExecNodeConfig;
+
+import
org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonCreator;
+
+import org.apache.calcite.rex.RexCall;
+import org.apache.calcite.rex.RexNode;
+
+import java.io.Serializable;
+import java.time.Duration;
+import java.util.Collection;
+import java.util.Objects;
+import java.util.function.Predicate;
+
+/** Contains utilities for AsyncScalarFunctions. */
+public class AsyncUtil {
+
+ private static final EmptyResponseResultStrategy EMPTY_RESPONSE =
+ new EmptyResponseResultStrategy();
+ private static final Predicate<Throwable> ANY_EXCEPTION = new
AnyExceptionStrategy();
+
+ /**
+ * 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<RowData> asyncRetryStrategy;
+
+ @JsonCreator
+ public Options(
+ int asyncBufferCapacity,
+ long asyncTimeout,
+ AsyncDataStream.OutputMode asyncOutputMode,
+ AsyncRetryStrategy<RowData> 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;
+ }
+ }
+
+ private static AsyncRetryStrategy<RowData> getResultRetryStrategy(
+ ExecutionConfigOptions.RetryStrategy retryStrategy,
+ Duration retryDelay,
+ int retryMaxAttempts) {
+ // Only fixed delay is allowed at the moment, so just ignore the
config.
+ return new
AsyncRetryStrategies.FixedDelayRetryStrategyBuilder<RowData>(
+ retryMaxAttempts, retryDelay.toMillis())
+ .ifResult(EMPTY_RESPONSE)
+ .ifException(ANY_EXCEPTION)
+ .build();
+ // return NO_RETRY_STRATEGY;
+ }
+
+ private static class FunctionFinder extends RexDefaultVisitor<Boolean> {
+
+ 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) {
+ if (!(call.getOperator() instanceof BridgingSqlFunction)) {
+ return false;
+ }
+ FunctionDefinition definition =
+ ((BridgingSqlFunction) call.getOperator()).getDefinition();
+ return
AsyncScalarFunction.class.isAssignableFrom(definition.getClass());
Review Comment:
Use `ShortcutUtils#unwrapFunctionDefinition(org.apache.calcite.rex.RexNode)`
instead. The check should be based purely on the
`FunctionDefinition.getKind()`. This allows to work with FunctionDefinition and
defer the need for the actual class in the classpath during planning. See also
`SpecializedFunction`.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]