diff --git a/flink-core-api/src/main/java/org/apache/flink/util/TaggedUnion.java b/flink-core-api/src/main/java/org/apache/flink/util/TaggedUnion.java new file mode 100644 --- /dev/null +++ b/flink-core-api/src/main/java/org/apache/flink/util/TaggedUnion.java @@ -0,0 +1,76 @@ +/* + * 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.util; + +import org.apache.flink.annotation.Internal; + +import java.util.Objects; + +/** + * Utility class for implementing CoGroupedStream in DataStream V1, as well as two-input window + * operations in DataStream V2. + */ +@Internal +public class TaggedUnion { + private final T1 one; + private final T2 two; + + private TaggedUnion(T1 one, T2 two) { + this.one = one; + this.two = two; + } + + public boolean isOne() { + return one != null; + } + + public boolean isTwo() { + return two != null; + } + + public T1 getOne() { + return one; + } + + public T2 getTwo() { + return two; + } + + public static TaggedUnion one(T1 one) { + return new TaggedUnion<>(one, null); + } + + public static TaggedUnion two(T2 two) { + return new TaggedUnion<>(null, two); + } + + @Override + public boolean equals(Object obj) { + if (obj == this) { + return true; + } + + if (!(obj instanceof TaggedUnion)) { + return false; + } + + TaggedUnion other = (TaggedUnion) obj; + return Objects.equals(one, other.one) && Objects.equals(two, other.two); + } +} diff --git a/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/builtin/BuiltinFuncs.java b/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/builtin/BuiltinFuncs.java --- a/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/builtin/BuiltinFuncs.java +++ b/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/builtin/BuiltinFuncs.java @@ -22,7 +22,13 @@ import org.apache.flink.api.java.functions.KeySelector; import org.apache.flink.datastream.api.extension.join.JoinFunction; import org.apache.flink.datastream.api.extension.join.JoinType; +import org.apache.flink.datastream.api.extension.window.function.OneInputWindowStreamProcessFunction; +import org.apache.flink.datastream.api.extension.window.function.TwoInputNonBroadcastWindowStreamProcessFunction; +import org.apache.flink.datastream.api.extension.window.function.TwoOutputWindowStreamProcessFunction; +import org.apache.flink.datastream.api.extension.window.strategy.WindowStrategy; +import org.apache.flink.datastream.api.function.OneInputStreamProcessFunction; import org.apache.flink.datastream.api.function.TwoInputNonBroadcastStreamProcessFunction; +import org.apache.flink.datastream.api.function.TwoOutputStreamProcessFunction; import org.apache.flink.datastream.api.stream.KeyedPartitionStream; import org.apache.flink.datastream.api.stream.NonKeyedPartitionStream; @@ -121,4 +127,89 @@ public static NonKeyedPartitionStream join( joinFunction, joinType); } + + // =================== Window =========================== + + static final Class WINDOW_FUNCS_INSTANCE; + + static { + try { + WINDOW_FUNCS_INSTANCE = + Class.forName("org.apache.flink.datastream.impl.builtin.BuiltinWindowFuncs"); + } catch (ClassNotFoundException e) { + throw new RuntimeException("Please ensure that flink-datastream in your class path"); + } + } + + /** + * Wrap the WindowStrategy and OneInputWindowStreamProcessFunction within a + * OneInputStreamProcessFunction to perform the window operation. + * + * @param windowStrategy the window strategy + * @param windowProcessFunction the window process function + * @return the wrapped process function + */ + public static OneInputStreamProcessFunction window( + WindowStrategy windowStrategy, + OneInputWindowStreamProcessFunction windowProcessFunction) { + try { + return (OneInputStreamProcessFunction) + WINDOW_FUNCS_INSTANCE + .getMethod( + "window", + WindowStrategy.class, + OneInputWindowStreamProcessFunction.class) + .invoke(null, windowStrategy, windowProcessFunction); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + /** + * Wrap the WindowStrategy and TwoInputNonBroadcastWindowStreamProcessFunction within a + * TwoInputNonBroadcastStreamProcessFunction to perform the window operation. + * + * @param windowStrategy the window strategy + * @param windowProcessFunction the window process function + * @return the wrapped process function + */ + public static TwoInputNonBroadcastStreamProcessFunction window( + WindowStrategy windowStrategy, + TwoInputNonBroadcastWindowStreamProcessFunction windowProcessFunction) { + try { + return (TwoInputNonBroadcastStreamProcessFunction) + WINDOW_FUNCS_INSTANCE + .getMethod( + "window", + WindowStrategy.class, + TwoInputNonBroadcastWindowStreamProcessFunction.class) + .invoke(null, windowStrategy, windowProcessFunction); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + /** + * Wrap the WindowStrategy and TwoOutputWindowStreamProcessFunction within a + * TwoOutputStreamProcessFunction to perform the window operation. + * + * @param windowStrategy the window strategy + * @param windowProcessFunction the window process function + * @return the wrapped process function + */ + public static TwoOutputStreamProcessFunction window( + WindowStrategy windowStrategy, + TwoOutputWindowStreamProcessFunction windowProcessFunction) { + try { + return (TwoOutputStreamProcessFunction) + WINDOW_FUNCS_INSTANCE + .getMethod( + "window", + WindowStrategy.class, + TwoOutputWindowStreamProcessFunction.class) + .invoke(null, windowStrategy, windowProcessFunction); + } catch (Exception e) { + throw new RuntimeException(e); + } + } } diff --git a/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/extension/window/context/OneInputWindowContext.java b/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/extension/window/context/OneInputWindowContext.java new file mode 100644 --- /dev/null +++ b/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/extension/window/context/OneInputWindowContext.java @@ -0,0 +1,45 @@ +/* + * 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.datastream.api.extension.window.context; + +import org.apache.flink.annotation.Experimental; + +/** + * This interface extends {@link WindowContext} and provides additional functionality for writing + * and reading window data of one input window. + * + * @param Type of the input elements + */ +@Experimental +public interface OneInputWindowContext extends WindowContext { + + /** + * Write records into the window's state. + * + * @param record The record to be written into the window's state. + */ + void putRecord(IN record); + + /** + * Read records from the window's state. + * + * @return Iterable of records, which could be null if the window is empty. + */ + Iterable getAllRecords(); +} diff --git a/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/extension/window/context/TwoInputWindowContext.java b/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/extension/window/context/TwoInputWindowContext.java new file mode 100644 --- /dev/null +++ b/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/extension/window/context/TwoInputWindowContext.java @@ -0,0 +1,57 @@ +/* + * 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.datastream.api.extension.window.context; + +import org.apache.flink.annotation.Experimental; + +/** + * This interface extends {@link WindowContext} and provides additional functionality for writing + * and reading window data of two input window. + */ +@Experimental +public interface TwoInputWindowContext extends WindowContext { + + /** + * Write records from input1 into the window's state. + * + * @param record The record from input1 to be written into the window's state. + */ + void putRecord1(IN1 record); + + /** + * Read input1's records from the window's state. + * + * @return Iterable of input1's records, which could be null if input1 has no data. + */ + Iterable getAllRecords1(); + + /** + * Write records from input2 into the window's state. + * + * @param record The record from input2 to be written into the window's state. + */ + void putRecord2(IN2 record); + + /** + * Read input2's records from the window's state. + * + * @return Iterable of input2's records, which could be null if input2 has no data. + */ + Iterable getAllRecords2(); +} diff --git a/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/extension/window/context/WindowContext.java b/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/extension/window/context/WindowContext.java new file mode 100644 --- /dev/null +++ b/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/extension/window/context/WindowContext.java @@ -0,0 +1,94 @@ +/* + * 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.datastream.api.extension.window.context; + +import org.apache.flink.annotation.Experimental; +import org.apache.flink.api.common.state.AggregatingStateDeclaration; +import org.apache.flink.api.common.state.ListStateDeclaration; +import org.apache.flink.api.common.state.MapStateDeclaration; +import org.apache.flink.api.common.state.ReducingStateDeclaration; +import org.apache.flink.api.common.state.ValueStateDeclaration; +import org.apache.flink.api.common.state.v2.AggregatingState; +import org.apache.flink.api.common.state.v2.ListState; +import org.apache.flink.api.common.state.v2.MapState; +import org.apache.flink.api.common.state.v2.ReducingState; +import org.apache.flink.api.common.state.v2.ValueState; + +import java.util.Optional; + +/** + * This interface represents a context for window operations and provides methods to interact with + * state that is scoped to the window. + */ +@Experimental +public interface WindowContext { + + /** + * Gets the starting timestamp of the window. This is the first timestamp that belongs to this + * window. + * + * @return The starting timestamp of this window, or -1 if the window is not a time window or a + * session window. + */ + long getStartTime(); + + /** + * Gets the end timestamp of this window. The end timestamp is exclusive, meaning it is the + * first timestamp that does not belong to this window anymore. + * + * @return The exclusive end timestamp of this window, or -1 if the window is a session window + * or not a time window. + */ + long getEndTime(); + + /** + * Retrieves a {@link ListState} object that can be used to interact with fault-tolerant state + * that is scoped to the window. + */ + Optional> getWindowState(ListStateDeclaration stateDeclaration) + throws Exception; + + /** + * Retrieves a {@link MapState} object that can be used to interact with fault-tolerant state + * that is scoped to the window. + */ + Optional> getWindowState(MapStateDeclaration stateDeclaration) + throws Exception; + + /** + * Retrieves a {@link ValueState} object that can be used to interact with fault-tolerant state + * that is scoped to the window. + */ + Optional> getWindowState(ValueStateDeclaration stateDeclaration) + throws Exception; + + /** + * Retrieves a {@link ReducingState} object that can be used to interact with fault-tolerant + * state that is scoped to the window. + */ + Optional> getWindowState(ReducingStateDeclaration stateDeclaration) + throws Exception; + + /** + * Retrieves a {@link AggregatingState} object that can be used to interact with fault-tolerant + * state that is scoped to the window. + */ + Optional> getWindowState( + AggregatingStateDeclaration stateDeclaration) throws Exception; +} diff --git a/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/extension/window/function/OneInputWindowStreamProcessFunction.java b/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/extension/window/function/OneInputWindowStreamProcessFunction.java new file mode 100644 --- /dev/null +++ b/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/extension/window/function/OneInputWindowStreamProcessFunction.java @@ -0,0 +1,73 @@ +/* + * 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.datastream.api.extension.window.function; + +import org.apache.flink.annotation.Experimental; +import org.apache.flink.datastream.api.common.Collector; +import org.apache.flink.datastream.api.context.PartitionedContext; +import org.apache.flink.datastream.api.extension.window.context.OneInputWindowContext; + +/** + * A type of {@link WindowProcessFunction} for one-input window processing. + * + * @param The type of the input value. + * @param The type of the output value. + */ +@Experimental +public interface OneInputWindowStreamProcessFunction extends WindowProcessFunction { + + /** + * This method will be invoked when a record is received. Its default behaviors to store data in + * built-in window state by {@link OneInputWindowContext#putRecord}. If the user overrides this + * method, they have to take care of the input data themselves. + */ + default void onRecord( + IN record, + Collector output, + PartitionedContext ctx, + OneInputWindowContext windowContext) + throws Exception { + windowContext.putRecord(record); + } + + /** + * This method will be invoked when the Window is triggered, you can obtain all the input + * records in the Window by {@link OneInputWindowContext#getAllRecords()}. + */ + void onTrigger( + Collector output, + PartitionedContext ctx, + OneInputWindowContext windowContext) + throws Exception; + + /** + * Callback when a window is about to be cleaned up. It is the time to deletes any state in the + * {@code windowContext} when the Window expires (the event time or processing time passes its + * {@code maxTimestamp} + {@code allowedLateness}). + */ + default void onClear( + Collector output, + PartitionedContext ctx, + OneInputWindowContext windowContext) + throws Exception {} + + /** This method will be invoked when a record is received after the window has been cleaned. */ + default void onLateRecord(IN record, Collector output, PartitionedContext ctx) + throws Exception {} +} diff --git a/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/extension/window/function/TwoInputNonBroadcastWindowStreamProcessFunction.java b/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/extension/window/function/TwoInputNonBroadcastWindowStreamProcessFunction.java new file mode 100644 --- /dev/null +++ b/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/extension/window/function/TwoInputNonBroadcastWindowStreamProcessFunction.java @@ -0,0 +1,100 @@ +/* + * 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.datastream.api.extension.window.function; + +import org.apache.flink.annotation.Experimental; +import org.apache.flink.datastream.api.common.Collector; +import org.apache.flink.datastream.api.context.PartitionedContext; +import org.apache.flink.datastream.api.extension.window.context.TwoInputWindowContext; + +/** + * A type of {@link WindowProcessFunction} for two input window processing, such as window-join. + * + * @param The type of the input1 value. + * @param The type of the input2 value. + * @param The type of the output value. + */ +@Experimental +public interface TwoInputNonBroadcastWindowStreamProcessFunction + extends WindowProcessFunction { + + /** + * This method will be invoked when a record is received from input1. Its default behaviors to + * store data in built-in window state by {@link TwoInputWindowContext#putRecord1}. If the user + * overrides this method, they have to take care of the input data themselves. + */ + default void onRecord1( + IN1 record, + Collector output, + PartitionedContext ctx, + TwoInputWindowContext windowContext) + throws Exception { + windowContext.putRecord1(record); + } + + /** + * This method will be invoked when a record is received from input2. Its default behaviors to + * store data in built-in window state by {@link TwoInputWindowContext#putRecord2}. If the user + * overrides this method, they have to take care of the input data themselves. + */ + default void onRecord2( + IN2 record, + Collector output, + PartitionedContext ctx, + TwoInputWindowContext windowContext) + throws Exception { + windowContext.putRecord2(record); + } + + /** + * This method will be invoked when the Window is triggered, you can obtain all the input + * records in the Window by {@link TwoInputWindowContext#getAllRecords1()} and {@link + * TwoInputWindowContext#getAllRecords2()}. + */ + void onTrigger( + Collector output, + PartitionedContext ctx, + TwoInputWindowContext windowContext) + throws Exception; + + /** + * Callback when a window is about to be cleaned up. It is the time to deletes any state in the + * {@code windowContext} when the Window expires (the event time or processing time passes its + * {@code maxTimestamp} + {@code allowedLateness}). + */ + default void onClear( + Collector output, + PartitionedContext ctx, + TwoInputWindowContext windowContext) + throws Exception {} + + /** + * This method will be invoked when a record is received from input1 after the window has been + * cleaned. + */ + default void onLateRecord1(IN1 record, Collector output, PartitionedContext ctx) + throws Exception {} + + /** + * This method will be invoked when a record is received from input2 after the window has been + * cleaned. + */ + default void onLateRecord2(IN2 record, Collector output, PartitionedContext ctx) + throws Exception {} +} diff --git a/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/extension/window/function/TwoOutputWindowStreamProcessFunction.java b/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/extension/window/function/TwoOutputWindowStreamProcessFunction.java new file mode 100644 --- /dev/null +++ b/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/extension/window/function/TwoOutputWindowStreamProcessFunction.java @@ -0,0 +1,82 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.flink.datastream.api.extension.window.function; + +import org.apache.flink.annotation.Experimental; +import org.apache.flink.datastream.api.common.Collector; +import org.apache.flink.datastream.api.context.TwoOutputPartitionedContext; +import org.apache.flink.datastream.api.extension.window.context.OneInputWindowContext; + +/** + * A type of {@link WindowProcessFunction} for two-output window processing. + * + * @param The type of the input value. + * @param The type of the output value to the first output. + * @param The type of the output value to the second output. + */ +@Experimental +public interface TwoOutputWindowStreamProcessFunction + extends WindowProcessFunction { + + /** + * This method will be invoked when a record is received. Its default behaviors to store data in + * built-in window state by {@link OneInputWindowContext#putRecord}. If the user overrides this + * method, they have to take care of the input data themselves. + */ + default void onRecord( + IN record, + Collector output1, + Collector output2, + TwoOutputPartitionedContext ctx, + OneInputWindowContext windowContext) + throws Exception { + windowContext.putRecord(record); + } + + /** + * This method will be invoked when the Window is triggered, you can obtain all the input + * records in the Window by {@link OneInputWindowContext#getAllRecords()}. + */ + void onTrigger( + Collector output1, + Collector output2, + TwoOutputPartitionedContext ctx, + OneInputWindowContext windowContext) + throws Exception; + + /** + * Callback when a window is about to be cleaned up. It is the time to deletes any state in the + * {@code windowContext} when the Window expires (the event time or processing time passes its + * {@code maxTimestamp} + {@code allowedLateness}). + */ + default void onClear( + Collector output1, + Collector output2, + TwoOutputPartitionedContext ctx, + OneInputWindowContext windowContext) + throws Exception {} + + /** This method will be invoked when a record is received after the window has been cleaned. */ + default void onLateRecord( + IN record, + Collector output1, + Collector output2, + TwoOutputPartitionedContext ctx) + throws Exception {} +} diff --git a/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/extension/window/function/WindowProcessFunction.java b/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/extension/window/function/WindowProcessFunction.java new file mode 100644 --- /dev/null +++ b/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/extension/window/function/WindowProcessFunction.java @@ -0,0 +1,44 @@ +/* + * 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.datastream.api.extension.window.function; + +import org.apache.flink.annotation.Experimental; +import org.apache.flink.api.common.state.StateDeclaration; +import org.apache.flink.datastream.api.function.ProcessFunction; + +import java.util.Collections; +import java.util.Set; + +/** + * Base interface for functions evaluated over windows, providing callback functions for various + * stages of the window's lifecycle. + */ +@Experimental +public interface WindowProcessFunction extends ProcessFunction { + + /** + * Explicitly declares states that are bound to the window. Each specific window state must be + * declared in this method before it can be used. + * + * @return all declared window states used by this process function. + */ + default Set useWindowStates() { + return Collections.emptySet(); + } +} diff --git a/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/extension/window/strategy/GlobalWindowStrategy.java b/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/extension/window/strategy/GlobalWindowStrategy.java new file mode 100644 --- /dev/null +++ b/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/extension/window/strategy/GlobalWindowStrategy.java @@ -0,0 +1,25 @@ +/* + * 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.datastream.api.extension.window.strategy; + +import org.apache.flink.annotation.Experimental; + +/** A {@link WindowStrategy} used to generate GlobalWindow. */ +@Experimental +public class GlobalWindowStrategy extends WindowStrategy {} diff --git a/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/extension/window/strategy/SessionWindowStrategy.java b/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/extension/window/strategy/SessionWindowStrategy.java new file mode 100644 --- /dev/null +++ b/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/extension/window/strategy/SessionWindowStrategy.java @@ -0,0 +1,47 @@ +/* + * 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.datastream.api.extension.window.strategy; + +import org.apache.flink.annotation.Experimental; + +import java.time.Duration; + +/** A {@link WindowStrategy} used to generate Session Windows. */ +@Experimental +public class SessionWindowStrategy extends WindowStrategy { + private final Duration sessionGap; + private final TimeType timeType; + + public SessionWindowStrategy(Duration sessionGap) { + this(sessionGap, TimeType.EVENT); + } + + public SessionWindowStrategy(Duration sessionGap, TimeType timeType) { + this.sessionGap = sessionGap; + this.timeType = timeType; + } + + public Duration getSessionGap() { + return sessionGap; + } + + public TimeType getTimeType() { + return timeType; + } +} diff --git a/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/extension/window/strategy/SlidingTimeWindowStrategy.java b/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/extension/window/strategy/SlidingTimeWindowStrategy.java new file mode 100644 --- /dev/null +++ b/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/extension/window/strategy/SlidingTimeWindowStrategy.java @@ -0,0 +1,68 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.flink.datastream.api.extension.window.strategy; + +import org.apache.flink.annotation.Experimental; + +import java.time.Duration; + +/** A {@link WindowStrategy} used to generate sliding TimeWindow. */ +@Experimental +public class SlidingTimeWindowStrategy extends WindowStrategy { + private final Duration windowSize; + private final Duration windowSlideInterval; + private final TimeType timeType; + private final Duration allowedLateness; + + public SlidingTimeWindowStrategy(Duration windowSize, Duration windowSlideInterval) { + this(windowSize, windowSlideInterval, TimeType.EVENT); + } + + public SlidingTimeWindowStrategy( + Duration windowSize, Duration windowSlideInterval, TimeType timeType) { + this(windowSize, windowSlideInterval, timeType, Duration.ZERO); + } + + public SlidingTimeWindowStrategy( + Duration windowSize, + Duration windowSlideInterval, + TimeType timeType, + Duration allowedLateness) { + this.windowSize = windowSize; + this.windowSlideInterval = windowSlideInterval; + this.timeType = timeType; + this.allowedLateness = allowedLateness; + } + + public Duration getWindowSize() { + return windowSize; + } + + public Duration getWindowSlideInterval() { + return windowSlideInterval; + } + + public TimeType getTimeType() { + return timeType; + } + + public Duration getAllowedLateness() { + return allowedLateness; + } +} diff --git a/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/extension/window/strategy/TumblingTimeWindowStrategy.java b/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/extension/window/strategy/TumblingTimeWindowStrategy.java new file mode 100644 --- /dev/null +++ b/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/extension/window/strategy/TumblingTimeWindowStrategy.java @@ -0,0 +1,58 @@ +/* + * 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.datastream.api.extension.window.strategy; + +import org.apache.flink.annotation.Experimental; + +import java.time.Duration; + +/** A {@link WindowStrategy} used to generate tumbling TimeWindow. */ +@Experimental +public class TumblingTimeWindowStrategy extends WindowStrategy { + private final Duration windowSize; + private final TimeType timeType; + private final Duration allowedLateness; + + public TumblingTimeWindowStrategy(Duration windowSize) { + this(windowSize, TimeType.EVENT); + } + + public TumblingTimeWindowStrategy(Duration windowSize, TimeType timeType) { + this(windowSize, timeType, Duration.ZERO); + } + + public TumblingTimeWindowStrategy( + Duration windowSize, TimeType timeType, Duration allowedLateness) { + this.windowSize = windowSize; + this.timeType = timeType; + this.allowedLateness = allowedLateness; + } + + public Duration getWindowSize() { + return windowSize; + } + + public TimeType getTimeType() { + return timeType; + } + + public Duration getAllowedLateness() { + return allowedLateness; + } +} diff --git a/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/extension/window/strategy/WindowStrategy.java b/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/extension/window/strategy/WindowStrategy.java new file mode 100644 --- /dev/null +++ b/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/extension/window/strategy/WindowStrategy.java @@ -0,0 +1,201 @@ +/* + * 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.datastream.api.extension.window.strategy; + +import org.apache.flink.annotation.Experimental; + +import java.io.Serializable; +import java.time.Duration; + +/** + * This class describes what kind of Windows to use, including strategies for dividing, triggering, + * and clearing Windows. + * + *

We currently provide three built-in window types: Global Window, Time Window, and Session + * Window. + * + *

    + *
  • Global Window: All the data is in a single window. There is only one Global Window, and all + * data is assigned to this single window. Global Window are suitable for bounded stream + * scenarios and can be used in GlobalStream, KeyedStream, and NonKeyedStream. + *
  • Time Window: Data within a specific time period is assigned to a single window. Time + * Windows are divided into multiple windows based on time ranges, and data is assigned to the + * corresponding window based on its timestamp. We support two types of time windows: tumbling + * windows and sliding windows, and the tumbling windows cannot overlap. The time semantics + * within the windows can be divided into event time and processing time. Time Window can be + * used in GlobalStream and KeyedStream. + *
  • Session Window: Consecutive data is assigned to a single window. Session windows are a + * special type of time window and are divided into multiple windows based on time ranges. + * When data arrives, it is first assigned to the corresponding window based on its timestamp, + * and then existing windows are merged as much as possible. Session Window can be used in + * GlobalStream and KeyedStream. + *
+ */ +@Experimental +public class WindowStrategy implements Serializable { + + public static final TimeType PROCESSING_TIME = TimeType.PROCESSING; + public static final TimeType EVENT_TIME = TimeType.EVENT; + + /** The types of time used in window operations. */ + @Experimental + public enum TimeType { + PROCESSING, + EVENT + } + + // ============== global window ================ + + /** + * Creates a global window strategy. Note that the global window can be used in both + * GlobalStream, KeyedStream, NonKeyedStream. + * + * @return A global window strategy. + */ + public static WindowStrategy global() { + return new GlobalWindowStrategy(); + } + + // ============== tumbling time window ================ + + /** + * Create a tumbling time window strategy with the event time default time type. Note that + * tumbling time windows can be used in KeyedStream and GlobalStream. If tumbling time window is + * used in a GlobalStream, it will convert the GlobalStream into a KeyedStream with a Key of + * zero, and then use the converted KeyedStream to execute the window. + * + * @param windowSize the size of Window. + * @return A tumbling time window strategy. + */ + public static WindowStrategy tumbling(Duration windowSize) { + return new TumblingTimeWindowStrategy(windowSize); + } + + /** + * Create a tumbling time window strategy. Note that tumbling time windows can be used in + * KeyedStream and GlobalStream. If tumbling time window is used in a GlobalStream, it will + * convert the GlobalStream into a KeyedStream with a Key of zero, and then use the converted + * KeyedStream to execute the window. + * + * @param windowSize the size of Window. + * @param timeType the time type of Window. + * @return A tumbling time window strategy. + */ + public static WindowStrategy tumbling(Duration windowSize, TimeType timeType) { + return new TumblingTimeWindowStrategy(windowSize, timeType); + } + + /** + * Create a tumbling time window strategy. Note that tumbling time windows can be used in + * KeyedStream and GlobalStream. If tumbling time window is used in a GlobalStream, it will + * convert the GlobalStream into a KeyedStream with a Key of zero, and then use the converted + * KeyedStream to execute the window. + * + * @param windowSize the size of Window. + * @param timeType the time type of Window. + * @param allowedLateness the allowed lateness of Window. + * @return A tumbling time window strategy. + */ + public static WindowStrategy tumbling( + Duration windowSize, TimeType timeType, Duration allowedLateness) { + return new TumblingTimeWindowStrategy(windowSize, timeType, allowedLateness); + } + + // ============== sliding time window ================ + + /** + * Create a sliding time window strategy with the event time default time type. Note that + * sliding time windows can be used in KeyedStream and GlobalStream. If sliding time window is + * used in a GlobalStream, it will convert the GlobalStream into a KeyedStream with a Key of + * zero, and then use the converted KeyedStream to execute the window. + * + * @param windowSize the size of Window. + * @param windowSlideInterval the slide interval of Window. + * @return A sliding time window strategy. + */ + public static WindowStrategy sliding(Duration windowSize, Duration windowSlideInterval) { + return new SlidingTimeWindowStrategy(windowSize, windowSlideInterval); + } + + /** + * Create a sliding time window strategy. Note that sliding time windows can be used in + * KeyedStream and GlobalStream. If sliding time window is used in a GlobalStream, it will + * convert the GlobalStream into a KeyedStream with a Key of zero, and then use the converted + * KeyedStream to execute the window. + * + * @param windowSize the size of Window. + * @param windowSlideInterval the slide interval of Window. + * @param timeType the time type of Window. + * @return A sliding time window strategy. + */ + public static WindowStrategy sliding( + Duration windowSize, Duration windowSlideInterval, TimeType timeType) { + return new SlidingTimeWindowStrategy(windowSize, windowSlideInterval, timeType); + } + + /** + * Create a sliding time window strategy. Note that sliding time windows can be used in + * KeyedStream and GlobalStream. If sliding time window is used in a GlobalStream, it will + * convert the GlobalStream into a KeyedStream with a Key of zero, and then use the converted + * KeyedStream to execute the window. + * + * @param windowSize the size of Window. + * @param windowSlideInterval the slide interval of Window. + * @param timeType the time type of Window. + * @param allowedLateness the allowed lateness of Window. + * @return A sliding time window strategy. + */ + public static WindowStrategy sliding( + Duration windowSize, + Duration windowSlideInterval, + TimeType timeType, + Duration allowedLateness) { + return new SlidingTimeWindowStrategy( + windowSize, windowSlideInterval, timeType, allowedLateness); + } + + // ============== session window ================ + + /** + * Create a session time window strategy with the event time default time type. Note that + * session time windows can be used in KeyedStream and GlobalStream. If session time window is + * used in a GlobalStream, it will convert the GlobalStream into a KeyedStream with a Key of + * zero, and then use the converted KeyedStream to execute the window. + * + * @param sessionGap the timeout of session. + * @return A session window strategy. + */ + public static WindowStrategy session(Duration sessionGap) { + return new SessionWindowStrategy(sessionGap); + } + + /** + * Create a session time window strategy. Note that session time windows can be used in + * KeyedStream and GlobalStream. If session time window is used in a GlobalStream, it will + * convert the GlobalStream into a KeyedStream with a Key of zero, and then use the converted + * KeyedStream to execute the window. + * + * @param sessionGap the timeout of session. + * @param timeType the time type of Window. + * @return A session window strategy. + */ + public static WindowStrategy session(Duration sessionGap, TimeType timeType) { + return new SessionWindowStrategy(sessionGap, timeType); + } +} diff --git a/flink-datastream/src/main/java/org/apache/flink/datastream/impl/builtin/BuiltinWindowFuncs.java b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/builtin/BuiltinWindowFuncs.java new file mode 100644 --- /dev/null +++ b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/builtin/BuiltinWindowFuncs.java @@ -0,0 +1,94 @@ +/* + * 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.datastream.impl.builtin; + +import org.apache.flink.datastream.api.builtin.BuiltinFuncs; +import org.apache.flink.datastream.api.extension.window.function.OneInputWindowStreamProcessFunction; +import org.apache.flink.datastream.api.extension.window.function.TwoInputNonBroadcastWindowStreamProcessFunction; +import org.apache.flink.datastream.api.extension.window.function.TwoOutputWindowStreamProcessFunction; +import org.apache.flink.datastream.api.extension.window.strategy.WindowStrategy; +import org.apache.flink.datastream.api.function.OneInputStreamProcessFunction; +import org.apache.flink.datastream.api.function.TwoInputNonBroadcastStreamProcessFunction; +import org.apache.flink.datastream.api.function.TwoOutputStreamProcessFunction; +import org.apache.flink.datastream.impl.extension.window.function.InternalOneInputWindowStreamProcessFunction; +import org.apache.flink.datastream.impl.extension.window.function.InternalTwoInputWindowStreamProcessFunction; +import org.apache.flink.datastream.impl.extension.window.function.InternalTwoOutputWindowStreamProcessFunction; +import org.apache.flink.datastream.impl.extension.window.utils.WindowUtils; +import org.apache.flink.streaming.api.windowing.assigners.WindowAssigner; +import org.apache.flink.streaming.api.windowing.windows.Window; +import org.apache.flink.util.TaggedUnion; + +/** Window-related implementations in {@link BuiltinFuncs}. */ +public class BuiltinWindowFuncs { + + /** + * Wrap the WindowStrategy and OneInputWindowStreamProcessFunction within a ProcessFunction to + * perform the window operation. + */ + public static OneInputStreamProcessFunction window( + WindowStrategy windowStrategy, + OneInputWindowStreamProcessFunction windowProcessFunction) { + WindowAssigner windowAssigner = + (WindowAssigner) WindowUtils.createWindowAssigner(windowStrategy); + return new InternalOneInputWindowStreamProcessFunction<>( + windowProcessFunction, + windowAssigner, + windowAssigner.getDefaultTrigger(), + WindowUtils.getAllowedLateness(windowStrategy), + windowStrategy); + } + + /** + * Wrap the WindowStrategy and TwoInputWindowStreamProcessFunction within a ProcessFunction to + * perform the window operation. + */ + public static + TwoInputNonBroadcastStreamProcessFunction window( + WindowStrategy windowStrategy, + TwoInputNonBroadcastWindowStreamProcessFunction + windowProcessFunction) { + WindowAssigner, W> windowAssigner = + (WindowAssigner, W>) + WindowUtils.createWindowAssigner(windowStrategy); + return new InternalTwoInputWindowStreamProcessFunction<>( + windowProcessFunction, + windowAssigner, + windowAssigner.getDefaultTrigger(), + WindowUtils.getAllowedLateness(windowStrategy), + windowStrategy); + } + + /** + * Wrap the WindowStrategy and TwoOutputWindowStreamProcessFunction within a ProcessFunction to + * perform the window operation. + */ + public static + TwoOutputStreamProcessFunction window( + WindowStrategy windowStrategy, + TwoOutputWindowStreamProcessFunction windowProcessFunction) { + WindowAssigner windowAssigner = + (WindowAssigner) WindowUtils.createWindowAssigner(windowStrategy); + return new InternalTwoOutputWindowStreamProcessFunction<>( + windowProcessFunction, + windowAssigner, + windowAssigner.getDefaultTrigger(), + WindowUtils.getAllowedLateness(windowStrategy), + windowStrategy); + } +} diff --git a/flink-datastream/src/main/java/org/apache/flink/datastream/impl/extension/join/operators/TwoInputNonBroadcastJoinProcessOperator.java b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/extension/join/operators/TwoInputNonBroadcastJoinProcessOperator.java --- a/flink-datastream/src/main/java/org/apache/flink/datastream/impl/extension/join/operators/TwoInputNonBroadcastJoinProcessOperator.java +++ b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/extension/join/operators/TwoInputNonBroadcastJoinProcessOperator.java @@ -19,13 +19,13 @@ package org.apache.flink.datastream.impl.extension.join.operators; import org.apache.flink.api.common.state.v2.ListState; +import org.apache.flink.api.common.state.v2.ListStateDescriptor; import org.apache.flink.datastream.api.extension.join.JoinType; import org.apache.flink.datastream.api.function.TwoInputNonBroadcastStreamProcessFunction; import org.apache.flink.datastream.api.stream.KeyedPartitionStream; import org.apache.flink.datastream.impl.operators.KeyedTwoInputNonBroadcastProcessOperator; import org.apache.flink.runtime.state.VoidNamespace; import org.apache.flink.runtime.state.VoidNamespaceSerializer; -import org.apache.flink.runtime.state.v2.ListStateDescriptor; import org.apache.flink.streaming.runtime.streamrecord.StreamRecord; import static org.apache.flink.util.Preconditions.checkArgument; diff --git a/flink-datastream/src/main/java/org/apache/flink/datastream/impl/extension/window/context/DefaultOneInputWindowContext.java b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/extension/window/context/DefaultOneInputWindowContext.java new file mode 100644 --- /dev/null +++ b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/extension/window/context/DefaultOneInputWindowContext.java @@ -0,0 +1,139 @@ +/* + * 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.datastream.impl.extension.window.context; + +import org.apache.flink.api.common.state.AggregatingStateDeclaration; +import org.apache.flink.api.common.state.ListStateDeclaration; +import org.apache.flink.api.common.state.MapStateDeclaration; +import org.apache.flink.api.common.state.ReducingStateDeclaration; +import org.apache.flink.api.common.state.ValueStateDeclaration; +import org.apache.flink.api.common.state.v2.AggregatingState; +import org.apache.flink.api.common.state.v2.AppendingState; +import org.apache.flink.api.common.state.v2.ListState; +import org.apache.flink.api.common.state.v2.MapState; +import org.apache.flink.api.common.state.v2.ReducingState; +import org.apache.flink.api.common.state.v2.StateIterator; +import org.apache.flink.api.common.state.v2.ValueState; +import org.apache.flink.api.common.typeutils.TypeSerializer; +import org.apache.flink.datastream.api.extension.window.context.OneInputWindowContext; +import org.apache.flink.datastream.api.extension.window.function.WindowProcessFunction; +import org.apache.flink.runtime.asyncprocessing.operators.AbstractAsyncStateStreamOperator; +import org.apache.flink.streaming.api.windowing.windows.TimeWindow; +import org.apache.flink.streaming.api.windowing.windows.Window; + +import javax.annotation.Nullable; + +import java.util.Optional; + +/** + * Default implementation of the {@link OneInputWindowContext}. + * + * @param Type of the window key. + * @param Type of the input elements. + * @param Type of the window. + */ +public class DefaultOneInputWindowContext + implements OneInputWindowContext { + + /** + * The current processing window. An instance should be set every time before accessing + * window-related attributes, data, and state. + */ + @Nullable private W window; + + /** Use to retrieve state associated with windows. */ + private final WindowStateStore windowStateStore; + + /** The state utilized for storing window data. */ + private final AppendingState, Iterable> windowState; + + public DefaultOneInputWindowContext( + @Nullable W window, + AppendingState, Iterable> windowState, + WindowProcessFunction windowProcessFunction, + AbstractAsyncStateStreamOperator operator, + TypeSerializer windowSerializer, + boolean isMergingWindow) { + this.window = window; + this.windowState = windowState; + this.windowStateStore = + new WindowStateStore<>( + windowProcessFunction, operator, windowSerializer, isMergingWindow); + } + + public void setWindow(W window) { + this.window = window; + } + + @Override + public long getStartTime() { + if (window instanceof TimeWindow) { + return ((TimeWindow) window).getStart(); + } + return -1; + } + + @Override + public long getEndTime() { + if (window instanceof TimeWindow) { + return ((TimeWindow) window).getEnd(); + } + return -1; + } + + @Override + public Optional> getWindowState(ListStateDeclaration stateDeclaration) + throws Exception { + return windowStateStore.getWindowState(stateDeclaration, window); + } + + @Override + public Optional> getWindowState( + MapStateDeclaration stateDeclaration) throws Exception { + return windowStateStore.getWindowState(stateDeclaration, window); + } + + @Override + public Optional> getWindowState(ValueStateDeclaration stateDeclaration) + throws Exception { + return windowStateStore.getWindowState(stateDeclaration, window); + } + + @Override + public Optional> getWindowState( + ReducingStateDeclaration stateDeclaration) throws Exception { + return windowStateStore.getWindowState(stateDeclaration, window); + } + + @Override + public Optional> getWindowState( + AggregatingStateDeclaration stateDeclaration) throws Exception { + return windowStateStore.getWindowState(stateDeclaration, window); + } + + @Override + public void putRecord(IN record) { + windowState.add(record); + } + + @Override + public Iterable getAllRecords() { + return windowState.get(); + } +} diff --git a/flink-datastream/src/main/java/org/apache/flink/datastream/impl/extension/window/context/DefaultTwoInputWindowContext.java b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/extension/window/context/DefaultTwoInputWindowContext.java new file mode 100644 --- /dev/null +++ b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/extension/window/context/DefaultTwoInputWindowContext.java @@ -0,0 +1,155 @@ +/* + * 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.datastream.impl.extension.window.context; + +import org.apache.flink.api.common.state.AggregatingStateDeclaration; +import org.apache.flink.api.common.state.ListStateDeclaration; +import org.apache.flink.api.common.state.MapStateDeclaration; +import org.apache.flink.api.common.state.ReducingStateDeclaration; +import org.apache.flink.api.common.state.ValueStateDeclaration; +import org.apache.flink.api.common.state.v2.AggregatingState; +import org.apache.flink.api.common.state.v2.AppendingState; +import org.apache.flink.api.common.state.v2.ListState; +import org.apache.flink.api.common.state.v2.MapState; +import org.apache.flink.api.common.state.v2.ReducingState; +import org.apache.flink.api.common.state.v2.StateIterator; +import org.apache.flink.api.common.state.v2.ValueState; +import org.apache.flink.api.common.typeutils.TypeSerializer; +import org.apache.flink.datastream.api.extension.window.context.TwoInputWindowContext; +import org.apache.flink.datastream.api.extension.window.function.WindowProcessFunction; +import org.apache.flink.runtime.asyncprocessing.operators.AbstractAsyncStateStreamOperator; +import org.apache.flink.streaming.api.windowing.windows.TimeWindow; +import org.apache.flink.streaming.api.windowing.windows.Window; + +import javax.annotation.Nullable; + +import java.util.Optional; + +/** + * Default implementation of the {@link TwoInputWindowContext}. + * + * @param Type of the key. + * @param Type of the first input elements. + * @param Type of the second input elements. + * @param Type of the window. + */ +public class DefaultTwoInputWindowContext + implements TwoInputWindowContext { + + /** + * The current processing window. An instance should be set every time before accessing + * window-related attributes, data, and state. + */ + @Nullable private W window; + + /** Use to retrieve state associated with windows. */ + private final WindowStateStore windowStateStore; + + /** The state utilized for storing window received input data from first input. */ + private final AppendingState, Iterable> leftWindowState; + + /** The state utilized for storing window received input data from second input. */ + private final AppendingState, Iterable> rightWindowState; + + public DefaultTwoInputWindowContext( + W window, + AppendingState, Iterable> leftWindowState, + AppendingState, Iterable> rightWindowState, + WindowProcessFunction windowProcessFunction, + AbstractAsyncStateStreamOperator operator, + TypeSerializer windowSerializer, + boolean isMergingWindow) { + this.window = window; + this.leftWindowState = leftWindowState; + this.rightWindowState = rightWindowState; + this.windowStateStore = + new WindowStateStore<>( + windowProcessFunction, operator, windowSerializer, isMergingWindow); + } + + public void setWindow(W window) { + this.window = window; + } + + @Override + public long getStartTime() { + if (window instanceof TimeWindow) { + return ((TimeWindow) window).getStart(); + } + return -1; + } + + @Override + public long getEndTime() { + if (window instanceof TimeWindow) { + return ((TimeWindow) window).getEnd(); + } + return -1; + } + + @Override + public Optional> getWindowState(ListStateDeclaration stateDeclaration) + throws Exception { + return windowStateStore.getWindowState(stateDeclaration, window); + } + + @Override + public Optional> getWindowState( + MapStateDeclaration stateDeclaration) throws Exception { + return windowStateStore.getWindowState(stateDeclaration, window); + } + + @Override + public Optional> getWindowState(ValueStateDeclaration stateDeclaration) + throws Exception { + return windowStateStore.getWindowState(stateDeclaration, window); + } + + @Override + public Optional> getWindowState( + ReducingStateDeclaration stateDeclaration) throws Exception { + return windowStateStore.getWindowState(stateDeclaration, window); + } + + @Override + public Optional> getWindowState( + AggregatingStateDeclaration stateDeclaration) throws Exception { + return windowStateStore.getWindowState(stateDeclaration, window); + } + + @Override + public void putRecord1(IN1 record) { + leftWindowState.add(record); + } + + @Override + public Iterable getAllRecords1() { + return leftWindowState.get(); + } + + @Override + public void putRecord2(IN2 record) { + rightWindowState.add(record); + } + + @Override + public Iterable getAllRecords2() { + return rightWindowState.get(); + } +} diff --git a/flink-datastream/src/main/java/org/apache/flink/datastream/impl/extension/window/context/WindowStateStore.java b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/extension/window/context/WindowStateStore.java new file mode 100644 --- /dev/null +++ b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/extension/window/context/WindowStateStore.java @@ -0,0 +1,264 @@ +/* + * 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.datastream.impl.extension.window.context; + +import org.apache.flink.api.common.state.AggregatingStateDeclaration; +import org.apache.flink.api.common.state.ListStateDeclaration; +import org.apache.flink.api.common.state.MapStateDeclaration; +import org.apache.flink.api.common.state.ReducingStateDeclaration; +import org.apache.flink.api.common.state.StateDeclaration; +import org.apache.flink.api.common.state.ValueStateDeclaration; +import org.apache.flink.api.common.state.v2.AggregatingState; +import org.apache.flink.api.common.state.v2.AggregatingStateDescriptor; +import org.apache.flink.api.common.state.v2.ListState; +import org.apache.flink.api.common.state.v2.ListStateDescriptor; +import org.apache.flink.api.common.state.v2.MapState; +import org.apache.flink.api.common.state.v2.MapStateDescriptor; +import org.apache.flink.api.common.state.v2.ReducingState; +import org.apache.flink.api.common.state.v2.ReducingStateDescriptor; +import org.apache.flink.api.common.state.v2.ValueState; +import org.apache.flink.api.common.state.v2.ValueStateDescriptor; +import org.apache.flink.api.common.typeutils.TypeSerializer; +import org.apache.flink.api.java.typeutils.TypeExtractor; +import org.apache.flink.datastream.api.extension.window.context.WindowContext; +import org.apache.flink.datastream.api.extension.window.function.WindowProcessFunction; +import org.apache.flink.runtime.asyncprocessing.operators.AbstractAsyncStateStreamOperator; +import org.apache.flink.runtime.state.v2.adaptor.AggregatingStateAdaptor; +import org.apache.flink.runtime.state.v2.adaptor.ListStateAdaptor; +import org.apache.flink.runtime.state.v2.adaptor.MapStateAdaptor; +import org.apache.flink.runtime.state.v2.adaptor.ReducingStateAdaptor; +import org.apache.flink.runtime.state.v2.adaptor.ValueStateAdaptor; +import org.apache.flink.streaming.api.windowing.windows.Window; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Optional; +import java.util.Set; + +import static org.apache.flink.util.Preconditions.checkState; + +/** + * This class provides methods to store and retrieve state associated with windows in {@link + * WindowContext}. + * + * @param Type of the window key. + * @param Type of the window. + */ +public class WindowStateStore { + + private static final Logger LOG = LoggerFactory.getLogger(WindowStateStore.class); + + /** + * The {@link StateDeclaration}s that have been declared by the {@link + * WindowProcessFunction#useWindowStates()}. + */ + private final Set windowStateDeclarations; + + /** The operator to which the window belongs, used for creating and retrieving window state. */ + private final AbstractAsyncStateStreamOperator operator; + + private final TypeSerializer windowSerializer; + + /** Whether the window is a merging window. */ + private final boolean isMergingWindow; + + public WindowStateStore( + WindowProcessFunction windowProcessFunction, + AbstractAsyncStateStreamOperator operator, + TypeSerializer windowSerializer, + boolean isMergingWindow) { + this.windowStateDeclarations = windowProcessFunction.useWindowStates(); + this.operator = operator; + this.windowSerializer = windowSerializer; + this.isMergingWindow = isMergingWindow; + } + + private boolean isStateDeclared(StateDeclaration stateDeclaration) { + if (!windowStateDeclarations.contains(stateDeclaration)) { + LOG.warn( + "Fail to get window state for " + + stateDeclaration.getName() + + ", please declare the used state in the `WindowProcessFunction#useWindowStates` method first."); + return false; + } + return true; + } + + private boolean stateRedistributionModeIsNotNone(StateDeclaration stateDeclaration) { + StateDeclaration.RedistributionMode redistributionMode = + stateDeclaration.getRedistributionMode(); + return redistributionMode != StateDeclaration.RedistributionMode.NONE; + } + + /** Retrieve window state of list type. */ + public Optional> getWindowState( + ListStateDeclaration stateDeclaration, W namespace) throws Exception { + checkState( + !isMergingWindow, + "Retrieving the window state is not permitted when using merging windows, such as session windows."); + + if (!isStateDeclared(stateDeclaration)) { + return Optional.empty(); + } + + if (stateRedistributionModeIsNotNone(stateDeclaration)) { + throw new UnsupportedOperationException( + "RedistributionMode " + + stateDeclaration.getRedistributionMode().name() + + " is not supported for window state."); + } + + ListStateDescriptor stateDescriptor = + new ListStateDescriptor<>( + stateDeclaration.getName(), + TypeExtractor.createTypeInfo( + stateDeclaration.getTypeDescriptor().getTypeClass())); + + ListStateAdaptor state = + operator.getOrCreateKeyedState(namespace, windowSerializer, stateDescriptor); + state.setCurrentNamespace(namespace); + return Optional.of(state); + } + + /** Retrieve window state of map type. */ + public Optional> getWindowState( + MapStateDeclaration stateDeclaration, W namespace) throws Exception { + checkState( + !isMergingWindow, + "Retrieving the window state is not permitted when using merging windows, such as session windows."); + + if (!isStateDeclared(stateDeclaration)) { + return Optional.empty(); + } + + if (stateRedistributionModeIsNotNone(stateDeclaration)) { + throw new UnsupportedOperationException( + "RedistributionMode " + + stateDeclaration.getRedistributionMode().name() + + " is not supported for window state."); + } + + MapStateDescriptor stateDescriptor = + new MapStateDescriptor<>( + stateDeclaration.getName(), + TypeExtractor.createTypeInfo( + stateDeclaration.getKeyTypeDescriptor().getTypeClass()), + TypeExtractor.createTypeInfo( + stateDeclaration.getValueTypeDescriptor().getTypeClass())); + + MapStateAdaptor state = + operator.getOrCreateKeyedState(namespace, windowSerializer, stateDescriptor); + state.setCurrentNamespace(namespace); + return Optional.of(state); + } + + /** Retrieve window state of value type. */ + public Optional> getWindowState( + ValueStateDeclaration stateDeclaration, W namespace) throws Exception { + checkState( + !isMergingWindow, + "Retrieving the window state is not permitted when using merging windows, such as session windows."); + + if (!isStateDeclared(stateDeclaration)) { + return Optional.empty(); + } + + if (stateRedistributionModeIsNotNone(stateDeclaration)) { + throw new UnsupportedOperationException( + "RedistributionMode " + + stateDeclaration.getRedistributionMode().name() + + " is not supported for window state."); + } + + ValueStateDescriptor stateDescriptor = + new ValueStateDescriptor<>( + stateDeclaration.getName(), + TypeExtractor.createTypeInfo( + stateDeclaration.getTypeDescriptor().getTypeClass())); + + ValueStateAdaptor state = + operator.getOrCreateKeyedState(namespace, windowSerializer, stateDescriptor); + state.setCurrentNamespace(namespace); + return Optional.of(state); + } + + /** Retrieve window state of ReducingState type. */ + public Optional> getWindowState( + ReducingStateDeclaration stateDeclaration, W namespace) throws Exception { + checkState( + !isMergingWindow, + "Retrieving the window state is not permitted when using merging windows, such as session windows."); + + if (!isStateDeclared(stateDeclaration)) { + return Optional.empty(); + } + + if (stateRedistributionModeIsNotNone(stateDeclaration)) { + throw new UnsupportedOperationException( + "RedistributionMode " + + stateDeclaration.getRedistributionMode().name() + + " is not supported for window state."); + } + + ReducingStateDescriptor stateDescriptor = + new ReducingStateDescriptor<>( + stateDeclaration.getName(), + stateDeclaration.getReduceFunction(), + TypeExtractor.createTypeInfo( + stateDeclaration.getTypeDescriptor().getTypeClass())); + + ReducingStateAdaptor state = + operator.getOrCreateKeyedState(namespace, windowSerializer, stateDescriptor); + state.setCurrentNamespace(namespace); + return Optional.of(state); + } + + /** Retrieve window state of AggregatingState type. */ + public Optional> getWindowState( + AggregatingStateDeclaration stateDeclaration, W namespace) + throws Exception { + checkState( + !isMergingWindow, + "Retrieving the window state is not permitted when using merging windows, such as session windows."); + + if (!isStateDeclared(stateDeclaration)) { + return Optional.empty(); + } + + if (stateRedistributionModeIsNotNone(stateDeclaration)) { + throw new UnsupportedOperationException( + "RedistributionMode " + + stateDeclaration.getRedistributionMode().name() + + " is not supported for window state."); + } + + AggregatingStateDescriptor stateDescriptor = + new AggregatingStateDescriptor<>( + stateDeclaration.getName(), + stateDeclaration.getAggregateFunction(), + TypeExtractor.createTypeInfo( + stateDeclaration.getTypeDescriptor().getTypeClass())); + + AggregatingStateAdaptor state = + operator.getOrCreateKeyedState(namespace, windowSerializer, stateDescriptor); + state.setCurrentNamespace(namespace); + return Optional.of(state); + } +} diff --git a/flink-datastream/src/main/java/org/apache/flink/datastream/impl/extension/window/context/WindowTriggerContext.java b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/extension/window/context/WindowTriggerContext.java new file mode 100644 --- /dev/null +++ b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/extension/window/context/WindowTriggerContext.java @@ -0,0 +1,190 @@ +/* + * 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.datastream.impl.extension.window.context; + +import org.apache.flink.api.common.state.MergingState; +import org.apache.flink.api.common.state.State; +import org.apache.flink.api.common.typeutils.TypeSerializer; +import org.apache.flink.metrics.MetricGroup; +import org.apache.flink.streaming.api.operators.AbstractStreamOperator; +import org.apache.flink.streaming.api.operators.InternalTimerService; +import org.apache.flink.streaming.api.windowing.triggers.Trigger; +import org.apache.flink.streaming.api.windowing.triggers.TriggerResult; +import org.apache.flink.streaming.api.windowing.windows.Window; +import org.apache.flink.streaming.runtime.streamrecord.StreamRecord; + +import java.util.Collection; + +/** + * {@code WindowTriggerContext} is a utility for handling {@code Trigger} invocations. It can be + * reused by setting the {@code key} and {@code window} fields. + * + * @param Type of the key. + * @param Type of the input value. + * @param Type of the window. + */ +public class WindowTriggerContext implements Trigger.OnMergeContext { + + /** Current processing key. */ + private K key; + + /** Current processing window. */ + private W window; + + /** The operator to which the window belongs, used for creating and retrieving window state. */ + private final AbstractStreamOperator operator; + + /** The timer service of {@code operator}. */ + private final InternalTimerService internalTimerService; + + private final TypeSerializer windowSerializer; + + private final Trigger trigger; + + private Collection mergedWindows; + + public WindowTriggerContext( + K key, + W window, + AbstractStreamOperator operator, + InternalTimerService internalTimerService, + Trigger trigger, + TypeSerializer windowSerializer) { + this.key = key; + this.window = window; + this.operator = operator; + this.internalTimerService = internalTimerService; + this.trigger = trigger; + this.windowSerializer = windowSerializer; + } + + @Override + public MetricGroup getMetricGroup() { + return operator.getMetricGroup(); + } + + /** Get current event time. */ + public long getCurrentWatermark() { + return internalTimerService.currentWatermark(); + } + + public S getPartitionedState( + org.apache.flink.api.common.state.StateDescriptor stateDescriptor) { + try { + return operator.getPartitionedState(window, windowSerializer, stateDescriptor); + } catch (Exception e) { + throw new RuntimeException("Could not retrieve state", e); + } + } + + @Override + public > void mergePartitionedState( + org.apache.flink.api.common.state.StateDescriptor stateDescriptor) { + if (mergedWindows != null && !mergedWindows.isEmpty()) { + try { + S rawState = + operator.getKeyedStateBackend() + .getOrCreateKeyedState(windowSerializer, stateDescriptor); + + if (rawState + instanceof org.apache.flink.runtime.state.internal.InternalMergingState) { + @SuppressWarnings("unchecked") + org.apache.flink.runtime.state.internal.InternalMergingState + mergingState = + (org.apache.flink.runtime.state.internal.InternalMergingState< + K, W, ?, ?, ?>) + rawState; + mergingState.mergeNamespaces(window, mergedWindows); + } else { + throw new IllegalArgumentException( + "The given state descriptor does not refer to a mergeable state (MergingState)"); + } + } catch (Exception e) { + throw new RuntimeException("Error while merging state.", e); + } + } + } + + @Override + public long getCurrentProcessingTime() { + return internalTimerService.currentProcessingTime(); + } + + @Override + public void registerProcessingTimeTimer(long time) { + internalTimerService.registerProcessingTimeTimer(window, time); + } + + @Override + public void registerEventTimeTimer(long time) { + internalTimerService.registerEventTimeTimer(window, time); + } + + @Override + public void deleteProcessingTimeTimer(long time) { + internalTimerService.deleteProcessingTimeTimer(window, time); + } + + @Override + public void deleteEventTimeTimer(long time) { + internalTimerService.deleteEventTimeTimer(window, time); + } + + public TriggerResult onElement(StreamRecord element) throws Exception { + return trigger.onElement(element.getValue(), element.getTimestamp(), window, this); + } + + public TriggerResult onProcessingTime(long time) throws Exception { + return trigger.onProcessingTime(time, window, this); + } + + public TriggerResult onEventTime(long time) throws Exception { + return trigger.onEventTime(time, window, this); + } + + public void onMerge(Collection mergedWindows) throws Exception { + this.mergedWindows = mergedWindows; + trigger.onMerge(window, this); + } + + public void clear() throws Exception { + trigger.clear(window, this); + } + + @Override + public String toString() { + return "WindowTriggerContext{" + "key=" + key + ", window=" + window + '}'; + } + + public void setKey(K key) { + this.key = key; + } + + public void setWindow(W window) { + this.window = window; + } + + public K getKey() { + return key; + } + + public W getWindow() { + return window; + } +} diff --git a/flink-datastream/src/main/java/org/apache/flink/datastream/impl/extension/window/function/InternalOneInputWindowStreamProcessFunction.java b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/extension/window/function/InternalOneInputWindowStreamProcessFunction.java new file mode 100644 --- /dev/null +++ b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/extension/window/function/InternalOneInputWindowStreamProcessFunction.java @@ -0,0 +1,109 @@ +/* + * 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.datastream.impl.extension.window.function; + +import org.apache.flink.api.common.state.StateDeclaration; +import org.apache.flink.datastream.api.common.Collector; +import org.apache.flink.datastream.api.context.PartitionedContext; +import org.apache.flink.datastream.api.extension.window.function.OneInputWindowStreamProcessFunction; +import org.apache.flink.datastream.api.extension.window.function.WindowProcessFunction; +import org.apache.flink.datastream.api.extension.window.strategy.WindowStrategy; +import org.apache.flink.datastream.api.function.OneInputStreamProcessFunction; +import org.apache.flink.streaming.api.windowing.assigners.WindowAssigner; +import org.apache.flink.streaming.api.windowing.triggers.Trigger; +import org.apache.flink.streaming.api.windowing.windows.Window; + +import java.util.Set; + +/** + * A class that wrap a {@link OneInputWindowStreamProcessFunction} to process function. This will be + * translated to a window operator instead of vanilla process operator. + * + * @param Type of the input elements. + * @param Type of the output elements. + * @param Type of the window. + */ +public class InternalOneInputWindowStreamProcessFunction + implements OneInputStreamProcessFunction { + + /** User-defined {@link WindowProcessFunction}. */ + private final OneInputWindowStreamProcessFunction windowProcessFunction; + + private final WindowAssigner assigner; + + private final Trigger trigger; + + /** + * The allowed lateness for elements. This is used for: + * + *
    + *
  • Deciding if an element should be dropped from a window due to lateness. + *
  • Clearing the state of a window if the time out-of the {@code window.maxTimestamp + + * allowedLateness} landmark. + *
+ */ + private final long allowedLateness; + + private final WindowStrategy windowStrategy; + + public InternalOneInputWindowStreamProcessFunction( + OneInputWindowStreamProcessFunction windowProcessFunction, + WindowAssigner assigner, + Trigger trigger, + long allowedLateness, + WindowStrategy windowStrategy) { + this.windowProcessFunction = windowProcessFunction; + this.assigner = assigner; + this.trigger = trigger; + this.allowedLateness = allowedLateness; + this.windowStrategy = windowStrategy; + } + + @Override + public void processRecord(IN record, Collector output, PartitionedContext ctx) + throws Exception { + // Do nothing as this will translator to windowOperator instead of processOperator, and this + // method will never be invoked. + } + + public WindowAssigner getAssigner() { + return assigner; + } + + public Trigger getTrigger() { + return trigger; + } + + public long getAllowedLateness() { + return allowedLateness; + } + + public WindowStrategy getWindowStrategy() { + return windowStrategy; + } + + public OneInputWindowStreamProcessFunction getWindowProcessFunction() { + return windowProcessFunction; + } + + @Override + public Set usesStates() { + return windowProcessFunction.usesStates(); + } +} diff --git a/flink-datastream/src/main/java/org/apache/flink/datastream/impl/extension/window/function/InternalTwoInputWindowStreamProcessFunction.java b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/extension/window/function/InternalTwoInputWindowStreamProcessFunction.java new file mode 100644 --- /dev/null +++ b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/extension/window/function/InternalTwoInputWindowStreamProcessFunction.java @@ -0,0 +1,120 @@ +/* + * 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.datastream.impl.extension.window.function; + +import org.apache.flink.api.common.state.StateDeclaration; +import org.apache.flink.datastream.api.common.Collector; +import org.apache.flink.datastream.api.context.PartitionedContext; +import org.apache.flink.datastream.api.extension.window.function.TwoInputNonBroadcastWindowStreamProcessFunction; +import org.apache.flink.datastream.api.extension.window.function.WindowProcessFunction; +import org.apache.flink.datastream.api.extension.window.strategy.WindowStrategy; +import org.apache.flink.datastream.api.function.TwoInputNonBroadcastStreamProcessFunction; +import org.apache.flink.streaming.api.windowing.assigners.WindowAssigner; +import org.apache.flink.streaming.api.windowing.triggers.Trigger; +import org.apache.flink.streaming.api.windowing.windows.Window; +import org.apache.flink.util.TaggedUnion; + +import java.util.Set; + +/** + * A class that wrap a {@link TwoInputNonBroadcastWindowStreamProcessFunction} to process function. + * This will be translated to a window operator instead of vanilla process operator. + * + * @param Type of the first input elements. + * @param Type of the second input elements. + * @param Type of the output elements. + * @param Type of the window. + */ +public class InternalTwoInputWindowStreamProcessFunction + implements TwoInputNonBroadcastStreamProcessFunction { + + /** User-defined {@link WindowProcessFunction}. */ + private final TwoInputNonBroadcastWindowStreamProcessFunction + windowProcessFunction; + + private final WindowAssigner, W> assigner; + + private final Trigger, W> trigger; + + /** + * The allowed lateness for elements. This is used for: + * + *
    + *
  • Deciding if an element should be dropped from a window due to lateness. + *
  • Clearing the state of a window if the time out-of the {@code window.maxTimestamp + + * allowedLateness} landmark. + *
+ */ + private final long allowedLateness; + + private final WindowStrategy windowStrategy; + + public InternalTwoInputWindowStreamProcessFunction( + TwoInputNonBroadcastWindowStreamProcessFunction windowProcessFunction, + WindowAssigner, W> assigner, + Trigger, W> trigger, + long allowedLateness, + WindowStrategy windowStrategy) { + this.windowProcessFunction = windowProcessFunction; + this.assigner = assigner; + this.trigger = trigger; + this.allowedLateness = allowedLateness; + this.windowStrategy = windowStrategy; + } + + @Override + public void processRecordFromFirstInput( + IN1 record, Collector output, PartitionedContext ctx) throws Exception { + // Do nothing as this will translator to windowOperator instead of processOperator, and this + // method will never be invoked. + } + + @Override + public void processRecordFromSecondInput( + IN2 record, Collector output, PartitionedContext ctx) throws Exception { + // Do nothing as this will translator to windowOperator instead of processOperator, and this + // method will never be invoked. + } + + public TwoInputNonBroadcastWindowStreamProcessFunction + getWindowProcessFunction() { + return windowProcessFunction; + } + + @Override + public Set usesStates() { + return windowProcessFunction.usesStates(); + } + + public WindowAssigner, W> getAssigner() { + return assigner; + } + + public Trigger, W> getTrigger() { + return trigger; + } + + public long getAllowedLateness() { + return allowedLateness; + } + + public WindowStrategy getWindowStrategy() { + return windowStrategy; + } +} diff --git a/flink-datastream/src/main/java/org/apache/flink/datastream/impl/extension/window/function/InternalTwoOutputWindowStreamProcessFunction.java b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/extension/window/function/InternalTwoOutputWindowStreamProcessFunction.java new file mode 100644 --- /dev/null +++ b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/extension/window/function/InternalTwoOutputWindowStreamProcessFunction.java @@ -0,0 +1,114 @@ +/* + * 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.datastream.impl.extension.window.function; + +import org.apache.flink.api.common.state.StateDeclaration; +import org.apache.flink.datastream.api.common.Collector; +import org.apache.flink.datastream.api.context.TwoOutputPartitionedContext; +import org.apache.flink.datastream.api.extension.window.function.TwoOutputWindowStreamProcessFunction; +import org.apache.flink.datastream.api.extension.window.function.WindowProcessFunction; +import org.apache.flink.datastream.api.extension.window.strategy.WindowStrategy; +import org.apache.flink.datastream.api.function.TwoOutputStreamProcessFunction; +import org.apache.flink.streaming.api.windowing.assigners.WindowAssigner; +import org.apache.flink.streaming.api.windowing.triggers.Trigger; +import org.apache.flink.streaming.api.windowing.windows.Window; + +import java.util.Set; + +/** + * A class that wrap a {@link TwoOutputWindowStreamProcessFunction} to process function. This will + * be translated to a window operator instead of vanilla process operator. + * + * @param Type of the input elements. + * @param Type of the first output elements. + * @param Type of the second output elements. + * @param Type of the window. + */ +public class InternalTwoOutputWindowStreamProcessFunction + implements TwoOutputStreamProcessFunction { + + /** User-defined {@link WindowProcessFunction}. */ + private final TwoOutputWindowStreamProcessFunction windowProcessFunction; + + private final WindowAssigner assigner; + + private final Trigger trigger; + + /** + * The allowed lateness for elements. This is used for: + * + *
    + *
  • Deciding if an element should be dropped from a window due to lateness. + *
  • Clearing the state of a window if the time out-of the {@code window.maxTimestamp + + * allowedLateness} landmark. + *
+ */ + private final long allowedLateness; + + private final WindowStrategy windowStrategy; + + public InternalTwoOutputWindowStreamProcessFunction( + TwoOutputWindowStreamProcessFunction windowProcessFunction, + WindowAssigner assigner, + Trigger trigger, + long allowedLateness, + WindowStrategy windowStrategy) { + this.windowProcessFunction = windowProcessFunction; + this.assigner = assigner; + this.trigger = trigger; + this.allowedLateness = allowedLateness; + this.windowStrategy = windowStrategy; + } + + @Override + public void processRecord( + IN record, + Collector output1, + Collector output2, + TwoOutputPartitionedContext ctx) + throws Exception { + // Do nothing as this will translator to windowOperator instead of processOperator, and this + // method will never be invoked. + } + + public WindowAssigner getAssigner() { + return assigner; + } + + public Trigger getTrigger() { + return trigger; + } + + public long getAllowedLateness() { + return allowedLateness; + } + + public WindowStrategy getWindowStrategy() { + return windowStrategy; + } + + public TwoOutputWindowStreamProcessFunction getWindowProcessFunction() { + return windowProcessFunction; + } + + @Override + public Set usesStates() { + return windowProcessFunction.usesStates(); + } +} diff --git a/flink-datastream/src/main/java/org/apache/flink/datastream/impl/extension/window/operators/MergingWindowSet.java b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/extension/window/operators/MergingWindowSet.java new file mode 100644 --- /dev/null +++ b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/extension/window/operators/MergingWindowSet.java @@ -0,0 +1,246 @@ +/* + * 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.datastream.impl.extension.window.operators; + +import org.apache.flink.api.java.tuple.Tuple2; +import org.apache.flink.runtime.state.VoidNamespace; +import org.apache.flink.runtime.state.v2.internal.InternalListState; +import org.apache.flink.streaming.api.windowing.assigners.MergingWindowAssigner; +import org.apache.flink.streaming.api.windowing.windows.Window; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * Utility for keeping track of merging {@link Window Windows} when using a {@link + * MergingWindowAssigner} in a {@code WindowProcessOperator}. + * + *

Please refer to {@link + * org.apache.flink.streaming.runtime.operators.windowing.MergingWindowSet}. We do not use this + * directly because we are utilizing State V2, while it is based on State V1. + */ +public class MergingWindowSet { + + private static final Logger LOG = LoggerFactory.getLogger(MergingWindowSet.class); + + /** + * Mapping from window to the window that keeps the window state. When we are incrementally + * merging windows starting from some window we keep that starting window as the state window to + * prevent costly state juggling. + */ + private final Map mapping; + + /** + * Mapping when we created the {@code MergingWindowSet}. We use this to decide whether we need + * to persist any changes to state. + */ + private final Map initialMapping; + + private final InternalListState> state; + + /** Our window assigner. */ + private final MergingWindowAssigner windowAssigner; + + /** Restores a {@link MergingWindowSet} from the given state. */ + public MergingWindowSet( + MergingWindowAssigner windowAssigner, + InternalListState> state) + throws Exception { + this.windowAssigner = windowAssigner; + mapping = new HashMap<>(); + + Iterable> windowState = state.get(); + if (windowState != null) { + for (Tuple2 window : windowState) { + mapping.put(window.f0, window.f1); + } + } + + this.state = state; + + initialMapping = new HashMap<>(); + initialMapping.putAll(mapping); + } + + /** + * Persist the updated mapping to the given state if the mapping changed since initialization. + */ + public void persist() throws Exception { + if (!mapping.equals(initialMapping)) { + state.update( + mapping.entrySet().stream() + .map((w) -> new Tuple2<>(w.getKey(), w.getValue())) + .collect(Collectors.toList())); + } + } + + /** + * Returns the state window for the given in-flight {@code Window}. The state window is the + * {@code Window} in which we keep the actual state of a given in-flight window. Windows might + * expand but we keep to original state window for keeping the elements of the window to avoid + * costly state juggling. + * + * @param window The window for which to get the state window. + */ + public W getStateWindow(W window) { + return mapping.get(window); + } + + /** + * Removes the given window from the set of in-flight windows. + * + * @param window The {@code Window} to remove. + */ + public void retireWindow(W window) { + W removed = this.mapping.remove(window); + if (removed == null) { + throw new IllegalStateException( + "Window " + window + " is not in in-flight window set."); + } + } + + /** + * Adds a new {@code Window} to the set of in-flight windows. It might happen that this triggers + * merging of previously in-flight windows. In that case, the provided {@link MergeFunction} is + * called. + * + *

This returns the window that is the representative of the added window after adding. This + * can either be the new window itself, if no merge occurred, or the newly merged window. Adding + * an element to a window or calling trigger functions should only happen on the returned + * representative. This way, we never have to deal with a new window that is immediately + * swallowed up by another window. + * + *

If the new window is merged, the {@code MergeFunction} callback arguments also don't + * contain the new window as part of the list of merged windows. + * + * @param newWindow The new {@code Window} to add. + * @param mergeFunction The callback to be invoked in case a merge occurs. + * @return The {@code Window} that new new {@code Window} ended up in. This can also be the new + * {@code Window} itself in case no merge occurred. + * @throws Exception + */ + public W addWindow(W newWindow, MergeFunction mergeFunction) throws Exception { + + List windows = new ArrayList<>(); + + windows.addAll(this.mapping.keySet()); + windows.add(newWindow); + + final Map> mergeResults = new HashMap<>(); + windowAssigner.mergeWindows( + windows, + new MergingWindowAssigner.MergeCallback() { + @Override + public void merge(Collection toBeMerged, W mergeResult) { + if (LOG.isDebugEnabled()) { + LOG.debug("Merging {} into {}", toBeMerged, mergeResult); + } + mergeResults.put(mergeResult, toBeMerged); + } + }); + + W resultWindow = newWindow; + boolean mergedNewWindow = false; + + // perform the merge + for (Map.Entry> c : mergeResults.entrySet()) { + W mergeResult = c.getKey(); + Collection mergedWindows = c.getValue(); + + // if our new window is in the merged windows make the merge result the + // result window + if (mergedWindows.remove(newWindow)) { + mergedNewWindow = true; + resultWindow = mergeResult; + } + + // pick any of the merged windows and choose that window's state window + // as the state window for the merge result + W mergedStateWindow = this.mapping.get(mergedWindows.iterator().next()); + + // figure out the state windows that we are merging + List mergedStateWindows = new ArrayList<>(); + for (W mergedWindow : mergedWindows) { + W res = this.mapping.remove(mergedWindow); + if (res != null) { + mergedStateWindows.add(res); + } + } + + this.mapping.put(mergeResult, mergedStateWindow); + + // don't put the target state window into the merged windows + mergedStateWindows.remove(mergedStateWindow); + + // don't merge the new window itself, it never had any state associated with it + // i.e. if we are only merging one pre-existing window into itself + // without extending the pre-existing window + if (!(mergedWindows.contains(mergeResult) && mergedWindows.size() == 1)) { + mergeFunction.merge( + mergeResult, + mergedWindows, + this.mapping.get(mergeResult), + mergedStateWindows); + } + } + + // the new window created a new, self-contained window without merging + if (mergeResults.isEmpty() || (resultWindow.equals(newWindow) && !mergedNewWindow)) { + this.mapping.put(resultWindow, resultWindow); + } + + return resultWindow; + } + + /** + * Callback for {@link #addWindow(Window, MergeFunction)}. + * + * @param + */ + public interface MergeFunction { + + /** + * This gets called when a merge occurs. + * + * @param mergeResult The newly resulting merged {@code Window}. + * @param mergedWindows The merged {@code Window Windows}. + * @param stateWindowResult The state window of the merge result. + * @param mergedStateWindows The merged state windows. + * @throws Exception + */ + void merge( + W mergeResult, + Collection mergedWindows, + W stateWindowResult, + Collection mergedStateWindows) + throws Exception; + } + + @Override + public String toString() { + return "MergingWindowSet{" + "windows=" + mapping + '}'; + } +} diff --git a/flink-datastream/src/main/java/org/apache/flink/datastream/impl/extension/window/operators/OneInputWindowProcessOperator.java b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/extension/window/operators/OneInputWindowProcessOperator.java new file mode 100644 --- /dev/null +++ b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/extension/window/operators/OneInputWindowProcessOperator.java @@ -0,0 +1,532 @@ +/* + * 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.datastream.impl.extension.window.operators; + +import org.apache.flink.api.common.state.v2.AppendingState; +import org.apache.flink.api.common.state.v2.ListStateDescriptor; +import org.apache.flink.api.common.state.v2.StateDescriptor; +import org.apache.flink.api.common.state.v2.StateIterator; +import org.apache.flink.api.common.typeutils.TypeSerializer; +import org.apache.flink.api.java.tuple.Tuple2; +import org.apache.flink.api.java.typeutils.runtime.TupleSerializer; +import org.apache.flink.datastream.api.context.ProcessingTimeManager; +import org.apache.flink.datastream.api.extension.window.function.OneInputWindowStreamProcessFunction; +import org.apache.flink.datastream.api.extension.window.function.WindowProcessFunction; +import org.apache.flink.datastream.api.stream.KeyedPartitionStream; +import org.apache.flink.datastream.impl.context.UnsupportedProcessingTimeManager; +import org.apache.flink.datastream.impl.extension.window.context.DefaultOneInputWindowContext; +import org.apache.flink.datastream.impl.extension.window.context.WindowTriggerContext; +import org.apache.flink.datastream.impl.extension.window.function.InternalOneInputWindowStreamProcessFunction; +import org.apache.flink.datastream.impl.extension.window.utils.WindowUtils; +import org.apache.flink.datastream.impl.operators.BaseKeyedProcessOperator; +import org.apache.flink.runtime.state.VoidNamespace; +import org.apache.flink.runtime.state.VoidNamespaceSerializer; +import org.apache.flink.runtime.state.v2.internal.InternalAppendingState; +import org.apache.flink.runtime.state.v2.internal.InternalListState; +import org.apache.flink.runtime.state.v2.internal.InternalMergingState; +import org.apache.flink.streaming.api.operators.InternalTimer; +import org.apache.flink.streaming.api.operators.InternalTimerService; +import org.apache.flink.streaming.api.operators.Triggerable; +import org.apache.flink.streaming.api.windowing.assigners.MergingWindowAssigner; +import org.apache.flink.streaming.api.windowing.assigners.WindowAssigner; +import org.apache.flink.streaming.api.windowing.triggers.Trigger; +import org.apache.flink.streaming.api.windowing.triggers.TriggerResult; +import org.apache.flink.streaming.api.windowing.windows.Window; +import org.apache.flink.streaming.runtime.streamrecord.StreamRecord; + +import java.util.Collection; + +import static org.apache.flink.util.Preconditions.checkArgument; + +/** Operator for {@link OneInputWindowStreamProcessFunction} in {@link KeyedPartitionStream}. */ +public class OneInputWindowProcessOperator + extends BaseKeyedProcessOperator implements Triggerable { + + private static final long serialVersionUID = 1L; + + // ------------------------------------------------------------------------ + // Configuration values and user functions + // ------------------------------------------------------------------------ + + /** User-defined {@link WindowProcessFunction}. */ + private final OneInputWindowStreamProcessFunction windowProcessFunction; + + /** + * The allowed lateness for elements. This is used for: + * + *

    + *
  • Deciding if an element should be dropped from a window due to lateness. + *
  • Clearing the state of a window if the time out-of the {@code window.maxTimestamp + + * allowedLateness} landmark. + *
+ */ + private final long allowedLateness; + + // ------------------------------------------------------------------------ + // Operator components + // ------------------------------------------------------------------------ + + private transient InternalTimerService internalTimerService; + + /** For serializing the window in checkpoints. */ + private final TypeSerializer windowSerializer; + + // ------------------------------------------------------------------------ + // Window assigner and trigger + // ------------------------------------------------------------------------ + + private final WindowAssigner windowAssigner; + + private transient WindowAssigner.WindowAssignerContext windowAssignerContext; + + private final Trigger trigger; + + private transient WindowTriggerContext triggerContext; + + private transient DefaultOneInputWindowContext windowFunctionContext; + + // ------------------------------------------------------------------------ + // State that is not checkpointed + // ------------------------------------------------------------------------ + + private final StateDescriptor windowStateDescriptor; + + /** The state in which the window contents is stored. Each window is a namespace */ + private transient InternalAppendingState, Iterable> + windowState; + + /** + * The {@link #windowState}, typed to merging state for merging windows. Null if the window + * state is not mergeable. + */ + private transient InternalMergingState, Iterable> + windowMergingState; + + /** The state that holds the merging window metadata (the sets that describe what is merged). */ + private transient InternalListState> mergingSetsState; + + public OneInputWindowProcessOperator( + InternalOneInputWindowStreamProcessFunction windowProcessFunction, + WindowAssigner windowAssigner, + Trigger trigger, + TypeSerializer windowSerializer, + StateDescriptor windowStateDescriptor, + long allowedLateness) { + super(windowProcessFunction); + checkArgument(allowedLateness >= 0); + this.windowProcessFunction = windowProcessFunction.getWindowProcessFunction(); + this.windowAssigner = windowAssigner; + this.trigger = trigger; + this.windowSerializer = windowSerializer; + this.windowStateDescriptor = windowStateDescriptor; + this.allowedLateness = allowedLateness; + } + + @Override + public void open() throws Exception { + super.open(); + internalTimerService = + getInternalTimerService("process-window-timers", windowSerializer, this); + + // create (or restore) the state that hold the actual window contents + // NOTE - the state may be null in the case of the overriding evicting window operator + if (windowStateDescriptor != null) { + windowState = + getOrCreateKeyedState( + windowSerializer.createInstance(), + windowSerializer, + windowStateDescriptor); + } + + // create the typed and helper states for merging windows + if (windowAssigner instanceof MergingWindowAssigner) { + + // store a typed reference for the state of merging windows - sanity check + if (windowState instanceof InternalMergingState) { + windowMergingState = + (InternalMergingState, Iterable>) + windowState; + } else if (windowState != null) { + throw new IllegalStateException( + "The window uses a merging assigner, but the window state is not mergeable."); + } + + @SuppressWarnings("unchecked") + final Class> typedTuple = (Class>) (Class) Tuple2.class; + + final TupleSerializer> tupleSerializer = + new TupleSerializer<>( + typedTuple, new TypeSerializer[] {windowSerializer, windowSerializer}); + + final ListStateDescriptor> mergingSetsStateDescriptor = + new ListStateDescriptor<>("merging-window-set", tupleSerializer); + + // get the state that stores the merging sets + mergingSetsState = + getOrCreateKeyedState( + VoidNamespaceSerializer.INSTANCE.createInstance(), + VoidNamespaceSerializer.INSTANCE, + mergingSetsStateDescriptor); + mergingSetsState.setCurrentNamespace(VoidNamespace.INSTANCE); + } + + triggerContext = + new WindowTriggerContext<>( + null, null, this, internalTimerService, trigger, windowSerializer); + windowAssignerContext = + new WindowAssigner.WindowAssignerContext() { + @Override + public long getCurrentProcessingTime() { + return internalTimerService.currentProcessingTime(); + } + }; + windowFunctionContext = + new DefaultOneInputWindowContext<>( + null, + windowState, + windowProcessFunction, + this, + windowSerializer, + windowMergingState != null); + } + + @Override + public void close() throws Exception { + super.close(); + triggerContext = null; + windowFunctionContext = null; + windowAssignerContext = null; + } + + @Override + public void processElement(StreamRecord element) throws Exception { + final Collection elementWindows = + windowAssigner.assignWindows( + element.getValue(), element.getTimestamp(), windowAssignerContext); + + // if element is handled by none of assigned elementWindows + boolean isSkippedElement = true; + + final K key = (K) this.getCurrentKey(); + + if (windowAssigner instanceof MergingWindowAssigner) { + MergingWindowSet mergingWindows = getMergingWindowSet(); + + for (W window : elementWindows) { + + // adding the new window might result in a merge, in that case the actualWindow + // is the merged window and we work with that. If we don't merge then + // actualWindow == window + W actualWindow = + mergingWindows.addWindow( + window, + new MergingWindowSet.MergeFunction<>() { + @Override + public void merge( + W mergeResult, + Collection mergedWindows, + W stateWindowResult, + Collection mergedStateWindows) + throws Exception { + + if ((windowAssigner.isEventTime() + && mergeResult.maxTimestamp() + allowedLateness + <= internalTimerService + .currentWatermark())) { + throw new UnsupportedOperationException( + "The end timestamp of an " + + "event-time window cannot become earlier than the current watermark " + + "by merging. Current event time: " + + internalTimerService + .currentWatermark() + + " window: " + + mergeResult); + } else if (!windowAssigner.isEventTime()) { + long currentProcessingTime = + internalTimerService.currentProcessingTime(); + if (mergeResult.maxTimestamp() + <= currentProcessingTime) { + throw new UnsupportedOperationException( + "The end timestamp of a " + + "processing-time window cannot become earlier than the current processing time " + + "by merging. Current processing time: " + + currentProcessingTime + + " window: " + + mergeResult); + } + } + + triggerContext.setKey(key); + triggerContext.setWindow(mergeResult); + + triggerContext.onMerge(mergedWindows); + + for (W m : mergedWindows) { + triggerContext.setWindow(m); + triggerContext.clear(); + WindowUtils.deleteCleanupTimer( + m, + windowAssigner, + triggerContext, + allowedLateness); + } + + // merge the merged state windows into the newly resulting + // state window + windowMergingState.mergeNamespaces( + stateWindowResult, mergedStateWindows); + } + }); + + // drop if the window is already late + if (WindowUtils.isWindowLate( + actualWindow, windowAssigner, internalTimerService, allowedLateness)) { + mergingWindows.retireWindow(actualWindow); + continue; + } + isSkippedElement = false; + + W stateWindow = mergingWindows.getStateWindow(actualWindow); + if (stateWindow == null) { + throw new IllegalStateException( + "Window " + window + " is not in in-flight window set."); + } + + windowState.setCurrentNamespace(stateWindow); + outputCollector.setTimestamp(window.maxTimestamp()); + windowFunctionContext.setWindow(window); + windowProcessFunction.onRecord( + element.getValue(), + outputCollector, + partitionedContext, + windowFunctionContext); + + triggerContext.setKey(key); + triggerContext.setWindow(actualWindow); + + TriggerResult triggerResult = triggerContext.onElement(element); + + if (triggerResult.isFire()) { + emitWindowContents(actualWindow); + } + + if (triggerResult.isPurge()) { + windowState.clear(); + } + + WindowUtils.registerCleanupTimer( + actualWindow, windowAssigner, triggerContext, allowedLateness); + } + + // need to make sure to update the merging state in state + mergingWindows.persist(); + } else { + for (W window : elementWindows) { + + // drop if the window is already late + if (WindowUtils.isWindowLate( + window, windowAssigner, internalTimerService, allowedLateness)) { + continue; + } + isSkippedElement = false; + + windowState.setCurrentNamespace(window); + outputCollector.setTimestamp(window.maxTimestamp()); + windowFunctionContext.setWindow(window); + windowProcessFunction.onRecord( + element.getValue(), + outputCollector, + partitionedContext, + windowFunctionContext); + + triggerContext.setKey(key); + triggerContext.setWindow(window); + + TriggerResult triggerResult = triggerContext.onElement(element); + + if (triggerResult.isFire()) { + emitWindowContents(window); + } + + if (triggerResult.isPurge()) { + windowState.clear(); + } + + WindowUtils.registerCleanupTimer( + window, windowAssigner, triggerContext, allowedLateness); + } + } + + // side output input event if element not handled by any window late arriving tag has been + // set windowAssigner is event time and current timestamp + allowed lateness no less than + // element timestamp. + if (isSkippedElement + && WindowUtils.isElementLate( + element, windowAssigner, allowedLateness, internalTimerService)) { + windowProcessFunction.onLateRecord( + element.getValue(), outputCollector, partitionedContext); + } + } + + @Override + public void onEventTime(InternalTimer timer) throws Exception { + triggerContext.setKey(timer.getKey()); + triggerContext.setWindow(timer.getNamespace()); + + MergingWindowSet mergingWindows; + + if (windowAssigner instanceof MergingWindowAssigner) { + mergingWindows = getMergingWindowSet(); + W stateWindow = mergingWindows.getStateWindow(triggerContext.getWindow()); + if (stateWindow == null) { + // Timer firing for non-existent window, this can only happen if a + // trigger did not clean up timers. We have already cleared the merging + // window and therefore the Trigger state, however, so nothing to do. + return; + } else { + windowState.setCurrentNamespace(stateWindow); + } + } else { + windowState.setCurrentNamespace(triggerContext.getWindow()); + mergingWindows = null; + } + + TriggerResult triggerResult = triggerContext.onEventTime(timer.getTimestamp()); + + if (triggerResult.isFire()) { + emitWindowContents(triggerContext.getWindow()); + } + + if (triggerResult.isPurge()) { + windowState.clear(); + } + + if (windowAssigner.isEventTime() + && WindowUtils.isCleanupTime( + triggerContext.getWindow(), + timer.getTimestamp(), + windowAssigner, + allowedLateness)) { + clearAllState(triggerContext.getWindow(), windowState, mergingWindows); + } + + if (mergingWindows != null) { + // need to make sure to update the merging state in state + mergingWindows.persist(); + } + } + + @Override + public void onProcessingTime(InternalTimer timer) throws Exception { + triggerContext.setKey(timer.getKey()); + triggerContext.setWindow(timer.getNamespace()); + + MergingWindowSet mergingWindows; + + if (windowAssigner instanceof MergingWindowAssigner) { + mergingWindows = getMergingWindowSet(); + W stateWindow = mergingWindows.getStateWindow(triggerContext.getWindow()); + if (stateWindow == null) { + // Timer firing for non-existent window, this can only happen if a + // trigger did not clean up timers. We have already cleared the merging + // window and therefore the Trigger state, however, so nothing to do. + return; + } else { + windowState.setCurrentNamespace(stateWindow); + } + } else { + windowState.setCurrentNamespace(triggerContext.getWindow()); + mergingWindows = null; + } + + TriggerResult triggerResult = triggerContext.onProcessingTime(timer.getTimestamp()); + + if (triggerResult.isFire()) { + emitWindowContents(triggerContext.getWindow()); + } + + if (triggerResult.isPurge()) { + windowState.clear(); + } + + if (!windowAssigner.isEventTime() + && WindowUtils.isCleanupTime( + triggerContext.getWindow(), + timer.getTimestamp(), + windowAssigner, + allowedLateness)) { + clearAllState(triggerContext.getWindow(), windowState, mergingWindows); + } + + if (mergingWindows != null) { + // need to make sure to update the merging state in state + mergingWindows.persist(); + } + } + + @Override + protected ProcessingTimeManager getProcessingTimeManager() { + // we don't support user utilize processing time in window operators + return UnsupportedProcessingTimeManager.INSTANCE; + } + + /** + * Drops all state for the given window and calls {@link Trigger#clear(Window, + * Trigger.TriggerContext)}. + * + *

The caller must ensure that the correct key is set in the state backend and the + * triggerContext object. + */ + private void clearAllState( + W window, + AppendingState, Iterable> windowState, + MergingWindowSet mergingWindows) + throws Exception { + windowState.clear(); + triggerContext.clear(); + windowFunctionContext.setWindow(window); + windowProcessFunction.onClear(outputCollector, partitionedContext, windowFunctionContext); + if (mergingWindows != null) { + mergingWindows.retireWindow(window); + mergingWindows.persist(); + } + } + + /** Emits the contents of the given window using the {@link WindowProcessFunction}. */ + private void emitWindowContents(W window) throws Exception { + // only time window touch the time concept. + outputCollector.setTimestamp(window.maxTimestamp()); + windowFunctionContext.setWindow(window); + windowProcessFunction.onTrigger(outputCollector, partitionedContext, windowFunctionContext); + } + + /** + * Retrieves the {@link MergingWindowSet} for the currently active key. The caller must ensure + * that the correct key is set in the state backend. + * + *

The caller must also ensure to properly persist changes to state using {@link + * MergingWindowSet#persist()}. + */ + protected MergingWindowSet getMergingWindowSet() throws Exception { + + MergingWindowAssigner mergingAssigner = + (MergingWindowAssigner) windowAssigner; + return new MergingWindowSet<>(mergingAssigner, mergingSetsState); + } +} diff --git a/flink-datastream/src/main/java/org/apache/flink/datastream/impl/extension/window/operators/TwoInputNonBroadcastWindowProcessOperator.java b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/extension/window/operators/TwoInputNonBroadcastWindowProcessOperator.java new file mode 100644 --- /dev/null +++ b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/extension/window/operators/TwoInputNonBroadcastWindowProcessOperator.java @@ -0,0 +1,763 @@ +/* + * 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.datastream.impl.extension.window.operators; + +import org.apache.flink.api.common.state.v2.AppendingState; +import org.apache.flink.api.common.state.v2.ListStateDescriptor; +import org.apache.flink.api.common.state.v2.StateDescriptor; +import org.apache.flink.api.common.state.v2.StateIterator; +import org.apache.flink.api.common.typeutils.TypeSerializer; +import org.apache.flink.api.java.tuple.Tuple2; +import org.apache.flink.api.java.typeutils.runtime.TupleSerializer; +import org.apache.flink.datastream.api.context.ProcessingTimeManager; +import org.apache.flink.datastream.api.extension.window.function.TwoInputNonBroadcastWindowStreamProcessFunction; +import org.apache.flink.datastream.api.stream.KeyedPartitionStream; +import org.apache.flink.datastream.impl.context.UnsupportedProcessingTimeManager; +import org.apache.flink.datastream.impl.extension.window.context.DefaultTwoInputWindowContext; +import org.apache.flink.datastream.impl.extension.window.context.WindowTriggerContext; +import org.apache.flink.datastream.impl.extension.window.function.InternalTwoInputWindowStreamProcessFunction; +import org.apache.flink.datastream.impl.extension.window.utils.WindowUtils; +import org.apache.flink.datastream.impl.operators.BaseKeyedTwoInputNonBroadcastProcessOperator; +import org.apache.flink.runtime.state.VoidNamespace; +import org.apache.flink.runtime.state.VoidNamespaceSerializer; +import org.apache.flink.runtime.state.v2.internal.InternalAppendingState; +import org.apache.flink.runtime.state.v2.internal.InternalListState; +import org.apache.flink.runtime.state.v2.internal.InternalMergingState; +import org.apache.flink.streaming.api.operators.InternalTimer; +import org.apache.flink.streaming.api.operators.InternalTimerService; +import org.apache.flink.streaming.api.operators.Triggerable; +import org.apache.flink.streaming.api.windowing.assigners.MergingWindowAssigner; +import org.apache.flink.streaming.api.windowing.assigners.WindowAssigner; +import org.apache.flink.streaming.api.windowing.triggers.Trigger; +import org.apache.flink.streaming.api.windowing.triggers.TriggerResult; +import org.apache.flink.streaming.api.windowing.windows.Window; +import org.apache.flink.streaming.runtime.streamrecord.StreamRecord; +import org.apache.flink.util.TaggedUnion; + +import java.util.Collection; + +import static org.apache.flink.util.Preconditions.checkArgument; + +/** + * Operator for {@link TwoInputNonBroadcastWindowStreamProcessFunction} in {@link + * KeyedPartitionStream}. + */ +public class TwoInputNonBroadcastWindowProcessOperator + extends BaseKeyedTwoInputNonBroadcastProcessOperator + implements Triggerable { + + private static final long serialVersionUID = 1L; + + // ------------------------------------------------------------------------ + // Configuration values and user functions + // ------------------------------------------------------------------------ + + private final TwoInputNonBroadcastWindowStreamProcessFunction + windowProcessFunction; + + /** + * The allowed lateness for elements. This is used for: + * + *

    + *
  • Deciding if an element should be dropped from a window due to lateness. + *
  • Clearing the state of a window if the time out-of the {@code window.maxTimestamp + + * allowedLateness} landmark. + *
+ */ + protected final long allowedLateness; + + // ------------------------------------------------------------------------ + // Operator components + // ------------------------------------------------------------------------ + + protected transient InternalTimerService internalTimerService; + + /** For serializing the window in checkpoints. */ + private final TypeSerializer windowSerializer; + + // ------------------------------------------------------------------------ + // Window assigner and trigger + // ------------------------------------------------------------------------ + + private final WindowAssigner, W> windowAssigner; + + private transient WindowAssigner.WindowAssignerContext windowAssignerContext; + + private final Trigger, ? super W> trigger; + + private transient WindowTriggerContext, W> triggerContext; + + private transient DefaultTwoInputWindowContext windowFunctionContext; + + // ------------------------------------------------------------------------ + // State that is not checkpointed + // ------------------------------------------------------------------------ + + private final StateDescriptor leftWindowStateDescriptor; + + private final StateDescriptor rightWindowStateDescriptor; + + /** + * The state in which the window contents from the left input are stored. Each window is a + * namespace. + */ + private transient InternalAppendingState, Iterable> + leftWindowState; + + /** + * The state in which the window contents from the right input are stored. Each window is a + * namespace + */ + private transient InternalAppendingState, Iterable> + rightWindowState; + + /** + * The {@link #leftWindowState}, typed to merging state for merging windows. Null if the window + * state is not mergeable. + */ + private transient InternalMergingState, Iterable> + leftWindowMergingState; + + /** + * The {@link #rightWindowState}, typed to merging state for merging windows. Null if the window + * state is not mergeable. + */ + private transient InternalMergingState, Iterable> + rightWindowMergingState; + + /** The state that holds the merging window metadata (the sets that describe what is merged). */ + private transient InternalListState> mergingSetsState; + + public TwoInputNonBroadcastWindowProcessOperator( + InternalTwoInputWindowStreamProcessFunction windowFunction, + WindowAssigner, W> windowAssigner, + Trigger, ? super W> trigger, + TypeSerializer windowSerializer, + StateDescriptor leftWindowStateDescriptor, + StateDescriptor rightWindowStateDescriptor, + long allowedLateness) { + super(windowFunction); + checkArgument(allowedLateness >= 0); + this.windowProcessFunction = windowFunction.getWindowProcessFunction(); + this.windowAssigner = windowAssigner; + this.trigger = trigger; + this.windowSerializer = windowSerializer; + this.leftWindowStateDescriptor = leftWindowStateDescriptor; + this.rightWindowStateDescriptor = rightWindowStateDescriptor; + this.allowedLateness = allowedLateness; + } + + @Override + public void open() throws Exception { + super.open(); + internalTimerService = + getInternalTimerService("process-window-timers", windowSerializer, this); + + // create (or restore) the state that hold the actual window contents + // NOTE - the state may be null in the case of the overriding evicting window operator + if (leftWindowStateDescriptor != null) { + leftWindowState = + getOrCreateKeyedState( + windowSerializer.createInstance(), + windowSerializer, + leftWindowStateDescriptor); + } + + if (rightWindowStateDescriptor != null) { + rightWindowState = + getOrCreateKeyedState( + windowSerializer.createInstance(), + windowSerializer, + rightWindowStateDescriptor); + } + + // create the typed and helper states for merging windows + if (windowAssigner instanceof MergingWindowAssigner) { + + // store a typed reference for the state of merging windows - sanity check + if (leftWindowState instanceof InternalMergingState) { + leftWindowMergingState = + (InternalMergingState, Iterable>) + leftWindowState; + } else if (leftWindowState != null) { + throw new IllegalStateException( + "The window uses a merging assigner, but the window state is not mergeable."); + } + + if (rightWindowState instanceof InternalMergingState) { + rightWindowMergingState = + (InternalMergingState, Iterable>) + rightWindowState; + } else if (rightWindowState != null) { + throw new IllegalStateException( + "The window uses a merging assigner, but the window state is not mergeable."); + } + + @SuppressWarnings("unchecked") + final Class> typedTuple = (Class>) (Class) Tuple2.class; + + final TupleSerializer> tupleSerializer = + new TupleSerializer<>( + typedTuple, new TypeSerializer[] {windowSerializer, windowSerializer}); + + final ListStateDescriptor> mergingSetsStateDescriptor = + new ListStateDescriptor<>("merging-window-set", tupleSerializer); + + // get the state that stores the merging sets + mergingSetsState = + getOrCreateKeyedState( + VoidNamespaceSerializer.INSTANCE.createInstance(), + VoidNamespaceSerializer.INSTANCE, + mergingSetsStateDescriptor); + mergingSetsState.setCurrentNamespace(VoidNamespace.INSTANCE); + } + + triggerContext = + new WindowTriggerContext<>( + null, null, this, internalTimerService, trigger, windowSerializer); + windowAssignerContext = + new WindowAssigner.WindowAssignerContext() { + @Override + public long getCurrentProcessingTime() { + return internalTimerService.currentProcessingTime(); + } + }; + windowFunctionContext = + new DefaultTwoInputWindowContext<>( + null, + leftWindowState, + rightWindowState, + windowProcessFunction, + this, + windowSerializer, + leftWindowMergingState != null); + } + + @Override + public void processElement1(StreamRecord element) throws Exception { + final Collection elementWindows = + windowAssigner.assignWindows( + TaggedUnion.one(element.getValue()), + element.getTimestamp(), + windowAssignerContext); + + // if element is handled by none of assigned elementWindows + boolean isSkippedElement = true; + + final K key = (K) this.getCurrentKey(); + + if (windowAssigner instanceof MergingWindowAssigner) { + MergingWindowSet mergingWindows = getMergingWindowSet(); + + for (W window : elementWindows) { + + // adding the new window might result in a merge, in that case the actualWindow + // is the merged window and we work with that. If we don't merge then + // actualWindow == window + W actualWindow = + mergingWindows.addWindow( + window, + new MergingWindowSet.MergeFunction<>() { + @Override + public void merge( + W mergeResult, + Collection mergedWindows, + W stateWindowResult, + Collection mergedStateWindows) + throws Exception { + + if ((windowAssigner.isEventTime() + && mergeResult.maxTimestamp() + allowedLateness + <= internalTimerService + .currentWatermark())) { + throw new UnsupportedOperationException( + "The end timestamp of an " + + "event-time window cannot become earlier than the current watermark " + + "by merging. Current event time: " + + internalTimerService + .currentWatermark() + + " window: " + + mergeResult); + } else if (!windowAssigner.isEventTime()) { + long currentProcessingTime = + internalTimerService.currentProcessingTime(); + if (mergeResult.maxTimestamp() + <= currentProcessingTime) { + throw new UnsupportedOperationException( + "The end timestamp of a " + + "processing-time window cannot become earlier than the current processing time " + + "by merging. Current processing time: " + + currentProcessingTime + + " window: " + + mergeResult); + } + } + + triggerContext.setKey(key); + triggerContext.setWindow(mergeResult); + + triggerContext.onMerge(mergedWindows); + + for (W m : mergedWindows) { + triggerContext.setWindow(m); + triggerContext.clear(); + WindowUtils.deleteCleanupTimer( + m, + windowAssigner, + triggerContext, + allowedLateness); + } + + // merge the merged state windows into the newly resulting + // state window + leftWindowMergingState.mergeNamespaces( + stateWindowResult, mergedStateWindows); + rightWindowMergingState.mergeNamespaces( + stateWindowResult, mergedStateWindows); + } + }); + + // drop if the window is already late + if (WindowUtils.isWindowLate( + actualWindow, windowAssigner, internalTimerService, allowedLateness)) { + mergingWindows.retireWindow(actualWindow); + continue; + } + isSkippedElement = false; + + W stateWindow = mergingWindows.getStateWindow(actualWindow); + if (stateWindow == null) { + throw new IllegalStateException( + "Window " + window + " is not in in-flight window set."); + } + + leftWindowState.setCurrentNamespace(stateWindow); + collector.setTimestamp(window.maxTimestamp()); + windowFunctionContext.setWindow(window); + windowProcessFunction.onRecord1( + element.getValue(), collector, partitionedContext, windowFunctionContext); + + triggerContext.setKey(key); + triggerContext.setWindow(actualWindow); + + TriggerResult triggerResult = + triggerContext.onElement( + new StreamRecord<>( + TaggedUnion.one(element.getValue()), + element.getTimestamp())); + + if (triggerResult.isFire()) { + emitWindowContents(actualWindow); + } + + if (triggerResult.isPurge()) { + leftWindowState.clear(); + rightWindowState.clear(); + } + + WindowUtils.registerCleanupTimer( + actualWindow, windowAssigner, triggerContext, allowedLateness); + } + + // need to make sure to update the merging state in state + mergingWindows.persist(); + } else { + + for (W window : elementWindows) { + // drop if the window is already late + if (WindowUtils.isWindowLate( + window, windowAssigner, internalTimerService, allowedLateness)) { + continue; + } + isSkippedElement = false; + + leftWindowState.setCurrentNamespace(window); + collector.setTimestamp(window.maxTimestamp()); + windowFunctionContext.setWindow(window); + windowProcessFunction.onRecord1( + element.getValue(), collector, partitionedContext, windowFunctionContext); + + triggerContext.setKey(key); + triggerContext.setWindow(window); + + TriggerResult triggerResult = + triggerContext.onElement( + new StreamRecord<>( + TaggedUnion.one(element.getValue()), + element.getTimestamp())); + + if (triggerResult.isFire()) { + emitWindowContents(window); + } + + if (triggerResult.isPurge()) { + leftWindowState.clear(); + rightWindowState.clear(); + } + + WindowUtils.registerCleanupTimer( + window, windowAssigner, triggerContext, allowedLateness); + } + } + + // side output input event if element not handled by any window late arriving tag has been + // set windowAssigner is event time and current timestamp + allowed lateness no less than + // element timestamp. + if (isSkippedElement + && WindowUtils.isElementLate( + element, windowAssigner, allowedLateness, internalTimerService)) { + windowProcessFunction.onLateRecord1(element.getValue(), collector, partitionedContext); + } + } + + @Override + public void processElement2(StreamRecord element) throws Exception { + final Collection elementWindows = + windowAssigner.assignWindows( + TaggedUnion.two(element.getValue()), + element.getTimestamp(), + windowAssignerContext); + + // if element is handled by none of assigned elementWindows + boolean isSkippedElement = true; + + final K key = (K) this.getCurrentKey(); + + if (windowAssigner instanceof MergingWindowAssigner) { + MergingWindowSet mergingWindows = getMergingWindowSet(); + + for (W window : elementWindows) { + + // adding the new window might result in a merge, in that case the actualWindow + // is the merged window and we work with that. If we don't merge then + // actualWindow == window + W actualWindow = + mergingWindows.addWindow( + window, + new MergingWindowSet.MergeFunction<>() { + @Override + public void merge( + W mergeResult, + Collection mergedWindows, + W stateWindowResult, + Collection mergedStateWindows) + throws Exception { + + if ((windowAssigner.isEventTime() + && mergeResult.maxTimestamp() + allowedLateness + <= internalTimerService + .currentWatermark())) { + throw new UnsupportedOperationException( + "The end timestamp of an " + + "event-time window cannot become earlier than the current watermark " + + "by merging. Current event time: " + + internalTimerService + .currentWatermark() + + " window: " + + mergeResult); + } else if (!windowAssigner.isEventTime()) { + long currentProcessingTime = + internalTimerService.currentProcessingTime(); + if (mergeResult.maxTimestamp() + <= currentProcessingTime) { + throw new UnsupportedOperationException( + "The end timestamp of a " + + "processing-time window cannot become earlier than the current processing time " + + "by merging. Current processing time: " + + currentProcessingTime + + " window: " + + mergeResult); + } + } + + triggerContext.setKey(key); + triggerContext.setWindow(mergeResult); + + triggerContext.onMerge(mergedWindows); + + for (W m : mergedWindows) { + triggerContext.setWindow(m); + triggerContext.clear(); + WindowUtils.deleteCleanupTimer( + m, + windowAssigner, + triggerContext, + allowedLateness); + } + + // merge the merged state windows into the newly resulting + // state window + leftWindowMergingState.mergeNamespaces( + stateWindowResult, mergedStateWindows); + rightWindowMergingState.mergeNamespaces( + stateWindowResult, mergedStateWindows); + } + }); + + // drop if the window is already late + if (WindowUtils.isWindowLate( + actualWindow, windowAssigner, internalTimerService, allowedLateness)) { + mergingWindows.retireWindow(actualWindow); + continue; + } + isSkippedElement = false; + + W stateWindow = mergingWindows.getStateWindow(actualWindow); + if (stateWindow == null) { + throw new IllegalStateException( + "Window " + window + " is not in in-flight window set."); + } + + rightWindowState.setCurrentNamespace(stateWindow); + collector.setTimestamp(window.maxTimestamp()); + windowFunctionContext.setWindow(window); + windowProcessFunction.onRecord2( + element.getValue(), collector, partitionedContext, windowFunctionContext); + + triggerContext.setKey(key); + triggerContext.setWindow(actualWindow); + + TriggerResult triggerResult = + triggerContext.onElement( + new StreamRecord<>( + TaggedUnion.two(element.getValue()), + element.getTimestamp())); + + if (triggerResult.isFire()) { + emitWindowContents(actualWindow); + } + + if (triggerResult.isPurge()) { + leftWindowState.clear(); + rightWindowState.clear(); + } + + WindowUtils.registerCleanupTimer( + actualWindow, windowAssigner, triggerContext, allowedLateness); + } + + // need to make sure to update the merging state in state + mergingWindows.persist(); + } else { + + for (W window : elementWindows) { + // drop if the window is already late + if (WindowUtils.isWindowLate( + window, windowAssigner, internalTimerService, allowedLateness)) { + continue; + } + isSkippedElement = false; + + rightWindowState.setCurrentNamespace(window); + collector.setTimestamp(window.maxTimestamp()); + windowFunctionContext.setWindow(window); + windowProcessFunction.onRecord2( + element.getValue(), collector, partitionedContext, windowFunctionContext); + + triggerContext.setKey(key); + triggerContext.setWindow(window); + + TriggerResult triggerResult = + triggerContext.onElement( + new StreamRecord<>( + TaggedUnion.two(element.getValue()), + element.getTimestamp())); + + if (triggerResult.isFire()) { + emitWindowContents(window); + } + + if (triggerResult.isPurge()) { + leftWindowState.clear(); + rightWindowState.clear(); + } + + WindowUtils.registerCleanupTimer( + window, windowAssigner, triggerContext, allowedLateness); + } + } + + // side output input event if element not handled by any window late arriving tag has been + // set windowAssigner is event time and current timestamp + allowed lateness no less than + // element timestamp. + if (isSkippedElement + && WindowUtils.isElementLate( + element, windowAssigner, allowedLateness, internalTimerService)) { + windowProcessFunction.onLateRecord2(element.getValue(), collector, partitionedContext); + } + } + + @Override + public void onEventTime(InternalTimer timer) throws Exception { + triggerContext.setKey(timer.getKey()); + triggerContext.setWindow(timer.getNamespace()); + + MergingWindowSet mergingWindows; + + if (windowAssigner instanceof MergingWindowAssigner) { + mergingWindows = getMergingWindowSet(); + W stateWindow = mergingWindows.getStateWindow(triggerContext.getWindow()); + if (stateWindow == null) { + // Timer firing for non-existent window, this can only happen if a + // trigger did not clean up timers. We have already cleared the merging + // window and therefore the Trigger state, however, so nothing to do. + return; + } else { + leftWindowState.setCurrentNamespace(stateWindow); + rightWindowState.setCurrentNamespace(stateWindow); + } + } else { + leftWindowState.setCurrentNamespace(triggerContext.getWindow()); + rightWindowState.setCurrentNamespace(triggerContext.getWindow()); + mergingWindows = null; + } + + TriggerResult triggerResult = triggerContext.onEventTime(timer.getTimestamp()); + + if (triggerResult.isFire()) { + emitWindowContents(triggerContext.getWindow()); + } + + if (triggerResult.isPurge()) { + leftWindowState.clear(); + rightWindowState.clear(); + } + + if (windowAssigner.isEventTime() + && WindowUtils.isCleanupTime( + triggerContext.getWindow(), + timer.getTimestamp(), + windowAssigner, + allowedLateness)) { + clearAllState( + triggerContext.getWindow(), leftWindowState, rightWindowState, mergingWindows); + } + + if (mergingWindows != null) { + // need to make sure to update the merging state in state + mergingWindows.persist(); + } + } + + @Override + public void onProcessingTime(InternalTimer timer) throws Exception { + triggerContext.setKey(timer.getKey()); + triggerContext.setWindow(timer.getNamespace()); + + MergingWindowSet mergingWindows; + + if (windowAssigner instanceof MergingWindowAssigner) { + mergingWindows = getMergingWindowSet(); + W stateWindow = mergingWindows.getStateWindow(triggerContext.getWindow()); + if (stateWindow == null) { + // Timer firing for non-existent window, this can only happen if a + // trigger did not clean up timers. We have already cleared the merging + // window and therefore the Trigger state, however, so nothing to do. + return; + } else { + leftWindowState.setCurrentNamespace(stateWindow); + rightWindowState.setCurrentNamespace(stateWindow); + } + } else { + leftWindowState.setCurrentNamespace(triggerContext.getWindow()); + rightWindowState.setCurrentNamespace(triggerContext.getWindow()); + mergingWindows = null; + } + + TriggerResult triggerResult = triggerContext.onProcessingTime(timer.getTimestamp()); + + if (triggerResult.isFire()) { + emitWindowContents(triggerContext.getWindow()); + } + + if (triggerResult.isPurge()) { + leftWindowState.clear(); + rightWindowState.clear(); + } + + if (!windowAssigner.isEventTime() + && WindowUtils.isCleanupTime( + triggerContext.getWindow(), + timer.getTimestamp(), + windowAssigner, + allowedLateness)) { + clearAllState( + triggerContext.getWindow(), leftWindowState, rightWindowState, mergingWindows); + } + + if (mergingWindows != null) { + // need to make sure to update the merging state in state + mergingWindows.persist(); + } + } + + @Override + protected ProcessingTimeManager getProcessingTimeManager() { + // we don't support user utilize processing time in window operators + return UnsupportedProcessingTimeManager.INSTANCE; + } + + /** + * Drops all state for the given window and calls {@link Trigger#clear(Window, + * Trigger.TriggerContext)}. + * + *

The caller must ensure that the correct key is set in the state backend and the + * triggerContext object. + */ + private void clearAllState( + W window, + AppendingState, Iterable> leftWindowState, + AppendingState, Iterable> rightWindowState, + MergingWindowSet mergingWindows) + throws Exception { + leftWindowState.clear(); + rightWindowState.clear(); + triggerContext.clear(); + windowFunctionContext.setWindow(window); + windowProcessFunction.onClear(collector, partitionedContext, windowFunctionContext); + if (mergingWindows != null) { + mergingWindows.retireWindow(window); + mergingWindows.persist(); + } + } + + /** + * Emits the contents of the given window using the user-defined {@link + * TwoInputNonBroadcastWindowStreamProcessFunction}. + */ + private void emitWindowContents(W window) throws Exception { + // only time window touch the time concept. + collector.setTimestamp(window.maxTimestamp()); + windowFunctionContext.setWindow(window); + windowProcessFunction.onTrigger(collector, partitionedContext, windowFunctionContext); + } + + /** + * Retrieves the {@link MergingWindowSet} for the currently active key. The caller must ensure + * that the correct key is set in the state backend. + * + *

The caller must also ensure to properly persist changes to state using {@link + * MergingWindowSet#persist()}. + */ + protected MergingWindowSet getMergingWindowSet() throws Exception { + MergingWindowAssigner, W> mergingAssigner = + (MergingWindowAssigner, W>) windowAssigner; + return new MergingWindowSet<>(mergingAssigner, mergingSetsState); + } +} diff --git a/flink-datastream/src/main/java/org/apache/flink/datastream/impl/extension/window/operators/TwoOutputWindowProcessOperator.java b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/extension/window/operators/TwoOutputWindowProcessOperator.java new file mode 100644 --- /dev/null +++ b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/extension/window/operators/TwoOutputWindowProcessOperator.java @@ -0,0 +1,549 @@ +/* + * 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.datastream.impl.extension.window.operators; + +import org.apache.flink.api.common.state.v2.AppendingState; +import org.apache.flink.api.common.state.v2.ListStateDescriptor; +import org.apache.flink.api.common.state.v2.StateDescriptor; +import org.apache.flink.api.common.state.v2.StateIterator; +import org.apache.flink.api.common.typeutils.TypeSerializer; +import org.apache.flink.api.java.functions.KeySelector; +import org.apache.flink.api.java.tuple.Tuple2; +import org.apache.flink.api.java.typeutils.runtime.TupleSerializer; +import org.apache.flink.datastream.api.context.ProcessingTimeManager; +import org.apache.flink.datastream.api.extension.window.function.TwoOutputWindowStreamProcessFunction; +import org.apache.flink.datastream.api.extension.window.function.WindowProcessFunction; +import org.apache.flink.datastream.api.stream.KeyedPartitionStream; +import org.apache.flink.datastream.impl.context.UnsupportedProcessingTimeManager; +import org.apache.flink.datastream.impl.extension.window.context.DefaultOneInputWindowContext; +import org.apache.flink.datastream.impl.extension.window.context.WindowTriggerContext; +import org.apache.flink.datastream.impl.extension.window.function.InternalTwoOutputWindowStreamProcessFunction; +import org.apache.flink.datastream.impl.extension.window.utils.WindowUtils; +import org.apache.flink.datastream.impl.operators.BaseKeyedTwoOutputProcessOperator; +import org.apache.flink.runtime.state.VoidNamespace; +import org.apache.flink.runtime.state.VoidNamespaceSerializer; +import org.apache.flink.runtime.state.v2.internal.InternalAppendingState; +import org.apache.flink.runtime.state.v2.internal.InternalListState; +import org.apache.flink.runtime.state.v2.internal.InternalMergingState; +import org.apache.flink.streaming.api.operators.InternalTimer; +import org.apache.flink.streaming.api.operators.InternalTimerService; +import org.apache.flink.streaming.api.operators.Triggerable; +import org.apache.flink.streaming.api.windowing.assigners.MergingWindowAssigner; +import org.apache.flink.streaming.api.windowing.assigners.WindowAssigner; +import org.apache.flink.streaming.api.windowing.triggers.Trigger; +import org.apache.flink.streaming.api.windowing.triggers.TriggerResult; +import org.apache.flink.streaming.api.windowing.windows.Window; +import org.apache.flink.streaming.runtime.streamrecord.StreamRecord; +import org.apache.flink.util.OutputTag; + +import javax.annotation.Nullable; + +import java.util.Collection; + +import static org.apache.flink.util.Preconditions.checkArgument; + +/** Operator for {@link TwoOutputWindowStreamProcessFunction} in {@link KeyedPartitionStream}. */ +public class TwoOutputWindowProcessOperator + extends BaseKeyedTwoOutputProcessOperator + implements Triggerable { + + private static final long serialVersionUID = 1L; + + // ------------------------------------------------------------------------ + // Configuration values and user functions + // ------------------------------------------------------------------------ + + private final TwoOutputWindowStreamProcessFunction + windowProcessFunction; + + /** + * The allowed lateness for elements. This is used for: + * + *

    + *
  • Deciding if an element should be dropped from a window due to lateness. + *
  • Clearing the state of a window if the time out-of the {@code window.maxTimestamp + + * allowedLateness} landmark. + *
+ */ + private final long allowedLateness; + + // ------------------------------------------------------------------------ + // Operator components + // ------------------------------------------------------------------------ + + private transient InternalTimerService internalTimerService; + + /** For serializing the window in checkpoints. */ + private final TypeSerializer windowSerializer; + + // ------------------------------------------------------------------------ + // Window assigner and trigger + // ------------------------------------------------------------------------ + + private final WindowAssigner windowAssigner; + + private transient WindowAssigner.WindowAssignerContext windowAssignerContext; + + private final Trigger trigger; + + private transient WindowTriggerContext triggerContext; + + private transient DefaultOneInputWindowContext windowFunctionContext; + + // ------------------------------------------------------------------------ + // State that is not checkpointed + // ------------------------------------------------------------------------ + + private final StateDescriptor windowStateDescriptor; + + /** The state in which the window contents is stored. Each window is a namespace */ + private transient InternalAppendingState, Iterable> + windowState; + + /** + * The {@link #windowState}, typed to merging state for merging windows. Null if the window + * state is not mergeable. + */ + private transient InternalMergingState, Iterable> + windowMergingState; + + /** The state that holds the merging window metadata (the sets that describe what is merged). */ + private transient InternalListState> mergingSetsState; + + public TwoOutputWindowProcessOperator( + InternalTwoOutputWindowStreamProcessFunction + windowProcessFunction, + OutputTag outputTag, + @Nullable KeySelector mainOutKeySelector, + @Nullable KeySelector sideOutKeySelector, + WindowAssigner windowAssigner, + Trigger trigger, + TypeSerializer windowSerializer, + StateDescriptor windowStateDescriptor, + long allowedLateness) { + super(windowProcessFunction, outputTag, mainOutKeySelector, sideOutKeySelector); + checkArgument(allowedLateness >= 0); + this.windowProcessFunction = windowProcessFunction.getWindowProcessFunction(); + this.windowAssigner = windowAssigner; + this.trigger = trigger; + this.windowSerializer = windowSerializer; + this.windowStateDescriptor = windowStateDescriptor; + this.allowedLateness = allowedLateness; + } + + @Override + public void open() throws Exception { + super.open(); + internalTimerService = + getInternalTimerService("process-window-timers", windowSerializer, this); + + // create (or restore) the state that hold the actual window contents + // NOTE - the state may be null in the case of the overriding evicting window operator + if (windowStateDescriptor != null) { + windowState = + getOrCreateKeyedState( + windowSerializer.createInstance(), + windowSerializer, + windowStateDescriptor); + } + + // create the typed and helper states for merging windows + if (windowAssigner instanceof MergingWindowAssigner) { + + // store a typed reference for the state of merging windows - sanity check + if (windowState instanceof InternalMergingState) { + windowMergingState = + (InternalMergingState, Iterable>) + windowState; + } else if (windowState != null) { + throw new IllegalStateException( + "The window uses a merging assigner, but the window state is not mergeable."); + } + + @SuppressWarnings("unchecked") + final Class> typedTuple = (Class>) (Class) Tuple2.class; + + final TupleSerializer> tupleSerializer = + new TupleSerializer<>( + typedTuple, new TypeSerializer[] {windowSerializer, windowSerializer}); + + final ListStateDescriptor> mergingSetsStateDescriptor = + new ListStateDescriptor<>("merging-window-set", tupleSerializer); + + // get the state that stores the merging sets + mergingSetsState = + getOrCreateKeyedState( + VoidNamespaceSerializer.INSTANCE.createInstance(), + VoidNamespaceSerializer.INSTANCE, + mergingSetsStateDescriptor); + mergingSetsState.setCurrentNamespace(VoidNamespace.INSTANCE); + } + + triggerContext = + new WindowTriggerContext<>( + null, null, this, internalTimerService, trigger, windowSerializer); + windowAssignerContext = + new WindowAssigner.WindowAssignerContext() { + @Override + public long getCurrentProcessingTime() { + return internalTimerService.currentProcessingTime(); + } + }; + windowFunctionContext = + new DefaultOneInputWindowContext<>( + null, + windowState, + windowProcessFunction, + this, + windowSerializer, + windowMergingState != null); + } + + @Override + public void close() throws Exception { + super.close(); + triggerContext = null; + windowFunctionContext = null; + windowAssignerContext = null; + } + + @Override + public void processElement(StreamRecord element) throws Exception { + final Collection elementWindows = + windowAssigner.assignWindows( + element.getValue(), element.getTimestamp(), windowAssignerContext); + + // if element is handled by none of assigned elementWindows + boolean isSkippedElement = true; + + final K key = (K) this.getCurrentKey(); + + if (windowAssigner instanceof MergingWindowAssigner) { + MergingWindowSet mergingWindows = getMergingWindowSet(); + + for (W window : elementWindows) { + + // adding the new window might result in a merge, in that case the actualWindow + // is the merged window and we work with that. If we don't merge then + // actualWindow == window + W actualWindow = + mergingWindows.addWindow( + window, + new MergingWindowSet.MergeFunction<>() { + @Override + public void merge( + W mergeResult, + Collection mergedWindows, + W stateWindowResult, + Collection mergedStateWindows) + throws Exception { + + if ((windowAssigner.isEventTime() + && mergeResult.maxTimestamp() + allowedLateness + <= internalTimerService + .currentWatermark())) { + throw new UnsupportedOperationException( + "The end timestamp of an " + + "event-time window cannot become earlier than the current watermark " + + "by merging. Current event time: " + + internalTimerService + .currentWatermark() + + " window: " + + mergeResult); + } else if (!windowAssigner.isEventTime()) { + long currentProcessingTime = + internalTimerService.currentProcessingTime(); + if (mergeResult.maxTimestamp() + <= currentProcessingTime) { + throw new UnsupportedOperationException( + "The end timestamp of a " + + "processing-time window cannot become earlier than the current processing time " + + "by merging. Current processing time: " + + currentProcessingTime + + " window: " + + mergeResult); + } + } + + triggerContext.setKey(key); + triggerContext.setWindow(mergeResult); + + triggerContext.onMerge(mergedWindows); + + for (W m : mergedWindows) { + triggerContext.setWindow(m); + triggerContext.clear(); + WindowUtils.deleteCleanupTimer( + m, + windowAssigner, + triggerContext, + allowedLateness); + } + + // merge the merged state windows into the newly resulting + // state window + windowMergingState.mergeNamespaces( + stateWindowResult, mergedStateWindows); + } + }); + + // drop if the window is already late + if (WindowUtils.isWindowLate( + actualWindow, windowAssigner, internalTimerService, allowedLateness)) { + mergingWindows.retireWindow(actualWindow); + continue; + } + isSkippedElement = false; + + W stateWindow = mergingWindows.getStateWindow(actualWindow); + if (stateWindow == null) { + throw new IllegalStateException( + "Window " + window + " is not in in-flight window set."); + } + + windowState.setCurrentNamespace(stateWindow); + mainCollector.setTimestamp(window.maxTimestamp()); + sideCollector.setTimestamp(window.maxTimestamp()); + windowFunctionContext.setWindow(window); + windowProcessFunction.onRecord( + element.getValue(), + mainCollector, + sideCollector, + partitionedContext, + windowFunctionContext); + + triggerContext.setKey(key); + triggerContext.setWindow(actualWindow); + + TriggerResult triggerResult = triggerContext.onElement(element); + + if (triggerResult.isFire()) { + emitWindowContents(actualWindow); + } + + if (triggerResult.isPurge()) { + windowState.clear(); + } + + WindowUtils.registerCleanupTimer( + actualWindow, windowAssigner, triggerContext, allowedLateness); + } + + // need to make sure to update the merging state in state + mergingWindows.persist(); + } else { + for (W window : elementWindows) { + + // drop if the window is already late + if (WindowUtils.isWindowLate( + window, windowAssigner, internalTimerService, allowedLateness)) { + continue; + } + isSkippedElement = false; + + windowState.setCurrentNamespace(window); + mainCollector.setTimestamp(window.maxTimestamp()); + sideCollector.setTimestamp(window.maxTimestamp()); + windowFunctionContext.setWindow(window); + windowProcessFunction.onRecord( + element.getValue(), + mainCollector, + sideCollector, + partitionedContext, + windowFunctionContext); + + triggerContext.setKey(key); + triggerContext.setWindow(window); + + TriggerResult triggerResult = triggerContext.onElement(element); + + if (triggerResult.isFire()) { + emitWindowContents(window); + } + + if (triggerResult.isPurge()) { + windowState.clear(); + } + + WindowUtils.registerCleanupTimer( + window, windowAssigner, triggerContext, allowedLateness); + } + } + + // side output input event if element not handled by any window late arriving tag has been + // set windowAssigner is event time and current timestamp + allowed lateness no less than + // element timestamp. + if (isSkippedElement + && WindowUtils.isElementLate( + element, windowAssigner, allowedLateness, internalTimerService)) { + windowProcessFunction.onLateRecord( + element.getValue(), mainCollector, sideCollector, partitionedContext); + } + } + + @Override + public void onEventTime(InternalTimer timer) throws Exception { + triggerContext.setKey(timer.getKey()); + triggerContext.setWindow(timer.getNamespace()); + + MergingWindowSet mergingWindows; + + if (windowAssigner instanceof MergingWindowAssigner) { + mergingWindows = getMergingWindowSet(); + W stateWindow = mergingWindows.getStateWindow(triggerContext.getWindow()); + if (stateWindow == null) { + // Timer firing for non-existent window, this can only happen if a + // trigger did not clean up timers. We have already cleared the merging + // window and therefore the Trigger state, however, so nothing to do. + return; + } else { + windowState.setCurrentNamespace(stateWindow); + } + } else { + windowState.setCurrentNamespace(triggerContext.getWindow()); + mergingWindows = null; + } + + TriggerResult triggerResult = triggerContext.onEventTime(timer.getTimestamp()); + + if (triggerResult.isFire()) { + emitWindowContents(triggerContext.getWindow()); + } + + if (triggerResult.isPurge()) { + windowState.clear(); + } + + if (windowAssigner.isEventTime() + && WindowUtils.isCleanupTime( + triggerContext.getWindow(), + timer.getTimestamp(), + windowAssigner, + allowedLateness)) { + clearAllState(triggerContext.getWindow(), windowState, mergingWindows); + } + + if (mergingWindows != null) { + // need to make sure to update the merging state in state + mergingWindows.persist(); + } + } + + @Override + public void onProcessingTime(InternalTimer timer) throws Exception { + triggerContext.setKey(timer.getKey()); + triggerContext.setWindow(timer.getNamespace()); + + MergingWindowSet mergingWindows; + + if (windowAssigner instanceof MergingWindowAssigner) { + mergingWindows = getMergingWindowSet(); + W stateWindow = mergingWindows.getStateWindow(triggerContext.getWindow()); + if (stateWindow == null) { + // Timer firing for non-existent window, this can only happen if a + // trigger did not clean up timers. We have already cleared the merging + // window and therefore the Trigger state, however, so nothing to do. + return; + } else { + windowState.setCurrentNamespace(stateWindow); + } + } else { + windowState.setCurrentNamespace(triggerContext.getWindow()); + mergingWindows = null; + } + + TriggerResult triggerResult = triggerContext.onProcessingTime(timer.getTimestamp()); + + if (triggerResult.isFire()) { + emitWindowContents(triggerContext.getWindow()); + } + + if (triggerResult.isPurge()) { + windowState.clear(); + } + + if (!windowAssigner.isEventTime() + && WindowUtils.isCleanupTime( + triggerContext.getWindow(), + timer.getTimestamp(), + windowAssigner, + allowedLateness)) { + clearAllState(triggerContext.getWindow(), windowState, mergingWindows); + } + + if (mergingWindows != null) { + // need to make sure to update the merging state in state + mergingWindows.persist(); + } + } + + @Override + protected ProcessingTimeManager getProcessingTimeManager() { + // we don't support user utilize processing time in window operators + return UnsupportedProcessingTimeManager.INSTANCE; + } + + /** + * Drops all state for the given window and calls {@link Trigger#clear(Window, + * Trigger.TriggerContext)}. + * + *

The caller must ensure that the correct key is set in the state backend and the + * triggerContext object. + */ + private void clearAllState( + W window, + AppendingState, Iterable> windowState, + MergingWindowSet mergingWindows) + throws Exception { + windowState.clear(); + triggerContext.clear(); + windowFunctionContext.setWindow(window); + windowProcessFunction.onClear( + mainCollector, sideCollector, partitionedContext, windowFunctionContext); + if (mergingWindows != null) { + mergingWindows.retireWindow(window); + mergingWindows.persist(); + } + } + + /** + * Emits the contents of the given window using the user-defined {@link WindowProcessFunction}. + */ + private void emitWindowContents(W window) throws Exception { + // only time window touch the time concept. + mainCollector.setTimestamp(window.maxTimestamp()); + sideCollector.setTimestamp(window.maxTimestamp()); + windowFunctionContext.setWindow(window); + windowProcessFunction.onTrigger( + mainCollector, sideCollector, partitionedContext, windowFunctionContext); + } + + /** + * Retrieves the {@link MergingWindowSet} for the currently active key. The caller must ensure + * that the correct key is set in the state backend. + * + *

The caller must also ensure to properly persist changes to state using {@link + * MergingWindowSet#persist()}. + */ + protected MergingWindowSet getMergingWindowSet() throws Exception { + MergingWindowAssigner mergingAssigner = + (MergingWindowAssigner) windowAssigner; + return new MergingWindowSet<>(mergingAssigner, mergingSetsState); + } +} diff --git a/flink-datastream/src/main/java/org/apache/flink/datastream/impl/extension/window/utils/WindowUtils.java b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/extension/window/utils/WindowUtils.java new file mode 100644 --- /dev/null +++ b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/extension/window/utils/WindowUtils.java @@ -0,0 +1,230 @@ +/* + * 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.datastream.impl.extension.window.utils; + +import org.apache.flink.datastream.api.extension.window.strategy.GlobalWindowStrategy; +import org.apache.flink.datastream.api.extension.window.strategy.SessionWindowStrategy; +import org.apache.flink.datastream.api.extension.window.strategy.SlidingTimeWindowStrategy; +import org.apache.flink.datastream.api.extension.window.strategy.TumblingTimeWindowStrategy; +import org.apache.flink.datastream.api.extension.window.strategy.WindowStrategy; +import org.apache.flink.datastream.impl.extension.window.context.WindowTriggerContext; +import org.apache.flink.streaming.api.operators.InternalTimerService; +import org.apache.flink.streaming.api.windowing.assigners.EventTimeSessionWindows; +import org.apache.flink.streaming.api.windowing.assigners.GlobalWindows; +import org.apache.flink.streaming.api.windowing.assigners.ProcessingTimeSessionWindows; +import org.apache.flink.streaming.api.windowing.assigners.SlidingEventTimeWindows; +import org.apache.flink.streaming.api.windowing.assigners.SlidingProcessingTimeWindows; +import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows; +import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows; +import org.apache.flink.streaming.api.windowing.assigners.WindowAssigner; +import org.apache.flink.streaming.api.windowing.windows.Window; +import org.apache.flink.streaming.runtime.streamrecord.StreamRecord; + +/** Utilities for Window extension. */ +public final class WindowUtils { + + /** + * Get the allowed lateness for the window. Note that, in the current design, only + * TumblingTimeWindow and SlidingTimeWindow can have allowed lateness configured; for other + * types of windows, the returned allowed lateness will be 0. + */ + public static long getAllowedLateness(WindowStrategy windowStrategy) { + if (windowStrategy instanceof TumblingTimeWindowStrategy) { + return ((TumblingTimeWindowStrategy) windowStrategy).getAllowedLateness().toMillis(); + } else if (windowStrategy instanceof SlidingTimeWindowStrategy) { + return ((SlidingTimeWindowStrategy) windowStrategy).getAllowedLateness().toMillis(); + } else { + return 0; + } + } + + /** Create a {@link WindowAssigner} according to {@link WindowStrategy}. */ + public static WindowAssigner createWindowAssigner(WindowStrategy windowStrategy) { + if (windowStrategy instanceof GlobalWindowStrategy) { + return createGlobalWindowAssigner(); + } else if (windowStrategy instanceof TumblingTimeWindowStrategy) { + return createTumblingTimeWindowAssigner((TumblingTimeWindowStrategy) windowStrategy); + } else if (windowStrategy instanceof SlidingTimeWindowStrategy) { + return createSlidingTimeWindowAssigner((SlidingTimeWindowStrategy) windowStrategy); + } else if (windowStrategy instanceof SessionWindowStrategy) { + return createSessionWindowAssigner((SessionWindowStrategy) windowStrategy); + } else { + throw new IllegalArgumentException( + "Unsupported type of window strategy : " + windowStrategy.getClass()); + } + } + + /** Create window assigner for global window. */ + private static WindowAssigner createGlobalWindowAssigner() { + return GlobalWindows.createWithEndOfStreamTrigger(); + } + + /** Create window assigner for tumbling time window. */ + private static WindowAssigner createTumblingTimeWindowAssigner( + TumblingTimeWindowStrategy windowStrategy) { + switch (windowStrategy.getTimeType()) { + case PROCESSING: + return TumblingProcessingTimeWindows.of(windowStrategy.getWindowSize()); + case EVENT: + return TumblingEventTimeWindows.of(windowStrategy.getWindowSize()); + default: + throw new IllegalArgumentException( + "Unsupported time type : " + windowStrategy.getTimeType()); + } + } + + /** Create window assigner for sliding time window. */ + private static WindowAssigner createSlidingTimeWindowAssigner( + SlidingTimeWindowStrategy windowStrategy) { + switch (windowStrategy.getTimeType()) { + case PROCESSING: + return SlidingProcessingTimeWindows.of( + windowStrategy.getWindowSize(), windowStrategy.getWindowSlideInterval()); + case EVENT: + return SlidingEventTimeWindows.of( + windowStrategy.getWindowSize(), windowStrategy.getWindowSlideInterval()); + default: + throw new IllegalArgumentException( + "Unsupported time type : " + windowStrategy.getTimeType()); + } + } + + /** Create window assigner for session time window. */ + private static WindowAssigner createSessionWindowAssigner( + SessionWindowStrategy windowStrategy) { + switch (windowStrategy.getTimeType()) { + case PROCESSING: + return ProcessingTimeSessionWindows.withGap(windowStrategy.getSessionGap()); + case EVENT: + return EventTimeSessionWindows.withGap(windowStrategy.getSessionGap()); + default: + throw new IllegalArgumentException( + "Unsupported time type : " + windowStrategy.getTimeType()); + } + } + + /** + * Returns {@code true} if the event time is after the end timestamp plus the allowed lateness + * of the given window. + */ + public static boolean isWindowLate( + W window, + WindowAssigner windowAssigner, + InternalTimerService internalTimerService, + long allowedLateness) { + return (windowAssigner.isEventTime() + && (cleanupTime(window, windowAssigner, allowedLateness) + <= internalTimerService.currentWatermark())); + } + + /** + * Decide if a record is currently late, based on current event time and allowed lateness. + * + * @param element The element to check + * @param windowAssigner The window assigner + * @param allowedLateness The allowed lateness of the window + * @param internalTimerService The timer service to get current event time + * @return The element for which should be considered late + */ + public static boolean isElementLate( + StreamRecord element, + WindowAssigner windowAssigner, + long allowedLateness, + InternalTimerService internalTimerService) { + return (windowAssigner.isEventTime()) + && (element.getTimestamp() + allowedLateness + <= internalTimerService.currentWatermark()); + } + + /** + * Deletes the cleanup timer set for the contents of the provided window. + * + * @param window the window whose state to discard + * @param windowAssigner The window assigner + * @param triggerContext The trigger context + * @param allowedLateness The allowed lateness of the window + */ + public static void deleteCleanupTimer( + W window, + WindowAssigner windowAssigner, + WindowTriggerContext triggerContext, + long allowedLateness) { + long cleanupTime = cleanupTime(window, windowAssigner, allowedLateness); + if (cleanupTime == Long.MAX_VALUE) { + // no need to clean up because we didn't set one + return; + } + if (windowAssigner.isEventTime()) { + triggerContext.deleteEventTimeTimer(cleanupTime); + } else { + triggerContext.deleteProcessingTimeTimer(cleanupTime); + } + } + + /** + * Registers a timer to cleanup the content of the window. + * + * @param window the window whose state to discard + * @param windowAssigner The window assigner + * @param triggerContext The trigger context + * @param allowedLateness The allowed lateness of the window + */ + public static void registerCleanupTimer( + W window, + WindowAssigner windowAssigner, + WindowTriggerContext triggerContext, + long allowedLateness) { + long cleanupTime = cleanupTime(window, windowAssigner, allowedLateness); + if (cleanupTime == Long.MAX_VALUE) { + // don't set a GC timer for "end of time" + return; + } + + if (windowAssigner.isEventTime()) { + triggerContext.registerEventTimeTimer(cleanupTime); + } else { + triggerContext.registerProcessingTimeTimer(cleanupTime); + } + } + + /** + * Returns the cleanup time for a window, which is {@code window.maxTimestamp + + * allowedLateness}. In case this leads to a value greater than {@link Long#MAX_VALUE} then a + * cleanup time of {@link Long#MAX_VALUE} is returned. + * + * @param window the window whose cleanup time we are computing. + * @param windowAssigner The window assigner + * @param allowedLateness The allowed lateness of the window + */ + private static long cleanupTime( + W window, WindowAssigner windowAssigner, long allowedLateness) { + if (windowAssigner.isEventTime()) { + long cleanupTime = window.maxTimestamp() + allowedLateness; + return cleanupTime >= window.maxTimestamp() ? cleanupTime : Long.MAX_VALUE; + } else { + return window.maxTimestamp(); + } + } + + /** Returns {@code true} if the given time is the cleanup time for the given window. */ + public static boolean isCleanupTime( + W window, long time, WindowAssigner windowAssigner, long allowedLateness) { + return time == cleanupTime(window, windowAssigner, allowedLateness); + } +} diff --git a/flink-datastream/src/main/java/org/apache/flink/datastream/impl/operators/BaseKeyedProcessOperator.java b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/operators/BaseKeyedProcessOperator.java new file mode 100644 --- /dev/null +++ b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/operators/BaseKeyedProcessOperator.java @@ -0,0 +1,96 @@ +/* + * 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.datastream.impl.operators; + +import org.apache.flink.api.java.functions.KeySelector; +import org.apache.flink.datastream.api.context.NonPartitionedContext; +import org.apache.flink.datastream.api.function.OneInputStreamProcessFunction; +import org.apache.flink.datastream.api.stream.KeyedPartitionStream; +import org.apache.flink.datastream.impl.common.KeyCheckedOutputCollector; +import org.apache.flink.datastream.impl.common.OutputCollector; +import org.apache.flink.datastream.impl.common.TimestampCollector; +import org.apache.flink.datastream.impl.context.DefaultNonPartitionedContext; +import org.apache.flink.streaming.runtime.streamrecord.StreamRecord; + +import javax.annotation.Nullable; + +import java.util.HashSet; +import java.util.Set; + +/** Base operator for {@link OneInputStreamProcessFunction} in {@link KeyedPartitionStream}. */ +public class BaseKeyedProcessOperator extends ProcessOperator { + // TODO Restore this keySet when task initialized from checkpoint. + protected transient Set keySet; + + @Nullable protected final KeySelector outKeySelector; + + public BaseKeyedProcessOperator(OneInputStreamProcessFunction userFunction) { + this(userFunction, null); + } + + public BaseKeyedProcessOperator( + OneInputStreamProcessFunction userFunction, + @Nullable KeySelector outKeySelector) { + super(userFunction); + this.outKeySelector = outKeySelector; + } + + @Override + public void open() throws Exception { + this.keySet = new HashSet<>(); + super.open(); + } + + @Override + protected TimestampCollector getOutputCollector() { + return outKeySelector != null + ? new KeyCheckedOutputCollector<>( + new OutputCollector<>(output), outKeySelector, () -> (KEY) getCurrentKey()) + : new OutputCollector<>(output); + } + + @Override + protected Object currentKey() { + return getCurrentKey(); + } + + @Override + protected NonPartitionedContext getNonPartitionedContext() { + return new DefaultNonPartitionedContext<>( + context, + partitionedContext, + outputCollector, + true, + keySet, + output, + watermarkDeclarationMap); + } + + @Override + @SuppressWarnings({"rawtypes"}) + public void setKeyContextElement1(StreamRecord record) throws Exception { + super.setKeyContextElement1(record); + keySet.add(getCurrentKey()); + } + + @Override + public boolean isAsyncStateProcessingEnabled() { + return true; + } +} diff --git a/flink-datastream/src/main/java/org/apache/flink/datastream/impl/operators/BaseKeyedTwoInputNonBroadcastProcessOperator.java b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/operators/BaseKeyedTwoInputNonBroadcastProcessOperator.java new file mode 100644 --- /dev/null +++ b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/operators/BaseKeyedTwoInputNonBroadcastProcessOperator.java @@ -0,0 +1,109 @@ +/* + * 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.datastream.impl.operators; + +import org.apache.flink.api.java.functions.KeySelector; +import org.apache.flink.datastream.api.context.NonPartitionedContext; +import org.apache.flink.datastream.api.function.TwoInputNonBroadcastStreamProcessFunction; +import org.apache.flink.datastream.api.stream.KeyedPartitionStream; +import org.apache.flink.datastream.impl.common.KeyCheckedOutputCollector; +import org.apache.flink.datastream.impl.common.OutputCollector; +import org.apache.flink.datastream.impl.common.TimestampCollector; +import org.apache.flink.datastream.impl.context.DefaultNonPartitionedContext; +import org.apache.flink.streaming.runtime.streamrecord.StreamRecord; + +import javax.annotation.Nullable; + +import java.util.HashSet; +import java.util.Set; + +/** + * Base operator for {@link TwoInputNonBroadcastStreamProcessFunction} in {@link + * KeyedPartitionStream}. + */ +public class BaseKeyedTwoInputNonBroadcastProcessOperator + extends TwoInputNonBroadcastProcessOperator { + + // TODO Restore this keySet when task initialized from checkpoint. + protected transient Set keySet; + + @Nullable protected final KeySelector outKeySelector; + + public BaseKeyedTwoInputNonBroadcastProcessOperator( + TwoInputNonBroadcastStreamProcessFunction userFunction) { + this(userFunction, null); + } + + public BaseKeyedTwoInputNonBroadcastProcessOperator( + TwoInputNonBroadcastStreamProcessFunction userFunction, + @Nullable KeySelector outKeySelector) { + super(userFunction); + this.outKeySelector = outKeySelector; + } + + @Override + public void open() throws Exception { + this.keySet = new HashSet<>(); + super.open(); + } + + @Override + protected TimestampCollector getOutputCollector() { + return outKeySelector == null + ? new OutputCollector<>(output) + : new KeyCheckedOutputCollector<>( + new OutputCollector<>(output), outKeySelector, () -> (KEY) getCurrentKey()); + } + + @Override + protected Object currentKey() { + return getCurrentKey(); + } + + @Override + protected NonPartitionedContext getNonPartitionedContext() { + return new DefaultNonPartitionedContext<>( + context, + partitionedContext, + collector, + true, + keySet, + output, + watermarkDeclarationMap); + } + + @Override + @SuppressWarnings({"rawtypes"}) + public void setKeyContextElement1(StreamRecord record) throws Exception { + super.setKeyContextElement1(record); + keySet.add(getCurrentKey()); + } + + @Override + @SuppressWarnings({"rawtypes"}) + public void setKeyContextElement2(StreamRecord record) throws Exception { + super.setKeyContextElement2(record); + keySet.add(getCurrentKey()); + } + + @Override + public boolean isAsyncStateProcessingEnabled() { + return true; + } +} diff --git a/flink-datastream/src/main/java/org/apache/flink/datastream/impl/operators/BaseKeyedTwoOutputProcessOperator.java b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/operators/BaseKeyedTwoOutputProcessOperator.java new file mode 100644 --- /dev/null +++ b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/operators/BaseKeyedTwoOutputProcessOperator.java @@ -0,0 +1,118 @@ +/* + * 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.datastream.impl.operators; + +import org.apache.flink.api.java.functions.KeySelector; +import org.apache.flink.datastream.api.context.TwoOutputNonPartitionedContext; +import org.apache.flink.datastream.api.function.TwoOutputStreamProcessFunction; +import org.apache.flink.datastream.api.stream.KeyedPartitionStream; +import org.apache.flink.datastream.impl.common.KeyCheckedOutputCollector; +import org.apache.flink.datastream.impl.common.OutputCollector; +import org.apache.flink.datastream.impl.common.TimestampCollector; +import org.apache.flink.datastream.impl.context.DefaultTwoOutputNonPartitionedContext; +import org.apache.flink.streaming.runtime.streamrecord.StreamRecord; +import org.apache.flink.util.OutputTag; +import org.apache.flink.util.Preconditions; + +import javax.annotation.Nullable; + +import java.util.HashSet; +import java.util.Set; + +/** Base operator for {@link TwoOutputStreamProcessFunction} in {@link KeyedPartitionStream}. */ +public class BaseKeyedTwoOutputProcessOperator + extends TwoOutputProcessOperator { + + // TODO Restore this keySet when task initialized from checkpoint. + protected transient Set keySet; + + @Nullable protected final KeySelector mainOutKeySelector; + + @Nullable protected final KeySelector sideOutKeySelector; + + public BaseKeyedTwoOutputProcessOperator( + TwoOutputStreamProcessFunction userFunction, + OutputTag outputTag, + @Nullable KeySelector mainOutKeySelector, + @Nullable KeySelector sideOutKeySelector) { + super(userFunction, outputTag); + Preconditions.checkArgument( + (mainOutKeySelector == null && sideOutKeySelector == null) + || (mainOutKeySelector != null && sideOutKeySelector != null), + "Both mainOutKeySelector and sideOutKeySelector must be null or not null."); + this.mainOutKeySelector = mainOutKeySelector; + this.sideOutKeySelector = sideOutKeySelector; + } + + @Override + public void open() throws Exception { + this.keySet = new HashSet<>(); + super.open(); + } + + @Override + protected TimestampCollector getMainCollector() { + return mainOutKeySelector != null && sideOutKeySelector != null + ? new KeyCheckedOutputCollector<>( + new OutputCollector<>(output), + mainOutKeySelector, + () -> (KEY) getCurrentKey()) + : new OutputCollector<>(output); + } + + @Override + public TimestampCollector getSideCollector() { + return mainOutKeySelector != null && sideOutKeySelector != null + ? new KeyCheckedOutputCollector<>( + new SideOutputCollector(output), + sideOutKeySelector, + () -> (KEY) getCurrentKey()) + : new SideOutputCollector(output); + } + + @Override + protected Object currentKey() { + return getCurrentKey(); + } + + @Override + protected TwoOutputNonPartitionedContext getNonPartitionedContext() { + return new DefaultTwoOutputNonPartitionedContext<>( + context, + partitionedContext, + mainCollector, + sideCollector, + true, + keySet, + output, + watermarkDeclarationMap); + } + + @Override + @SuppressWarnings({"rawtypes"}) + public void setKeyContextElement1(StreamRecord record) throws Exception { + super.setKeyContextElement1(record); + keySet.add(getCurrentKey()); + } + + @Override + public boolean isAsyncStateProcessingEnabled() { + return true; + } +} diff --git a/flink-datastream/src/main/java/org/apache/flink/datastream/impl/operators/KeyedProcessOperator.java b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/operators/KeyedProcessOperator.java --- a/flink-datastream/src/main/java/org/apache/flink/datastream/impl/operators/KeyedProcessOperator.java +++ b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/operators/KeyedProcessOperator.java @@ -19,71 +19,43 @@ package org.apache.flink.datastream.impl.operators; import org.apache.flink.api.java.functions.KeySelector; -import org.apache.flink.datastream.api.context.NonPartitionedContext; import org.apache.flink.datastream.api.context.ProcessingTimeManager; import org.apache.flink.datastream.api.function.OneInputStreamProcessFunction; import org.apache.flink.datastream.api.stream.KeyedPartitionStream; -import org.apache.flink.datastream.impl.common.KeyCheckedOutputCollector; -import org.apache.flink.datastream.impl.common.OutputCollector; -import org.apache.flink.datastream.impl.common.TimestampCollector; -import org.apache.flink.datastream.impl.context.DefaultNonPartitionedContext; import org.apache.flink.datastream.impl.context.DefaultProcessingTimeManager; import org.apache.flink.datastream.impl.extension.eventtime.functions.EventTimeWrappedOneInputStreamProcessFunction; import org.apache.flink.runtime.state.VoidNamespace; import org.apache.flink.runtime.state.VoidNamespaceSerializer; import org.apache.flink.streaming.api.operators.InternalTimer; import org.apache.flink.streaming.api.operators.InternalTimerService; import org.apache.flink.streaming.api.operators.Triggerable; -import org.apache.flink.streaming.runtime.streamrecord.StreamRecord; import javax.annotation.Nullable; -import java.util.HashSet; -import java.util.Set; import java.util.function.Supplier; /** Operator for {@link OneInputStreamProcessFunction} in {@link KeyedPartitionStream}. */ -public class KeyedProcessOperator extends ProcessOperator +public class KeyedProcessOperator extends BaseKeyedProcessOperator implements Triggerable { private transient InternalTimerService timerService; - // TODO Restore this keySet when task initialized from checkpoint. - private transient Set keySet; - - @Nullable private final KeySelector outKeySelector; - public KeyedProcessOperator(OneInputStreamProcessFunction userFunction) { this(userFunction, null); } public KeyedProcessOperator( OneInputStreamProcessFunction userFunction, @Nullable KeySelector outKeySelector) { - super(userFunction); - this.outKeySelector = outKeySelector; + super(userFunction, outKeySelector); } @Override public void open() throws Exception { this.timerService = getInternalTimerService("processing timer", VoidNamespaceSerializer.INSTANCE, this); - this.keySet = new HashSet<>(); super.open(); } - @Override - protected TimestampCollector getOutputCollector() { - return outKeySelector != null - ? new KeyCheckedOutputCollector<>( - new OutputCollector<>(output), outKeySelector, () -> (KEY) getCurrentKey()) - : new OutputCollector<>(output); - } - - @Override - protected Object currentKey() { - return getCurrentKey(); - } - @Override public void onEventTime(InternalTimer timer) throws Exception { if (userFunction instanceof EventTimeWrappedOneInputStreamProcessFunction) { @@ -103,30 +75,6 @@ protected ProcessingTimeManager getProcessingTimeManager() { return new DefaultProcessingTimeManager(timerService); } - @Override - protected NonPartitionedContext getNonPartitionedContext() { - return new DefaultNonPartitionedContext<>( - context, - partitionedContext, - outputCollector, - true, - keySet, - output, - watermarkDeclarationMap); - } - - @Override - @SuppressWarnings({"rawtypes"}) - public void setKeyContextElement1(StreamRecord record) throws Exception { - super.setKeyContextElement1(record); - keySet.add(getCurrentKey()); - } - - @Override - public boolean isAsyncStateProcessingEnabled() { - return true; - } - @Override protected InternalTimerService getTimerService() { return timerService; diff --git a/flink-datastream/src/main/java/org/apache/flink/datastream/impl/operators/KeyedTwoInputNonBroadcastProcessOperator.java b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/operators/KeyedTwoInputNonBroadcastProcessOperator.java --- a/flink-datastream/src/main/java/org/apache/flink/datastream/impl/operators/KeyedTwoInputNonBroadcastProcessOperator.java +++ b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/operators/KeyedTwoInputNonBroadcastProcessOperator.java @@ -19,42 +19,29 @@ package org.apache.flink.datastream.impl.operators; import org.apache.flink.api.java.functions.KeySelector; -import org.apache.flink.datastream.api.context.NonPartitionedContext; import org.apache.flink.datastream.api.context.ProcessingTimeManager; import org.apache.flink.datastream.api.function.TwoInputNonBroadcastStreamProcessFunction; import org.apache.flink.datastream.api.stream.KeyedPartitionStream; -import org.apache.flink.datastream.impl.common.KeyCheckedOutputCollector; -import org.apache.flink.datastream.impl.common.OutputCollector; -import org.apache.flink.datastream.impl.common.TimestampCollector; -import org.apache.flink.datastream.impl.context.DefaultNonPartitionedContext; import org.apache.flink.datastream.impl.context.DefaultProcessingTimeManager; import org.apache.flink.datastream.impl.extension.eventtime.functions.EventTimeWrappedTwoInputNonBroadcastStreamProcessFunction; import org.apache.flink.runtime.state.VoidNamespace; import org.apache.flink.runtime.state.VoidNamespaceSerializer; import org.apache.flink.streaming.api.operators.InternalTimer; import org.apache.flink.streaming.api.operators.InternalTimerService; import org.apache.flink.streaming.api.operators.Triggerable; -import org.apache.flink.streaming.runtime.streamrecord.StreamRecord; import javax.annotation.Nullable; -import java.util.HashSet; -import java.util.Set; import java.util.function.Supplier; /** * Operator for {@link TwoInputNonBroadcastStreamProcessFunction} in {@link KeyedPartitionStream}. */ public class KeyedTwoInputNonBroadcastProcessOperator - extends TwoInputNonBroadcastProcessOperator + extends BaseKeyedTwoInputNonBroadcastProcessOperator implements Triggerable { private transient InternalTimerService timerService; - // TODO Restore this keySet when task initialized from checkpoint. - private transient Set keySet; - - @Nullable private final KeySelector outKeySelector; - public KeyedTwoInputNonBroadcastProcessOperator( TwoInputNonBroadcastStreamProcessFunction userFunction) { this(userFunction, null); @@ -63,31 +50,16 @@ public KeyedTwoInputNonBroadcastProcessOperator( public KeyedTwoInputNonBroadcastProcessOperator( TwoInputNonBroadcastStreamProcessFunction userFunction, @Nullable KeySelector outKeySelector) { - super(userFunction); - this.outKeySelector = outKeySelector; + super(userFunction, outKeySelector); } @Override public void open() throws Exception { this.timerService = getInternalTimerService("processing timer", VoidNamespaceSerializer.INSTANCE, this); - this.keySet = new HashSet<>(); super.open(); } - @Override - protected TimestampCollector getOutputCollector() { - return outKeySelector == null - ? new OutputCollector<>(output) - : new KeyCheckedOutputCollector<>( - new OutputCollector<>(output), outKeySelector, () -> (KEY) getCurrentKey()); - } - - @Override - protected Object currentKey() { - return getCurrentKey(); - } - protected ProcessingTimeManager getProcessingTimeManager() { return new DefaultProcessingTimeManager(timerService); } @@ -107,37 +79,6 @@ public void onProcessingTime(InternalTimer timer) throws Exc timer.getTimestamp(), getOutputCollector(), partitionedContext); } - @Override - protected NonPartitionedContext getNonPartitionedContext() { - return new DefaultNonPartitionedContext<>( - context, - partitionedContext, - collector, - true, - keySet, - output, - watermarkDeclarationMap); - } - - @Override - @SuppressWarnings({"rawtypes"}) - public void setKeyContextElement1(StreamRecord record) throws Exception { - super.setKeyContextElement1(record); - keySet.add(getCurrentKey()); - } - - @Override - @SuppressWarnings({"rawtypes"}) - public void setKeyContextElement2(StreamRecord record) throws Exception { - super.setKeyContextElement2(record); - keySet.add(getCurrentKey()); - } - - @Override - public boolean isAsyncStateProcessingEnabled() { - return true; - } - @Override protected InternalTimerService getTimerService() { return timerService; diff --git a/flink-datastream/src/main/java/org/apache/flink/datastream/impl/operators/KeyedTwoOutputProcessOperator.java b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/operators/KeyedTwoOutputProcessOperator.java --- a/flink-datastream/src/main/java/org/apache/flink/datastream/impl/operators/KeyedTwoOutputProcessOperator.java +++ b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/operators/KeyedTwoOutputProcessOperator.java @@ -20,42 +20,27 @@ import org.apache.flink.api.java.functions.KeySelector; import org.apache.flink.datastream.api.context.ProcessingTimeManager; -import org.apache.flink.datastream.api.context.TwoOutputNonPartitionedContext; import org.apache.flink.datastream.api.function.TwoOutputStreamProcessFunction; -import org.apache.flink.datastream.impl.common.KeyCheckedOutputCollector; -import org.apache.flink.datastream.impl.common.OutputCollector; -import org.apache.flink.datastream.impl.common.TimestampCollector; import org.apache.flink.datastream.impl.context.DefaultProcessingTimeManager; -import org.apache.flink.datastream.impl.context.DefaultTwoOutputNonPartitionedContext; import org.apache.flink.datastream.impl.extension.eventtime.functions.EventTimeWrappedTwoOutputStreamProcessFunction; import org.apache.flink.runtime.state.VoidNamespace; import org.apache.flink.runtime.state.VoidNamespaceSerializer; import org.apache.flink.streaming.api.operators.InternalTimer; import org.apache.flink.streaming.api.operators.InternalTimerService; import org.apache.flink.streaming.api.operators.Triggerable; -import org.apache.flink.streaming.runtime.streamrecord.StreamRecord; import org.apache.flink.util.OutputTag; import org.apache.flink.util.Preconditions; import javax.annotation.Nullable; -import java.util.HashSet; -import java.util.Set; import java.util.function.Supplier; /** */ public class KeyedTwoOutputProcessOperator - extends TwoOutputProcessOperator + extends BaseKeyedTwoOutputProcessOperator implements Triggerable { private transient InternalTimerService timerService; - // TODO Restore this keySet when task initialized from checkpoint. - private transient Set keySet; - - @Nullable private final KeySelector mainOutKeySelector; - - @Nullable private final KeySelector sideOutKeySelector; - public KeyedTwoOutputProcessOperator( TwoOutputStreamProcessFunction userFunction, OutputTag outputTag) { @@ -67,48 +52,20 @@ public KeyedTwoOutputProcessOperator( OutputTag outputTag, @Nullable KeySelector mainOutKeySelector, @Nullable KeySelector sideOutKeySelector) { - super(userFunction, outputTag); + super(userFunction, outputTag, mainOutKeySelector, sideOutKeySelector); Preconditions.checkArgument( (mainOutKeySelector == null && sideOutKeySelector == null) || (mainOutKeySelector != null && sideOutKeySelector != null), "Both mainOutKeySelector and sideOutKeySelector must be null or not null."); - this.mainOutKeySelector = mainOutKeySelector; - this.sideOutKeySelector = sideOutKeySelector; } @Override public void open() throws Exception { this.timerService = getInternalTimerService("processing timer", VoidNamespaceSerializer.INSTANCE, this); - this.keySet = new HashSet<>(); super.open(); } - @Override - protected TimestampCollector getMainCollector() { - return mainOutKeySelector != null && sideOutKeySelector != null - ? new KeyCheckedOutputCollector<>( - new OutputCollector<>(output), - mainOutKeySelector, - () -> (KEY) getCurrentKey()) - : new OutputCollector<>(output); - } - - @Override - public TimestampCollector getSideCollector() { - return mainOutKeySelector != null && sideOutKeySelector != null - ? new KeyCheckedOutputCollector<>( - new SideOutputCollector(output), - sideOutKeySelector, - () -> (KEY) getCurrentKey()) - : new SideOutputCollector(output); - } - - @Override - protected Object currentKey() { - return getCurrentKey(); - } - protected ProcessingTimeManager getProcessingTimeManager() { return new DefaultProcessingTimeManager(timerService); } @@ -131,31 +88,6 @@ public void onProcessingTime(InternalTimer timer) throws Exc timer.getTimestamp(), getMainCollector(), getSideCollector(), partitionedContext); } - @Override - protected TwoOutputNonPartitionedContext getNonPartitionedContext() { - return new DefaultTwoOutputNonPartitionedContext<>( - context, - partitionedContext, - mainCollector, - sideCollector, - true, - keySet, - output, - watermarkDeclarationMap); - } - - @Override - @SuppressWarnings({"rawtypes"}) - public void setKeyContextElement1(StreamRecord record) throws Exception { - super.setKeyContextElement1(record); - keySet.add(getCurrentKey()); - } - - @Override - public boolean isAsyncStateProcessingEnabled() { - return true; - } - @Override protected InternalTimerService getTimerService() { return timerService; diff --git a/flink-datastream/src/main/java/org/apache/flink/datastream/impl/stream/GlobalStreamImpl.java b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/stream/GlobalStreamImpl.java --- a/flink-datastream/src/main/java/org/apache/flink/datastream/impl/stream/GlobalStreamImpl.java +++ b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/stream/GlobalStreamImpl.java @@ -21,9 +21,11 @@ import org.apache.flink.api.common.attribute.Attribute; import org.apache.flink.api.common.state.StateDeclaration; import org.apache.flink.api.common.typeinfo.TypeInformation; +import org.apache.flink.api.common.typeinfo.Types; import org.apache.flink.api.connector.dsv2.Sink; import org.apache.flink.api.dag.Transformation; import org.apache.flink.api.java.functions.KeySelector; +import org.apache.flink.api.java.functions.NullByteKeySelector; import org.apache.flink.api.java.tuple.Tuple2; import org.apache.flink.datastream.api.function.OneInputStreamProcessFunction; import org.apache.flink.datastream.api.function.TwoInputNonBroadcastStreamProcessFunction; @@ -35,6 +37,9 @@ import org.apache.flink.datastream.api.stream.ProcessConfigurable; import org.apache.flink.datastream.impl.ExecutionEnvironmentImpl; import org.apache.flink.datastream.impl.attribute.AttributeParser; +import org.apache.flink.datastream.impl.extension.window.function.InternalOneInputWindowStreamProcessFunction; +import org.apache.flink.datastream.impl.extension.window.function.InternalTwoInputWindowStreamProcessFunction; +import org.apache.flink.datastream.impl.extension.window.function.InternalTwoOutputWindowStreamProcessFunction; import org.apache.flink.datastream.impl.operators.ProcessOperator; import org.apache.flink.datastream.impl.operators.TwoInputNonBroadcastProcessOperator; import org.apache.flink.datastream.impl.operators.TwoOutputProcessOperator; @@ -70,13 +75,30 @@ public ProcessConfigurableAndGlobalStream process( TypeInformation outType = StreamUtils.getOutputTypeForOneInputProcessFunction(processFunction, getType()); - ProcessOperator operator = new ProcessOperator<>(processFunction); - return StreamUtils.wrapWithConfigureHandle( - transform( - "Global Process", - outType, - operator, - AttributeParser.parseAttribute(processFunction))); + + if (processFunction instanceof InternalOneInputWindowStreamProcessFunction) { + Transformation outTransformation = + StreamUtils.transformOneInputWindow( + environment.getExecutionConfig(), + this, + getType(), + outType, + (InternalOneInputWindowStreamProcessFunction) + processFunction, + new NullByteKeySelector<>(), + Types.BYTE); + outTransformation.setParallelism(1, true); + return StreamUtils.wrapWithConfigureHandle( + new GlobalStreamImpl<>(this.environment, outTransformation)); + } else { + ProcessOperator operator = new ProcessOperator<>(processFunction); + return StreamUtils.wrapWithConfigureHandle( + transform( + "Global Process", + outType, + operator, + AttributeParser.parseAttribute(processFunction))); + } } @Override @@ -91,16 +113,34 @@ public TwoGlobalStreams process( StreamUtils.getOutputTypesForTwoOutputProcessFunction(processFunction, getType()); TypeInformation firstOutputType = twoOutputType.f0; TypeInformation secondOutputType = twoOutputType.f1; - OutputTag secondOutputTag = new OutputTag("Second-Output", secondOutputType); - - TwoOutputProcessOperator operator = - new TwoOutputProcessOperator<>(processFunction, secondOutputTag); - GlobalStreamImpl firstStream = - transform( - "Two-Output-Operator", - firstOutputType, - operator, - AttributeParser.parseAttribute(processFunction)); + OutputTag secondOutputTag = new OutputTag<>("Second-Output", secondOutputType); + + GlobalStreamImpl firstStream; + if (processFunction instanceof InternalTwoOutputWindowStreamProcessFunction) { + Transformation outTransformation = + StreamUtils.transformTwoOutputWindow( + environment.getExecutionConfig(), + this, + getType(), + firstOutputType, + secondOutputType, + secondOutputTag, + (InternalTwoOutputWindowStreamProcessFunction) + processFunction, + new NullByteKeySelector<>(), + Types.BYTE); + outTransformation.setParallelism(1, true); + firstStream = new GlobalStreamImpl<>(environment, outTransformation); + } else { + TwoOutputProcessOperator operator = + new TwoOutputProcessOperator<>(processFunction, secondOutputTag); + firstStream = + transform( + "Two-Output-Operator", + firstOutputType, + operator, + AttributeParser.parseAttribute(processFunction)); + } GlobalStreamImpl secondStream = new GlobalStreamImpl<>( environment, firstStream.getSideOutputTransform(secondOutputTag)); @@ -121,15 +161,34 @@ public ProcessConfigurableAndGlobalStream connectAndProcess( TypeInformation outTypeInfo = StreamUtils.getOutputTypeForTwoInputNonBroadcastProcessFunction( processFunction, getType(), ((GlobalStreamImpl) other).getType()); - TwoInputNonBroadcastProcessOperator processOperator = - new TwoInputNonBroadcastProcessOperator<>(processFunction); - Transformation outTransformation = - StreamUtils.getTwoInputTransformation( - "Global-Global-TwoInput-Process", - this, - (GlobalStreamImpl) other, - outTypeInfo, - processOperator); + + Transformation outTransformation; + if (processFunction instanceof InternalTwoInputWindowStreamProcessFunction) { + outTransformation = + StreamUtils.transformTwoInputNonBroadcastWindow( + environment.getExecutionConfig(), + getTransformation(), + getType(), + ((GlobalStreamImpl) other).getTransformation(), + ((GlobalStreamImpl) other).getType(), + outTypeInfo, + (InternalTwoInputWindowStreamProcessFunction) + processFunction, + new NullByteKeySelector<>(), + Types.BYTE, + new NullByteKeySelector<>(), + Types.BYTE); + } else { + TwoInputNonBroadcastProcessOperator processOperator = + new TwoInputNonBroadcastProcessOperator<>(processFunction); + outTransformation = + StreamUtils.getTwoInputTransformation( + "Global-Global-TwoInput-Process", + this, + (GlobalStreamImpl) other, + outTypeInfo, + processOperator); + } // Operator parallelism should always be 1 for global stream. // parallelismConfigured should be true to avoid overwritten by AdaptiveBatchScheduler. outTransformation.setParallelism(1, true); diff --git a/flink-datastream/src/main/java/org/apache/flink/datastream/impl/stream/KeyedPartitionStreamImpl.java b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/stream/KeyedPartitionStreamImpl.java --- a/flink-datastream/src/main/java/org/apache/flink/datastream/impl/stream/KeyedPartitionStreamImpl.java +++ b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/stream/KeyedPartitionStreamImpl.java @@ -19,6 +19,7 @@ package org.apache.flink.datastream.impl.stream; import org.apache.flink.api.common.state.StateDeclaration; +import org.apache.flink.api.common.state.v2.ListStateDescriptor; import org.apache.flink.api.common.typeinfo.TypeInformation; import org.apache.flink.api.connector.dsv2.Sink; import org.apache.flink.api.dag.Transformation; @@ -39,12 +40,14 @@ import org.apache.flink.datastream.impl.attribute.AttributeParser; import org.apache.flink.datastream.impl.extension.join.operators.TwoInputNonBroadcastJoinProcessFunction; import org.apache.flink.datastream.impl.extension.join.operators.TwoInputNonBroadcastJoinProcessOperator; +import org.apache.flink.datastream.impl.extension.window.function.InternalOneInputWindowStreamProcessFunction; +import org.apache.flink.datastream.impl.extension.window.function.InternalTwoInputWindowStreamProcessFunction; +import org.apache.flink.datastream.impl.extension.window.function.InternalTwoOutputWindowStreamProcessFunction; import org.apache.flink.datastream.impl.operators.KeyedProcessOperator; import org.apache.flink.datastream.impl.operators.KeyedTwoInputBroadcastProcessOperator; import org.apache.flink.datastream.impl.operators.KeyedTwoInputNonBroadcastProcessOperator; import org.apache.flink.datastream.impl.operators.KeyedTwoOutputProcessOperator; import org.apache.flink.datastream.impl.utils.StreamUtils; -import org.apache.flink.runtime.state.v2.ListStateDescriptor; import org.apache.flink.streaming.api.graph.StreamGraphGenerator; import org.apache.flink.streaming.api.transformations.DataStreamV2SinkTransformation; import org.apache.flink.streaming.api.transformations.PartitionTransformation; @@ -118,10 +121,24 @@ public ProcessConfigurableAndNonKeyedPartitionStream process( TypeInformation outType; outType = StreamUtils.getOutputTypeForOneInputProcessFunction(processFunction, getType()); - KeyedProcessOperator operator = new KeyedProcessOperator<>(processFunction); - Transformation transform = - StreamUtils.getOneInputKeyedTransformation( - "KeyedProcess", this, outType, operator, keySelector, keyType); + Transformation transform; + if (processFunction instanceof InternalOneInputWindowStreamProcessFunction) { + transform = + StreamUtils.transformOneInputWindow( + environment.getExecutionConfig(), + this, + getType(), + outType, + (InternalOneInputWindowStreamProcessFunction) + processFunction, + keySelector, + keyType); + } else { + KeyedProcessOperator operator = new KeyedProcessOperator<>(processFunction); + transform = + StreamUtils.getOneInputKeyedTransformation( + "KeyedProcess", this, outType, operator, keySelector, keyType); + } transform.setAttribute(AttributeParser.parseAttribute(processFunction)); environment.addOperator(transform); return StreamUtils.wrapWithConfigureHandle( @@ -139,11 +156,26 @@ public ProcessConfigurableAndKeyedPartitionStream process( TypeInformation outType = StreamUtils.getOutputTypeForOneInputProcessFunction(processFunction, getType()); - KeyedProcessOperator operator = - new KeyedProcessOperator<>(processFunction, checkNotNull(newKeySelector)); - Transformation transform = - StreamUtils.getOneInputKeyedTransformation( - "KeyedProcess", this, outType, operator, keySelector, keyType); + + Transformation transform; + if (processFunction instanceof InternalOneInputWindowStreamProcessFunction) { + transform = + StreamUtils.transformOneInputWindow( + environment.getExecutionConfig(), + this, + getType(), + outType, + (InternalOneInputWindowStreamProcessFunction) + processFunction, + keySelector, + keyType); + } else { + KeyedProcessOperator operator = + new KeyedProcessOperator<>(processFunction, checkNotNull(newKeySelector)); + transform = + StreamUtils.getOneInputKeyedTransformation( + "KeyedProcess", this, outType, operator, keySelector, keyType); + } NonKeyedPartitionStreamImpl outputStream = new NonKeyedPartitionStreamImpl<>(environment, transform); transform.setAttribute(AttributeParser.parseAttribute(processFunction)); @@ -173,17 +205,33 @@ public ProcessConfigurableAndTwoKeyedPartitionStreams secondOutputType = twoOutputType.f1; OutputTag secondOutputTag = new OutputTag<>("Second-Output", secondOutputType); - KeyedTwoOutputProcessOperator operator = - new KeyedTwoOutputProcessOperator<>( - processFunction, secondOutputTag, keySelector1, keySelector2); - Transformation mainOutputTransform = - StreamUtils.getOneInputKeyedTransformation( - "Two-Output-Process", - this, - firstOutputType, - operator, - keySelector, - keyType); + Transformation mainOutputTransform; + if (processFunction instanceof InternalTwoOutputWindowStreamProcessFunction) { + mainOutputTransform = + StreamUtils.transformTwoOutputWindow( + environment.getExecutionConfig(), + this, + getType(), + firstOutputType, + secondOutputType, + secondOutputTag, + (InternalTwoOutputWindowStreamProcessFunction) + processFunction, + keySelector, + keyType); + } else { + KeyedTwoOutputProcessOperator operator = + new KeyedTwoOutputProcessOperator<>( + processFunction, secondOutputTag, keySelector1, keySelector2); + mainOutputTransform = + StreamUtils.getOneInputKeyedTransformation( + "Two-Output-Process", + this, + firstOutputType, + operator, + keySelector, + keyType); + } mainOutputTransform.setAttribute(AttributeParser.parseAttribute(processFunction)); NonKeyedPartitionStreamImpl nonKeyedMainOutputStream = new NonKeyedPartitionStreamImpl<>(environment, mainOutputTransform); @@ -226,16 +274,32 @@ public ProcessConfigurableAndTwoNonKeyedPartitionStream TypeInformation secondOutputType = twoOutputType.f1; OutputTag secondOutputTag = new OutputTag<>("Second-Output", secondOutputType); - KeyedTwoOutputProcessOperator operator = - new KeyedTwoOutputProcessOperator<>(processFunction, secondOutputTag); - Transformation firstTransformation = - StreamUtils.getOneInputKeyedTransformation( - "Two-Output-Process", - this, - firstOutputType, - operator, - keySelector, - keyType); + Transformation firstTransformation; + if (processFunction instanceof InternalTwoOutputWindowStreamProcessFunction) { + firstTransformation = + StreamUtils.transformTwoOutputWindow( + environment.getExecutionConfig(), + this, + getType(), + firstOutputType, + secondOutputType, + secondOutputTag, + (InternalTwoOutputWindowStreamProcessFunction) + processFunction, + keySelector, + keyType); + } else { + KeyedTwoOutputProcessOperator operator = + new KeyedTwoOutputProcessOperator<>(processFunction, secondOutputTag); + firstTransformation = + StreamUtils.getOneInputKeyedTransformation( + "Two-Output-Process", + this, + firstOutputType, + operator, + keySelector, + keyType); + } firstTransformation.setAttribute(AttributeParser.parseAttribute(processFunction)); NonKeyedPartitionStreamImpl firstStream = new NonKeyedPartitionStreamImpl<>(environment, firstTransformation); @@ -270,6 +334,21 @@ public ProcessConfigurableAndNonKeyedPartitionStream connect if (processFunction instanceof TwoInputNonBroadcastJoinProcessFunction) { outTransformation = getJoinTransformation(other, processFunction, outTypeInfo); + } else if (processFunction instanceof InternalTwoInputWindowStreamProcessFunction) { + outTransformation = + StreamUtils.transformTwoInputNonBroadcastWindow( + environment.getExecutionConfig(), + this.transformation, + getType(), + ((KeyedPartitionStreamImpl) other).getTransformation(), + ((KeyedPartitionStreamImpl) other).getType(), + outTypeInfo, + (InternalTwoInputWindowStreamProcessFunction) + processFunction, + keySelector, + keyType, + ((KeyedPartitionStreamImpl) other).getKeySelector(), + ((KeyedPartitionStreamImpl) other).getKeyType()); } else { KeyedTwoInputNonBroadcastProcessOperator processOperator = new KeyedTwoInputNonBroadcastProcessOperator<>(processFunction); diff --git a/flink-datastream/src/main/java/org/apache/flink/datastream/impl/stream/NonKeyedPartitionStreamImpl.java b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/stream/NonKeyedPartitionStreamImpl.java --- a/flink-datastream/src/main/java/org/apache/flink/datastream/impl/stream/NonKeyedPartitionStreamImpl.java +++ b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/stream/NonKeyedPartitionStreamImpl.java @@ -20,10 +20,13 @@ import org.apache.flink.api.common.state.StateDeclaration; import org.apache.flink.api.common.typeinfo.TypeInformation; +import org.apache.flink.api.common.typeinfo.Types; import org.apache.flink.api.connector.dsv2.Sink; import org.apache.flink.api.dag.Transformation; import org.apache.flink.api.java.functions.KeySelector; +import org.apache.flink.api.java.functions.NullByteKeySelector; import org.apache.flink.api.java.tuple.Tuple2; +import org.apache.flink.datastream.api.extension.window.strategy.GlobalWindowStrategy; import org.apache.flink.datastream.api.function.OneInputStreamProcessFunction; import org.apache.flink.datastream.api.function.TwoInputBroadcastStreamProcessFunction; import org.apache.flink.datastream.api.function.TwoInputNonBroadcastStreamProcessFunction; @@ -35,6 +38,9 @@ import org.apache.flink.datastream.api.stream.ProcessConfigurable; import org.apache.flink.datastream.impl.ExecutionEnvironmentImpl; import org.apache.flink.datastream.impl.attribute.AttributeParser; +import org.apache.flink.datastream.impl.extension.window.function.InternalOneInputWindowStreamProcessFunction; +import org.apache.flink.datastream.impl.extension.window.function.InternalTwoInputWindowStreamProcessFunction; +import org.apache.flink.datastream.impl.extension.window.function.InternalTwoOutputWindowStreamProcessFunction; import org.apache.flink.datastream.impl.operators.ProcessOperator; import org.apache.flink.datastream.impl.operators.TwoInputBroadcastProcessOperator; import org.apache.flink.datastream.impl.operators.TwoInputNonBroadcastProcessOperator; @@ -52,6 +58,7 @@ import java.util.HashSet; import static org.apache.flink.datastream.impl.utils.StreamUtils.validateStates; +import static org.apache.flink.util.Preconditions.checkState; /** The implementation of {@link NonKeyedPartitionStream}. */ public class NonKeyedPartitionStreamImpl extends AbstractDataStream @@ -73,9 +80,31 @@ public ProcessConfigurableAndNonKeyedPartitionStream process( TypeInformation outType = StreamUtils.getOutputTypeForOneInputProcessFunction(processFunction, getType()); - ProcessOperator operator = new ProcessOperator<>(processFunction); - OneInputTransformation outputTransform = - StreamUtils.getOneInputTransformation("Process", this, outType, operator); + OneInputTransformation outputTransform; + + if (processFunction instanceof InternalOneInputWindowStreamProcessFunction) { + InternalOneInputWindowStreamProcessFunction internalProcessFunction = + (InternalOneInputWindowStreamProcessFunction) processFunction; + checkState( + internalProcessFunction.getWindowStrategy() instanceof GlobalWindowStrategy, + "Only the Global Window is permitted for execution in NonKeyedPartitionStream."); + outputTransform = + (OneInputTransformation) + StreamUtils.transformOneInputWindow( + environment.getExecutionConfig(), + this, + getType(), + outType, + (InternalOneInputWindowStreamProcessFunction) + processFunction, + new NullByteKeySelector<>(), + Types.BYTE); + } else { + ProcessOperator operator = new ProcessOperator<>(processFunction); + outputTransform = + StreamUtils.getOneInputTransformation("Process", this, outType, operator); + } + outputTransform.setAttribute(AttributeParser.parseAttribute(processFunction)); environment.addOperator(outputTransform); return StreamUtils.wrapWithConfigureHandle( @@ -98,11 +127,35 @@ public ProcessConfigurableAndTwoNonKeyedPartitionStream TypeInformation secondOutputType = twoOutputType.f1; OutputTag secondOutputTag = new OutputTag<>("Second-Output", secondOutputType); - TwoOutputProcessOperator operator = - new TwoOutputProcessOperator<>(processFunction, secondOutputTag); - OneInputTransformation outTransformation = - StreamUtils.getOneInputTransformation( - "Two-Output-Operator", this, firstOutputType, operator); + OneInputTransformation outTransformation; + if (processFunction instanceof InternalTwoOutputWindowStreamProcessFunction) { + InternalTwoOutputWindowStreamProcessFunction internalProcessFunction = + (InternalTwoOutputWindowStreamProcessFunction) + processFunction; + checkState( + internalProcessFunction.getWindowStrategy() instanceof GlobalWindowStrategy, + "Only the Global Window is permitted for execution in NonKeyedPartitionStream."); + + outTransformation = + (OneInputTransformation) + StreamUtils.transformTwoOutputWindow( + environment.getExecutionConfig(), + this, + getType(), + firstOutputType, + secondOutputType, + secondOutputTag, + (InternalTwoOutputWindowStreamProcessFunction) + processFunction, + new NullByteKeySelector<>(), + Types.BYTE); + } else { + TwoOutputProcessOperator operator = + new TwoOutputProcessOperator<>(processFunction, secondOutputTag); + outTransformation = + StreamUtils.getOneInputTransformation( + "Two-Output-Operator", this, firstOutputType, operator); + } outTransformation.setAttribute(AttributeParser.parseAttribute(processFunction)); NonKeyedPartitionStreamImpl firstStream = new NonKeyedPartitionStreamImpl<>(environment, outTransformation); @@ -135,15 +188,39 @@ public ProcessConfigurableAndNonKeyedPartitionStream connect getType(), ((NonKeyedPartitionStreamImpl) other).getType()); - TwoInputNonBroadcastProcessOperator processOperator = - new TwoInputNonBroadcastProcessOperator<>(processFunction); - Transformation outTransformation = - StreamUtils.getTwoInputTransformation( - "TwoInput-Process", - this, - (NonKeyedPartitionStreamImpl) other, - outTypeInfo, - processOperator); + Transformation outTransformation; + if (processFunction instanceof InternalTwoInputWindowStreamProcessFunction) { + InternalTwoInputWindowStreamProcessFunction internalWindowFunction = + (InternalTwoInputWindowStreamProcessFunction) + processFunction; + checkState( + internalWindowFunction.getWindowStrategy() instanceof GlobalWindowStrategy, + "Only the Global Window is permitted for execution in NonKeyedPartitionStream."); + + outTransformation = + StreamUtils.transformTwoInputNonBroadcastWindow( + environment.getExecutionConfig(), + this.transformation, + getType(), + ((NonKeyedPartitionStreamImpl) other).getTransformation(), + ((NonKeyedPartitionStreamImpl) other).getType(), + outTypeInfo, + internalWindowFunction, + new NullByteKeySelector<>(), + Types.BYTE, + new NullByteKeySelector<>(), + Types.BYTE); + } else { + TwoInputNonBroadcastProcessOperator processOperator = + new TwoInputNonBroadcastProcessOperator<>(processFunction); + outTransformation = + StreamUtils.getTwoInputTransformation( + "TwoInput-Process", + this, + (NonKeyedPartitionStreamImpl) other, + outTypeInfo, + processOperator); + } outTransformation.setAttribute(AttributeParser.parseAttribute(processFunction)); environment.addOperator(outTransformation); return StreamUtils.wrapWithConfigureHandle( diff --git a/flink-datastream/src/main/java/org/apache/flink/datastream/impl/utils/StreamUtils.java b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/utils/StreamUtils.java --- a/flink-datastream/src/main/java/org/apache/flink/datastream/impl/utils/StreamUtils.java +++ b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/utils/StreamUtils.java @@ -18,15 +18,21 @@ package org.apache.flink.datastream.impl.utils; +import org.apache.flink.api.common.ExecutionConfig; import org.apache.flink.api.common.state.IllegalRedistributionModeException; import org.apache.flink.api.common.state.StateDeclaration; +import org.apache.flink.api.common.state.v2.ListStateDescriptor; import org.apache.flink.api.common.typeinfo.TypeInformation; import org.apache.flink.api.connector.dsv2.Sink; import org.apache.flink.api.connector.dsv2.WrappedSink; +import org.apache.flink.api.dag.Transformation; import org.apache.flink.api.java.functions.KeySelector; import org.apache.flink.api.java.tuple.Tuple2; import org.apache.flink.api.java.typeutils.TypeExtractor; import org.apache.flink.datastream.api.extension.join.JoinFunction; +import org.apache.flink.datastream.api.extension.window.function.OneInputWindowStreamProcessFunction; +import org.apache.flink.datastream.api.extension.window.function.TwoInputNonBroadcastWindowStreamProcessFunction; +import org.apache.flink.datastream.api.extension.window.function.TwoOutputWindowStreamProcessFunction; import org.apache.flink.datastream.api.function.OneInputStreamProcessFunction; import org.apache.flink.datastream.api.function.TwoInputBroadcastStreamProcessFunction; import org.apache.flink.datastream.api.function.TwoInputNonBroadcastStreamProcessFunction; @@ -39,6 +45,12 @@ import org.apache.flink.datastream.impl.extension.eventtime.functions.EventTimeWrappedTwoInputNonBroadcastStreamProcessFunction; import org.apache.flink.datastream.impl.extension.eventtime.functions.EventTimeWrappedTwoOutputStreamProcessFunction; import org.apache.flink.datastream.impl.extension.join.operators.TwoInputNonBroadcastJoinProcessFunction; +import org.apache.flink.datastream.impl.extension.window.function.InternalOneInputWindowStreamProcessFunction; +import org.apache.flink.datastream.impl.extension.window.function.InternalTwoInputWindowStreamProcessFunction; +import org.apache.flink.datastream.impl.extension.window.function.InternalTwoOutputWindowStreamProcessFunction; +import org.apache.flink.datastream.impl.extension.window.operators.OneInputWindowProcessOperator; +import org.apache.flink.datastream.impl.extension.window.operators.TwoInputNonBroadcastWindowProcessOperator; +import org.apache.flink.datastream.impl.extension.window.operators.TwoOutputWindowProcessOperator; import org.apache.flink.datastream.impl.stream.AbstractDataStream; import org.apache.flink.datastream.impl.stream.GlobalStreamImpl; import org.apache.flink.datastream.impl.stream.KeyedPartitionStreamImpl; @@ -54,6 +66,10 @@ import org.apache.flink.streaming.api.transformations.DataStreamV2SinkTransformation; import org.apache.flink.streaming.api.transformations.OneInputTransformation; import org.apache.flink.streaming.api.transformations.TwoInputTransformation; +import org.apache.flink.streaming.api.windowing.assigners.WindowAssigner; +import org.apache.flink.streaming.api.windowing.windows.Window; +import org.apache.flink.util.OutputTag; +import org.apache.flink.util.TaggedUnion; import org.apache.flink.util.Utils; import java.util.Set; @@ -70,6 +86,20 @@ public final class StreamUtils { public static TypeInformation getOutputTypeForOneInputProcessFunction( OneInputStreamProcessFunction processFunction, TypeInformation inTypeInformation) { + TypeInformation outType; + if (processFunction instanceof InternalOneInputWindowStreamProcessFunction) { + return TypeExtractor.getUnaryOperatorReturnType( + ((InternalOneInputWindowStreamProcessFunction) processFunction) + .getWindowProcessFunction(), + OneInputWindowStreamProcessFunction.class, + 0, + 1, + new int[] {1, 0}, + null, + Utils.getCallLocationName(), + false); + } + if (processFunction instanceof EventTimeWrappedOneInputStreamProcessFunction) { processFunction = ((EventTimeWrappedOneInputStreamProcessFunction) processFunction) @@ -111,6 +141,22 @@ TypeInformation getOutputTypeForTwoInputNonBroadcastProcessFunction( true); } + if (processFunction instanceof InternalTwoInputWindowStreamProcessFunction) { + return TypeExtractor.getBinaryOperatorReturnType( + ((InternalTwoInputWindowStreamProcessFunction) + processFunction) + .getWindowProcessFunction(), + TwoInputNonBroadcastWindowStreamProcessFunction.class, + 0, + 1, + 2, + new int[] {2, 0}, + null, + null, + Utils.getCallLocationName(), + false); + } + if (processFunction instanceof EventTimeWrappedTwoInputNonBroadcastStreamProcessFunction) { processFunction = ((EventTimeWrappedTwoInputNonBroadcastStreamProcessFunction) processFunction) @@ -168,6 +214,34 @@ TypeInformation getOutputTypeForTwoInputBroadcastProcessFunction( TwoOutputStreamProcessFunction twoOutputStreamProcessFunction, TypeInformation inTypeInformation) { + if (twoOutputStreamProcessFunction + instanceof InternalTwoOutputWindowStreamProcessFunction) { + TypeInformation firstOutputType = + TypeExtractor.getUnaryOperatorReturnType( + ((InternalTwoOutputWindowStreamProcessFunction) + twoOutputStreamProcessFunction) + .getWindowProcessFunction(), + TwoOutputWindowStreamProcessFunction.class, + 0, + 1, + new int[] {1, 0}, + inTypeInformation, + Utils.getCallLocationName(), + true); + TypeInformation secondOutputType = + TypeExtractor.getUnaryOperatorReturnType( + ((InternalTwoOutputWindowStreamProcessFunction) + twoOutputStreamProcessFunction) + .getWindowProcessFunction(), + TwoOutputWindowStreamProcessFunction.class, + 0, + 2, + new int[] {2, 0}, + inTypeInformation, + Utils.getCallLocationName(), + true); + return Tuple2.of(firstOutputType, secondOutputType); + } if (twoOutputStreamProcessFunction instanceof EventTimeWrappedTwoOutputStreamProcessFunction) { @@ -293,6 +367,44 @@ public static TwoInputTransformation getTwoInputT return transform; } + /** Construct and return a {@link TwoInputTransformation} from two input streams. */ + public static + TwoInputTransformation getTwoInputTransformation( + String operatorName, + Transformation inputStream1, + Transformation inputStream2, + TypeInformation outTypeInformation, + TwoInputStreamOperator operator, + KeySelector keySelector1, + TypeInformation keyType1, + KeySelector keySelector2, + TypeInformation keyType2) { + + if (!(keyType1.canEqual(keyType2) && keyType1.equals(keyType2))) { + throw new UnsupportedOperationException( + "Key types if input KeyedStreams " + + "don't match: " + + keyType1 + + " and " + + keyType2 + + "."); + } + + TwoInputTransformation transform = + new TwoInputTransformation<>( + inputStream1, + inputStream2, + operatorName, + SimpleOperatorFactory.of(operator), + outTypeInformation, + // inputStream1 & 2 share the same env. + inputStream1.getParallelism(), + false); + transform.setStateKeySelectors(keySelector1, keySelector2); + transform.setStateKeyType(keyType1); + return transform; + } + /** Construct and return a new DataStream with one input operator. */ public static AbstractDataStream transformOneInputOperator( String operatorName, @@ -319,6 +431,118 @@ public static AbstractDataStream transformOneInputOperator( return returnStream; } + /** Construct and return a {@link OneInputTransformation} of one input window operator. */ + public static Transformation transformOneInputWindow( + ExecutionConfig executionConfig, + AbstractDataStream inputStream, + TypeInformation inputType, + TypeInformation outType, + InternalOneInputWindowStreamProcessFunction internalWindowFunction, + KeySelector keySelector, + TypeInformation keyType) { + WindowAssigner assigner = internalWindowFunction.getAssigner(); + ListStateDescriptor stateDesc = + new ListStateDescriptor<>( + "window-state", TypeExtractor.createTypeInfo(inputType.getTypeClass())); + + OneInputWindowProcessOperator windowProcessOperator = + new OneInputWindowProcessOperator<>( + internalWindowFunction, + assigner, + internalWindowFunction.getTrigger(), + assigner.getWindowSerializer(executionConfig), + stateDesc, + internalWindowFunction.getAllowedLateness()); + return StreamUtils.getOneInputKeyedTransformation( + "Window", inputStream, outType, windowProcessOperator, keySelector, keyType); + } + + /** Construct and return a {@link OneInputTransformation} of one input window operator. */ + public static + Transformation transformTwoInputNonBroadcastWindow( + ExecutionConfig executionConfig, + Transformation inputStream1, + TypeInformation inputType1, + Transformation inputStream2, + TypeInformation inputType2, + TypeInformation outType, + InternalTwoInputWindowStreamProcessFunction + internalWindowFunction, + KeySelector keySelector1, + TypeInformation keyType1, + KeySelector keySelector2, + TypeInformation keyType2) { + WindowAssigner, W> assigner = internalWindowFunction.getAssigner(); + ListStateDescriptor leftStateDesc = + new ListStateDescriptor<>( + "two-input-window-left-state", + TypeExtractor.createTypeInfo(inputType1.getTypeClass())); + + ListStateDescriptor rightStateDesc = + new ListStateDescriptor<>( + "two-input-window-right-state", + TypeExtractor.createTypeInfo(inputType2.getTypeClass())); + + TwoInputNonBroadcastWindowProcessOperator windowProcessOperator = + new TwoInputNonBroadcastWindowProcessOperator<>( + internalWindowFunction, + assigner, + internalWindowFunction.getTrigger(), + assigner.getWindowSerializer(executionConfig), + leftStateDesc, + rightStateDesc, + internalWindowFunction.getAllowedLateness()); + return StreamUtils.getTwoInputTransformation( + "TwoInput-NonBroadcast-Window", + inputStream1, + inputStream2, + outType, + windowProcessOperator, + keySelector1, + keyType1, + keySelector2, + keyType2); + } + + /** Construct and return a {@link OneInputTransformation} of two output window operator. */ + public static + Transformation transformTwoOutputWindow( + ExecutionConfig executionConfig, + AbstractDataStream inputStream, + TypeInformation inputType, + TypeInformation outType1, + TypeInformation outType2, + OutputTag secondOutputTag, + InternalTwoOutputWindowStreamProcessFunction + internalWindowFunction, + KeySelector keySelector, + TypeInformation keyType) { + WindowAssigner assigner = internalWindowFunction.getAssigner(); + ListStateDescriptor stateDesc = + new ListStateDescriptor<>( + "two-output-window-state", + TypeExtractor.createTypeInfo(inputType.getTypeClass())); + + TwoOutputWindowProcessOperator windowProcessOperator = + new TwoOutputWindowProcessOperator<>( + internalWindowFunction, + secondOutputTag, + null, + null, + assigner, + internalWindowFunction.getTrigger(), + assigner.getWindowSerializer(executionConfig), + stateDesc, + internalWindowFunction.getAllowedLateness()); + return StreamUtils.getOneInputKeyedTransformation( + "TwoOutput-Window", + inputStream, + outType1, + windowProcessOperator, + keySelector, + keyType); + } + /** Add sink operator to the input stream. */ public static DataStreamV2SinkTransformation addSinkOperator( AbstractDataStream inputStream, Sink sink, TypeInformation typeInformation) { diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/asyncprocessing/operators/AbstractAsyncStateStreamOperator.java b/flink-runtime/src/main/java/org/apache/flink/runtime/asyncprocessing/operators/AbstractAsyncStateStreamOperator.java --- a/flink-runtime/src/main/java/org/apache/flink/runtime/asyncprocessing/operators/AbstractAsyncStateStreamOperator.java +++ b/flink-runtime/src/main/java/org/apache/flink/runtime/asyncprocessing/operators/AbstractAsyncStateStreamOperator.java @@ -236,7 +236,7 @@ public final ThrowingConsumer, Exception> getRecordProcessor } /** Create new state (v2) based on new state descriptor. */ - protected S getOrCreateKeyedState( + public S getOrCreateKeyedState( @Nonnull N defaultNamespace, @Nonnull TypeSerializer namespaceSerializer, @Nonnull StateDescriptor stateDescriptor) diff --git a/flink-runtime/src/main/java/org/apache/flink/streaming/api/datastream/CoGroupedStreams.java b/flink-runtime/src/main/java/org/apache/flink/streaming/api/datastream/CoGroupedStreams.java --- a/flink-runtime/src/main/java/org/apache/flink/streaming/api/datastream/CoGroupedStreams.java +++ b/flink-runtime/src/main/java/org/apache/flink/streaming/api/datastream/CoGroupedStreams.java @@ -40,14 +40,14 @@ import org.apache.flink.streaming.api.windowing.windows.Window; import org.apache.flink.util.Collector; import org.apache.flink.util.Preconditions; +import org.apache.flink.util.TaggedUnion; import javax.annotation.Nullable; import java.io.IOException; import java.time.Duration; import java.util.ArrayList; import java.util.List; -import java.util.Objects; import java.util.Optional; import static java.util.Objects.requireNonNull; @@ -392,59 +392,9 @@ WindowedStream, KEY, W> getWindowedStream() { } // ------------------------------------------------------------------------ - // Data type and type information for Tagged Union + // Type information for Tagged Union // ------------------------------------------------------------------------ - /** Internal class for implementing tagged union co-group. */ - @Internal - public static class TaggedUnion { - private final T1 one; - private final T2 two; - - private TaggedUnion(T1 one, T2 two) { - this.one = one; - this.two = two; - } - - public boolean isOne() { - return one != null; - } - - public boolean isTwo() { - return two != null; - } - - public T1 getOne() { - return one; - } - - public T2 getTwo() { - return two; - } - - public static TaggedUnion one(T1 one) { - return new TaggedUnion<>(one, null); - } - - public static TaggedUnion two(T2 two) { - return new TaggedUnion<>(null, two); - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - - if (!(obj instanceof TaggedUnion)) { - return false; - } - - TaggedUnion other = (TaggedUnion) obj; - return Objects.equals(one, other.one) && Objects.equals(two, other.two); - } - } - private static class UnionTypeInfo extends TypeInformation> { private static final long serialVersionUID = 1L; diff --git a/flink-runtime/src/main/java/org/apache/flink/streaming/api/datastream/JoinedStreams.java b/flink-runtime/src/main/java/org/apache/flink/streaming/api/datastream/JoinedStreams.java --- a/flink-runtime/src/main/java/org/apache/flink/streaming/api/datastream/JoinedStreams.java +++ b/flink-runtime/src/main/java/org/apache/flink/streaming/api/datastream/JoinedStreams.java @@ -27,12 +27,12 @@ import org.apache.flink.api.common.typeinfo.TypeInformation; import org.apache.flink.api.java.functions.KeySelector; import org.apache.flink.api.java.typeutils.TypeExtractor; -import org.apache.flink.streaming.api.datastream.CoGroupedStreams.TaggedUnion; import org.apache.flink.streaming.api.windowing.assigners.WindowAssigner; import org.apache.flink.streaming.api.windowing.evictors.Evictor; import org.apache.flink.streaming.api.windowing.triggers.Trigger; import org.apache.flink.streaming.api.windowing.windows.Window; import org.apache.flink.util.Collector; +import org.apache.flink.util.TaggedUnion; import javax.annotation.Nullable; diff --git a/flink-runtime/src/main/java/org/apache/flink/streaming/api/operators/AbstractStreamOperator.java b/flink-runtime/src/main/java/org/apache/flink/streaming/api/operators/AbstractStreamOperator.java --- a/flink-runtime/src/main/java/org/apache/flink/streaming/api/operators/AbstractStreamOperator.java +++ b/flink-runtime/src/main/java/org/apache/flink/streaming/api/operators/AbstractStreamOperator.java @@ -542,7 +542,7 @@ protected S getOrCreateKeyedState( * @throws IllegalStateException Thrown, if the key/value state was already initialized. * @throws Exception Thrown, if the state backend cannot create the key/value state. */ - protected S getPartitionedState( + public S getPartitionedState( N namespace, TypeSerializer namespaceSerializer, StateDescriptor stateDescriptor)