You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@beam.apache.org by "robertwb (via GitHub)" <gi...@apache.org> on 2024/03/04 19:43:48 UTC

[PR] Add translator for Flink DataStreams. [beam]

robertwb opened a new pull request, #30486:
URL: https://github.com/apache/beam/pull/30486

   This shares what code is reasonable with the DataSet translation paths.
   
   Timestamp information is preserved, but windowing is not due to the differences in how these are expressed and propagated.
   
   ------------------------
   
   Thank you for your contribution! Follow this checklist to help us incorporate your contribution quickly and easily:
   
    - [ ] Mention the appropriate issue in your description (for example: `addresses #123`), if applicable. This will automatically add a link to the pull request in the issue. If you would like the issue to automatically close on merging the pull request, comment `fixes #<ISSUE NUMBER>` instead.
    - [ ] Update `CHANGES.md` with noteworthy changes.
    - [ ] If this contribution is large, please file an Apache [Individual Contributor License Agreement](https://www.apache.org/licenses/icla.pdf).
   
   See the [Contributor Guide](https://beam.apache.org/contribute) for more tips on [how to make review process smoother](https://github.com/apache/beam/blob/master/CONTRIBUTING.md#make-the-reviewers-job-easier).
   
   To check the build health, please visit [https://github.com/apache/beam/blob/master/.test-infra/BUILD_STATUS.md](https://github.com/apache/beam/blob/master/.test-infra/BUILD_STATUS.md)
   
   GitHub Actions Tests Status (on master branch)
   ------------------------------------------------------------------------------------------------
   [![Build python source distribution and wheels](https://github.com/apache/beam/workflows/Build%20python%20source%20distribution%20and%20wheels/badge.svg?branch=master&event=schedule)](https://github.com/apache/beam/actions?query=workflow%3A%22Build+python+source+distribution+and+wheels%22+branch%3Amaster+event%3Aschedule)
   [![Python tests](https://github.com/apache/beam/workflows/Python%20tests/badge.svg?branch=master&event=schedule)](https://github.com/apache/beam/actions?query=workflow%3A%22Python+Tests%22+branch%3Amaster+event%3Aschedule)
   [![Java tests](https://github.com/apache/beam/workflows/Java%20Tests/badge.svg?branch=master&event=schedule)](https://github.com/apache/beam/actions?query=workflow%3A%22Java+Tests%22+branch%3Amaster+event%3Aschedule)
   [![Go tests](https://github.com/apache/beam/workflows/Go%20tests/badge.svg?branch=master&event=schedule)](https://github.com/apache/beam/actions?query=workflow%3A%22Go+tests%22+branch%3Amaster+event%3Aschedule)
   
   See [CI.md](https://github.com/apache/beam/blob/master/CI.md) for more information about GitHub Actions CI or the [workflows README](https://github.com/apache/beam/blob/master/.github/workflows/README.md) to see a list of phrases to trigger workflows.
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add translator for Flink DataStreams. [beam]

Posted by "robertwb (via GitHub)" <gi...@apache.org>.
robertwb commented on code in PR #30486:
URL: https://github.com/apache/beam/pull/30486#discussion_r1511793836


##########
runners/flink/src/main/java/org/apache/beam/runners/flink/adapter/BeamFlinkDataStreamAdapter.java:
##########
@@ -0,0 +1,300 @@
+/*
+ * 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.beam.runners.flink.adapter;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.function.BiFunction;
+import java.util.function.Function;
+import org.apache.beam.model.pipeline.v1.RunnerApi;
+import org.apache.beam.runners.flink.FlinkPipelineOptions;
+import org.apache.beam.runners.flink.FlinkStreamingPortablePipelineTranslator;
+import org.apache.beam.runners.fnexecution.provisioning.JobInfo;
+import org.apache.beam.sdk.Pipeline;
+import org.apache.beam.sdk.coders.Coder;
+import org.apache.beam.sdk.coders.CoderRegistry;
+import org.apache.beam.sdk.options.PipelineOptions;
+import org.apache.beam.sdk.options.PipelineOptionsFactory;
+import org.apache.beam.sdk.transforms.PTransform;
+import org.apache.beam.sdk.transforms.windowing.BoundedWindow;
+import org.apache.beam.sdk.transforms.windowing.GlobalWindow;
+import org.apache.beam.sdk.util.Preconditions;
+import org.apache.beam.sdk.util.WindowedValue;
+import org.apache.beam.sdk.util.construction.PipelineOptionsTranslation;
+import org.apache.beam.sdk.values.PBegin;
+import org.apache.beam.sdk.values.PCollection;
+import org.apache.beam.sdk.values.PCollectionTuple;
+import org.apache.beam.sdk.values.PDone;
+import org.apache.beam.sdk.values.PInput;
+import org.apache.beam.sdk.values.POutput;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableMap;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Iterables;
+import org.apache.flink.api.common.eventtime.WatermarkStrategy;
+import org.apache.flink.streaming.api.datastream.DataStream;
+import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
+import org.apache.flink.streaming.api.functions.ProcessFunction;
+import org.apache.flink.streaming.api.operators.AbstractStreamOperator;
+import org.apache.flink.streaming.api.operators.OneInputStreamOperator;
+import org.apache.flink.streaming.runtime.streamrecord.StreamRecord;
+import org.apache.flink.util.Collector;
+import org.joda.time.Instant;
+
+/**
+ * An adapter class that allows one to apply Apache Beam PTransforms directly to Flink DataStreams.
+ */
+public class BeamFlinkDataStreamAdapter {
+  private final PipelineOptions pipelineOptions;
+  private final CoderRegistry coderRegistry = CoderRegistry.createDefault();
+
+  public BeamFlinkDataStreamAdapter() {
+    this(PipelineOptionsFactory.create());
+  }
+
+  public BeamFlinkDataStreamAdapter(PipelineOptions pipelineOptions) {
+    this.pipelineOptions = pipelineOptions;
+  }
+
+  @SuppressWarnings("nullness")

Review Comment:
   Yes, I'm updating this just as I did the other. 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add translator for Flink DataStreams. [beam]

Posted by "robertwb (via GitHub)" <gi...@apache.org>.
robertwb commented on code in PR #30486:
URL: https://github.com/apache/beam/pull/30486#discussion_r1511891400


##########
runners/flink/src/main/java/org/apache/beam/runners/flink/adapter/BeamFlinkDataStreamAdapter.java:
##########
@@ -0,0 +1,300 @@
+/*
+ * 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.beam.runners.flink.adapter;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.function.BiFunction;
+import java.util.function.Function;
+import org.apache.beam.model.pipeline.v1.RunnerApi;
+import org.apache.beam.runners.flink.FlinkPipelineOptions;
+import org.apache.beam.runners.flink.FlinkStreamingPortablePipelineTranslator;
+import org.apache.beam.runners.fnexecution.provisioning.JobInfo;
+import org.apache.beam.sdk.Pipeline;
+import org.apache.beam.sdk.coders.Coder;
+import org.apache.beam.sdk.coders.CoderRegistry;
+import org.apache.beam.sdk.options.PipelineOptions;
+import org.apache.beam.sdk.options.PipelineOptionsFactory;
+import org.apache.beam.sdk.transforms.PTransform;
+import org.apache.beam.sdk.transforms.windowing.BoundedWindow;
+import org.apache.beam.sdk.transforms.windowing.GlobalWindow;
+import org.apache.beam.sdk.util.Preconditions;
+import org.apache.beam.sdk.util.WindowedValue;
+import org.apache.beam.sdk.util.construction.PipelineOptionsTranslation;
+import org.apache.beam.sdk.values.PBegin;
+import org.apache.beam.sdk.values.PCollection;
+import org.apache.beam.sdk.values.PCollectionTuple;
+import org.apache.beam.sdk.values.PDone;
+import org.apache.beam.sdk.values.PInput;
+import org.apache.beam.sdk.values.POutput;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableMap;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Iterables;
+import org.apache.flink.api.common.eventtime.WatermarkStrategy;
+import org.apache.flink.streaming.api.datastream.DataStream;
+import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
+import org.apache.flink.streaming.api.functions.ProcessFunction;
+import org.apache.flink.streaming.api.operators.AbstractStreamOperator;
+import org.apache.flink.streaming.api.operators.OneInputStreamOperator;
+import org.apache.flink.streaming.runtime.streamrecord.StreamRecord;
+import org.apache.flink.util.Collector;
+import org.joda.time.Instant;
+
+/**
+ * An adapter class that allows one to apply Apache Beam PTransforms directly to Flink DataStreams.
+ */
+public class BeamFlinkDataStreamAdapter {
+  private final PipelineOptions pipelineOptions;
+  private final CoderRegistry coderRegistry = CoderRegistry.createDefault();
+
+  public BeamFlinkDataStreamAdapter() {
+    this(PipelineOptionsFactory.create());
+  }
+
+  public BeamFlinkDataStreamAdapter(PipelineOptions pipelineOptions) {
+    this.pipelineOptions = pipelineOptions;
+  }
+
+  @SuppressWarnings("nullness")

Review Comment:
   Pushed.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add translator for Flink DataStreams. [beam]

Posted by "kennknowles (via GitHub)" <gi...@apache.org>.
kennknowles commented on code in PR #30486:
URL: https://github.com/apache/beam/pull/30486#discussion_r1511729815


##########
runners/flink/src/main/java/org/apache/beam/runners/flink/adapter/BeamFlinkDataStreamAdapter.java:
##########
@@ -0,0 +1,300 @@
+/*
+ * 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.beam.runners.flink.adapter;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.function.BiFunction;
+import java.util.function.Function;
+import org.apache.beam.model.pipeline.v1.RunnerApi;
+import org.apache.beam.runners.flink.FlinkPipelineOptions;
+import org.apache.beam.runners.flink.FlinkStreamingPortablePipelineTranslator;
+import org.apache.beam.runners.fnexecution.provisioning.JobInfo;
+import org.apache.beam.sdk.Pipeline;
+import org.apache.beam.sdk.coders.Coder;
+import org.apache.beam.sdk.coders.CoderRegistry;
+import org.apache.beam.sdk.options.PipelineOptions;
+import org.apache.beam.sdk.options.PipelineOptionsFactory;
+import org.apache.beam.sdk.transforms.PTransform;
+import org.apache.beam.sdk.transforms.windowing.BoundedWindow;
+import org.apache.beam.sdk.transforms.windowing.GlobalWindow;
+import org.apache.beam.sdk.util.Preconditions;
+import org.apache.beam.sdk.util.WindowedValue;
+import org.apache.beam.sdk.util.construction.PipelineOptionsTranslation;
+import org.apache.beam.sdk.values.PBegin;
+import org.apache.beam.sdk.values.PCollection;
+import org.apache.beam.sdk.values.PCollectionTuple;
+import org.apache.beam.sdk.values.PDone;
+import org.apache.beam.sdk.values.PInput;
+import org.apache.beam.sdk.values.POutput;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableMap;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Iterables;
+import org.apache.flink.api.common.eventtime.WatermarkStrategy;
+import org.apache.flink.streaming.api.datastream.DataStream;
+import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
+import org.apache.flink.streaming.api.functions.ProcessFunction;
+import org.apache.flink.streaming.api.operators.AbstractStreamOperator;
+import org.apache.flink.streaming.api.operators.OneInputStreamOperator;
+import org.apache.flink.streaming.runtime.streamrecord.StreamRecord;
+import org.apache.flink.util.Collector;
+import org.joda.time.Instant;
+
+/**
+ * An adapter class that allows one to apply Apache Beam PTransforms directly to Flink DataStreams.
+ */
+public class BeamFlinkDataStreamAdapter {
+  private final PipelineOptions pipelineOptions;
+  private final CoderRegistry coderRegistry = CoderRegistry.createDefault();
+
+  public BeamFlinkDataStreamAdapter() {
+    this(PipelineOptionsFactory.create());
+  }
+
+  public BeamFlinkDataStreamAdapter(PipelineOptions pipelineOptions) {
+    this.pipelineOptions = pipelineOptions;
+  }
+
+  @SuppressWarnings("nullness")

Review Comment:
   Let's not do this with this PR, and ideally fix the prior. These at a minimum need a comment justifying it if you think it is unavoidable, or a specific GitHub Issue to fix them (but we shouldn't just introduce bugs or tech debt unless there is a compelling reason)



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add translator for Flink DataStreams. [beam]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #30486:
URL: https://github.com/apache/beam/pull/30486#issuecomment-1977334892

   Stopping reviewer notifications for this pull request: review requested by someone other than the bot, ceding control


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add translator for Flink DataStreams. [beam]

Posted by "kennknowles (via GitHub)" <gi...@apache.org>.
kennknowles commented on code in PR #30486:
URL: https://github.com/apache/beam/pull/30486#discussion_r1513191336


##########
runners/flink/src/main/java/org/apache/beam/runners/flink/adapter/BeamFlinkDataStreamAdapter.java:
##########
@@ -0,0 +1,302 @@
+/*
+ * 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.beam.runners.flink.adapter;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.function.BiFunction;
+import java.util.function.Function;
+import org.apache.beam.model.pipeline.v1.RunnerApi;
+import org.apache.beam.runners.flink.FlinkPipelineOptions;
+import org.apache.beam.runners.flink.FlinkStreamingPortablePipelineTranslator;
+import org.apache.beam.runners.fnexecution.provisioning.JobInfo;
+import org.apache.beam.sdk.Pipeline;
+import org.apache.beam.sdk.coders.Coder;
+import org.apache.beam.sdk.coders.CoderRegistry;
+import org.apache.beam.sdk.options.PipelineOptions;
+import org.apache.beam.sdk.options.PipelineOptionsFactory;
+import org.apache.beam.sdk.transforms.PTransform;
+import org.apache.beam.sdk.transforms.windowing.BoundedWindow;
+import org.apache.beam.sdk.transforms.windowing.GlobalWindow;
+import org.apache.beam.sdk.util.WindowedValue;
+import org.apache.beam.sdk.util.construction.PipelineOptionsTranslation;
+import org.apache.beam.sdk.values.PBegin;
+import org.apache.beam.sdk.values.PCollection;
+import org.apache.beam.sdk.values.PCollectionTuple;
+import org.apache.beam.sdk.values.PDone;
+import org.apache.beam.sdk.values.PInput;
+import org.apache.beam.sdk.values.POutput;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableMap;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Iterables;
+import org.apache.flink.api.common.eventtime.WatermarkStrategy;
+import org.apache.flink.streaming.api.datastream.DataStream;
+import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
+import org.apache.flink.streaming.api.functions.ProcessFunction;
+import org.apache.flink.streaming.api.operators.AbstractStreamOperator;
+import org.apache.flink.streaming.api.operators.OneInputStreamOperator;
+import org.apache.flink.streaming.runtime.streamrecord.StreamRecord;
+import org.apache.flink.util.Collector;
+import org.joda.time.Instant;
+
+/**
+ * An adapter class that allows one to apply Apache Beam PTransforms directly to Flink DataStreams.
+ */
+public class BeamFlinkDataStreamAdapter {
+  private final PipelineOptions pipelineOptions;
+  private final CoderRegistry coderRegistry = CoderRegistry.createDefault();
+
+  public BeamFlinkDataStreamAdapter() {
+    this(PipelineOptionsFactory.create());
+  }
+
+  public BeamFlinkDataStreamAdapter(PipelineOptions pipelineOptions) {
+    this.pipelineOptions = pipelineOptions;
+  }
+
+  public <InputT, OutputT, CollectionT extends PCollection<? extends InputT>>
+      DataStream<OutputT> applyBeamPTransform(
+          DataStream<InputT> input, PTransform<CollectionT, PCollection<OutputT>> transform) {
+    return (DataStream)
+        getNonNull(
+            applyBeamPTransformInternal(
+                ImmutableMap.of("input", input),
+                (pipeline, map) -> (CollectionT) getNonNull(map, "input"),
+                (output) -> ImmutableMap.of("output", output),
+                transform,
+                input.getExecutionEnvironment()),
+            "output");
+  }
+
+  public <OutputT> DataStream<OutputT> applyBeamPTransform(
+      Map<String, ? extends DataStream<?>> inputs,
+      PTransform<PCollectionTuple, PCollection<OutputT>> transform) {
+    return (DataStream)
+        getNonNull(
+            applyBeamPTransformInternal(
+                inputs,
+                BeamAdapterUtils::mapToTuple,
+                (output) -> ImmutableMap.of("output", output),
+                transform,
+                inputs.values().stream().findAny().get().getExecutionEnvironment()),
+            "output");
+  }
+
+  public <OutputT> DataStream<OutputT> applyBeamPTransform(
+      StreamExecutionEnvironment executionEnvironment,
+      PTransform<PBegin, PCollection<OutputT>> transform) {
+    return (DataStream)
+        getNonNull(
+            applyBeamPTransformInternal(
+                ImmutableMap.of(),
+                (pipeline, map) -> PBegin.in(pipeline),
+                (output) -> ImmutableMap.of("output", output),
+                transform,
+                executionEnvironment),
+            "output");
+  }
+
+  public <InputT, CollectionT extends PCollection<? extends InputT>>
+      Map<String, DataStream<?>> applyMultiOutputBeamPTransform(
+          DataStream<InputT> input, PTransform<CollectionT, PCollectionTuple> transform) {
+    return applyBeamPTransformInternal(
+        ImmutableMap.of("input", input),
+        (pipeline, map) -> (CollectionT) getNonNull(map, "input"),
+        BeamAdapterUtils::tupleToMap,
+        transform,
+        input.getExecutionEnvironment());
+  }
+
+  public Map<String, DataStream<?>> applyMultiOutputBeamPTransform(
+      Map<String, ? extends DataStream<?>> inputs,
+      PTransform<PCollectionTuple, PCollectionTuple> transform) {
+    return applyBeamPTransformInternal(
+        inputs,
+        BeamAdapterUtils::mapToTuple,
+        BeamAdapterUtils::tupleToMap,
+        transform,
+        inputs.values().stream().findAny().get().getExecutionEnvironment());
+  }
+
+  public Map<String, DataStream<?>> applyMultiOutputBeamPTransform(
+      StreamExecutionEnvironment executionEnvironment,
+      PTransform<PBegin, PCollectionTuple> transform) {
+    return applyBeamPTransformInternal(
+        ImmutableMap.of(),
+        (pipeline, map) -> PBegin.in(pipeline),
+        BeamAdapterUtils::tupleToMap,
+        transform,
+        executionEnvironment);
+  }
+
+  public <InputT, CollectionT extends PCollection<? extends InputT>>
+      void applyNoOutputBeamPTransform(
+          DataStream<InputT> input, PTransform<CollectionT, PDone> transform) {
+    applyBeamPTransformInternal(
+        ImmutableMap.of("input", input),
+        (pipeline, map) -> (CollectionT) getNonNull(map, "input"),
+        pDone -> ImmutableMap.of(),
+        transform,
+        input.getExecutionEnvironment());
+  }
+
+  public void applyNoOutputBeamPTransform(
+      Map<String, ? extends DataStream<?>> inputs, PTransform<PCollectionTuple, PDone> transform) {
+    applyBeamPTransformInternal(
+        inputs,
+        BeamAdapterUtils::mapToTuple,
+        pDone -> ImmutableMap.of(),
+        transform,
+        inputs.values().stream().findAny().get().getExecutionEnvironment());
+  }
+
+  public void applyNoOutputBeamPTransform(
+      StreamExecutionEnvironment executionEnvironment, PTransform<PBegin, PDone> transform) {
+    applyBeamPTransformInternal(
+        ImmutableMap.of(),
+        (pipeline, map) -> PBegin.in(pipeline),
+        pDone -> ImmutableMap.of(),
+        transform,
+        executionEnvironment);
+  }
+
+  private <BeamInputT extends PInput, BeamOutputT extends POutput>
+      Map<String, DataStream<?>> applyBeamPTransformInternal(
+          Map<String, ? extends DataStream<?>> inputs,
+          BiFunction<Pipeline, Map<String, PCollection<?>>, BeamInputT> toBeamInput,
+          Function<BeamOutputT, Map<String, PCollection<?>>> fromBeamOutput,
+          PTransform<? super BeamInputT, BeamOutputT> transform,
+          StreamExecutionEnvironment executionEnvironment) {
+    return BeamAdapterUtils.applyBeamPTransformInternal(
+        inputs,
+        toBeamInput,
+        fromBeamOutput,
+        transform,
+        executionEnvironment,
+        false,
+        dataStream -> dataStream.getType(),
+        pipelineOptions,
+        coderRegistry,
+        (inputs1, pipelineProto, executionEnvironment1) -> {
+          Map<String, DataStream<?>> outputs = new HashMap<>();
+          FlinkStreamingPortablePipelineTranslator translator =
+              new FlinkStreamingPortablePipelineTranslator(
+                  ImmutableMap.of(
+                      FlinkInput.URN, flinkInputTranslator(inputs1),
+                      FlinkOutput.URN, flinkOutputTranslator(outputs)));
+          FlinkStreamingPortablePipelineTranslator.StreamingTranslationContext context =
+              translator.createTranslationContext(
+                  JobInfo.create(
+                      "unusedJobId",
+                      "unusedJobName",
+                      "unusedRetrievalToken",
+                      PipelineOptionsTranslation.toProto(pipelineOptions)),
+                  pipelineOptions.as(FlinkPipelineOptions.class),
+                  executionEnvironment1);
+          translator.translate(context, translator.prepareForTranslation(pipelineProto));
+          return outputs;
+        });
+  }
+
+  private <InputT>
+      FlinkStreamingPortablePipelineTranslator.PTransformTranslator<
+              FlinkStreamingPortablePipelineTranslator.StreamingTranslationContext>
+          flinkInputTranslator(Map<String, ? extends DataStream<?>> inputMap) {
+    return (String id,
+        RunnerApi.Pipeline p,
+        FlinkStreamingPortablePipelineTranslator.StreamingTranslationContext context) -> {
+      // When we run into a FlinkInput operator, it "produces" the corresponding input as its
+      // "computed result."
+      RunnerApi.PTransform transform = p.getComponents().getTransformsOrThrow(id);
+      String inputId = transform.getSpec().getPayload().toStringUtf8();
+      DataStream<InputT> flinkInput =
+          Preconditions.checkNotNull((DataStream<InputT>) inputMap.get(inputId));
+      context.addDataStream(
+          Iterables.getOnlyElement(transform.getOutputsMap().values()),
+          flinkInput.process(
+              new ProcessFunction<InputT, WindowedValue<InputT>>() {
+                @Override
+                public void processElement(
+                    InputT value,
+                    ProcessFunction<InputT, WindowedValue<InputT>>.Context ctx,
+                    Collector<WindowedValue<InputT>> out)
+                    throws Exception {
+                  out.collect(
+                      WindowedValue.timestampedValueInGlobalWindow(
+                          value,
+                          ctx.timestamp() == null
+                              ? BoundedWindow.TIMESTAMP_MIN_VALUE
+                              : Instant.ofEpochMilli(ctx.timestamp())));
+                }
+              },
+              BeamAdapterCoderUtils.coderToTypeInformation(
+                  WindowedValue.getFullCoder(
+                      BeamAdapterCoderUtils.typeInformationToCoder(
+                          flinkInput.getType(), coderRegistry),
+                      GlobalWindow.Coder.INSTANCE),
+                  pipelineOptions)));
+    };
+  }
+
+  private <InputT>
+      FlinkStreamingPortablePipelineTranslator.PTransformTranslator<
+              FlinkStreamingPortablePipelineTranslator.StreamingTranslationContext>
+          flinkOutputTranslator(Map<String, DataStream<?>> outputMap) {
+    return (String id,
+        RunnerApi.Pipeline p,
+        FlinkStreamingPortablePipelineTranslator.StreamingTranslationContext context) -> {
+      // When we run into a FlinkOutput operator, we cache the computed PCollection to return to the
+      // user.
+      RunnerApi.PTransform transform = p.getComponents().getTransformsOrThrow(id);
+      DataStream<WindowedValue<InputT>> inputDataStream =
+          context.getDataStreamOrThrow(Iterables.getOnlyElement(transform.getInputsMap().values()));
+      String outputId = transform.getSpec().getPayload().toStringUtf8();
+      Coder<InputT> outputCoder =
+          BeamAdapterCoderUtils.lookupCoder(
+              p, Iterables.getOnlyElement(transform.getInputsMap().values()));
+      // TODO(robertwb): Also handle or disable length prefix coding (for embedded mode at least).
+      outputMap.put(
+          outputId,
+          inputDataStream.transform(
+              "StripWindows",
+              BeamAdapterCoderUtils.coderToTypeInformation(outputCoder, pipelineOptions),
+              new UnwrapWindowOperator<InputT>()));
+    };
+  }
+
+  /**
+   * Forwards the Beam timestamps to the underlying Flink timestamps, but unlike {@link
+   * DataStream#assignTimestampsAndWatermarks(WatermarkStrategy)} does not discard the underlying
+   * watermark signals.
+   *
+   * @param <T> user element type
+   */
+  private static class UnwrapWindowOperator<T> extends AbstractStreamOperator<T>
+      implements OneInputStreamOperator<WindowedValue<T>, T> {
+    @Override
+    public void processElement(StreamRecord<WindowedValue<T>> element) {
+      output.collect(
+          element.replace(
+              element.getValue().getValue(), element.getValue().getTimestamp().getMillis()));
+    }
+  }
+
+  private <K, V> V getNonNull(Map<K, V> map, K key) {
+    return Preconditions.checkNotNull(map.get(Preconditions.checkNotNull(key)));

Review Comment:
   You'll want to use Beam's `checkArgumentNotNull` or `checkStateNotNull` with an explicit error message to indicate the source of the problem. This one from Guava will throw an NPE again bringing users knocking on our door about it being an unreasonable crash with no debugging info.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add translator for Flink DataStreams. [beam]

Posted by "robertwb (via GitHub)" <gi...@apache.org>.
robertwb commented on PR #30486:
URL: https://github.com/apache/beam/pull/30486#issuecomment-1977332812

   R: @kennknowles 


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add translator for Flink DataStreams. [beam]

Posted by "robertwb (via GitHub)" <gi...@apache.org>.
robertwb commented on code in PR #30486:
URL: https://github.com/apache/beam/pull/30486#discussion_r1518383064


##########
runners/flink/src/main/java/org/apache/beam/runners/flink/adapter/BeamFlinkDataStreamAdapter.java:
##########
@@ -0,0 +1,302 @@
+/*
+ * 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.beam.runners.flink.adapter;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.function.BiFunction;
+import java.util.function.Function;
+import org.apache.beam.model.pipeline.v1.RunnerApi;
+import org.apache.beam.runners.flink.FlinkPipelineOptions;
+import org.apache.beam.runners.flink.FlinkStreamingPortablePipelineTranslator;
+import org.apache.beam.runners.fnexecution.provisioning.JobInfo;
+import org.apache.beam.sdk.Pipeline;
+import org.apache.beam.sdk.coders.Coder;
+import org.apache.beam.sdk.coders.CoderRegistry;
+import org.apache.beam.sdk.options.PipelineOptions;
+import org.apache.beam.sdk.options.PipelineOptionsFactory;
+import org.apache.beam.sdk.transforms.PTransform;
+import org.apache.beam.sdk.transforms.windowing.BoundedWindow;
+import org.apache.beam.sdk.transforms.windowing.GlobalWindow;
+import org.apache.beam.sdk.util.WindowedValue;
+import org.apache.beam.sdk.util.construction.PipelineOptionsTranslation;
+import org.apache.beam.sdk.values.PBegin;
+import org.apache.beam.sdk.values.PCollection;
+import org.apache.beam.sdk.values.PCollectionTuple;
+import org.apache.beam.sdk.values.PDone;
+import org.apache.beam.sdk.values.PInput;
+import org.apache.beam.sdk.values.POutput;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableMap;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Iterables;
+import org.apache.flink.api.common.eventtime.WatermarkStrategy;
+import org.apache.flink.streaming.api.datastream.DataStream;
+import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
+import org.apache.flink.streaming.api.functions.ProcessFunction;
+import org.apache.flink.streaming.api.operators.AbstractStreamOperator;
+import org.apache.flink.streaming.api.operators.OneInputStreamOperator;
+import org.apache.flink.streaming.runtime.streamrecord.StreamRecord;
+import org.apache.flink.util.Collector;
+import org.joda.time.Instant;
+
+/**
+ * An adapter class that allows one to apply Apache Beam PTransforms directly to Flink DataStreams.
+ */
+public class BeamFlinkDataStreamAdapter {
+  private final PipelineOptions pipelineOptions;
+  private final CoderRegistry coderRegistry = CoderRegistry.createDefault();
+
+  public BeamFlinkDataStreamAdapter() {
+    this(PipelineOptionsFactory.create());
+  }
+
+  public BeamFlinkDataStreamAdapter(PipelineOptions pipelineOptions) {
+    this.pipelineOptions = pipelineOptions;
+  }
+
+  public <InputT, OutputT, CollectionT extends PCollection<? extends InputT>>
+      DataStream<OutputT> applyBeamPTransform(
+          DataStream<InputT> input, PTransform<CollectionT, PCollection<OutputT>> transform) {
+    return (DataStream)
+        getNonNull(
+            applyBeamPTransformInternal(
+                ImmutableMap.of("input", input),
+                (pipeline, map) -> (CollectionT) getNonNull(map, "input"),
+                (output) -> ImmutableMap.of("output", output),
+                transform,
+                input.getExecutionEnvironment()),
+            "output");
+  }
+
+  public <OutputT> DataStream<OutputT> applyBeamPTransform(
+      Map<String, ? extends DataStream<?>> inputs,
+      PTransform<PCollectionTuple, PCollection<OutputT>> transform) {
+    return (DataStream)
+        getNonNull(
+            applyBeamPTransformInternal(
+                inputs,
+                BeamAdapterUtils::mapToTuple,
+                (output) -> ImmutableMap.of("output", output),
+                transform,
+                inputs.values().stream().findAny().get().getExecutionEnvironment()),
+            "output");
+  }
+
+  public <OutputT> DataStream<OutputT> applyBeamPTransform(
+      StreamExecutionEnvironment executionEnvironment,
+      PTransform<PBegin, PCollection<OutputT>> transform) {
+    return (DataStream)
+        getNonNull(
+            applyBeamPTransformInternal(
+                ImmutableMap.of(),
+                (pipeline, map) -> PBegin.in(pipeline),
+                (output) -> ImmutableMap.of("output", output),
+                transform,
+                executionEnvironment),
+            "output");
+  }
+
+  public <InputT, CollectionT extends PCollection<? extends InputT>>
+      Map<String, DataStream<?>> applyMultiOutputBeamPTransform(
+          DataStream<InputT> input, PTransform<CollectionT, PCollectionTuple> transform) {
+    return applyBeamPTransformInternal(
+        ImmutableMap.of("input", input),
+        (pipeline, map) -> (CollectionT) getNonNull(map, "input"),
+        BeamAdapterUtils::tupleToMap,
+        transform,
+        input.getExecutionEnvironment());
+  }
+
+  public Map<String, DataStream<?>> applyMultiOutputBeamPTransform(
+      Map<String, ? extends DataStream<?>> inputs,
+      PTransform<PCollectionTuple, PCollectionTuple> transform) {
+    return applyBeamPTransformInternal(
+        inputs,
+        BeamAdapterUtils::mapToTuple,
+        BeamAdapterUtils::tupleToMap,
+        transform,
+        inputs.values().stream().findAny().get().getExecutionEnvironment());
+  }
+
+  public Map<String, DataStream<?>> applyMultiOutputBeamPTransform(
+      StreamExecutionEnvironment executionEnvironment,
+      PTransform<PBegin, PCollectionTuple> transform) {
+    return applyBeamPTransformInternal(
+        ImmutableMap.of(),
+        (pipeline, map) -> PBegin.in(pipeline),
+        BeamAdapterUtils::tupleToMap,
+        transform,
+        executionEnvironment);
+  }
+
+  public <InputT, CollectionT extends PCollection<? extends InputT>>
+      void applyNoOutputBeamPTransform(
+          DataStream<InputT> input, PTransform<CollectionT, PDone> transform) {
+    applyBeamPTransformInternal(
+        ImmutableMap.of("input", input),
+        (pipeline, map) -> (CollectionT) getNonNull(map, "input"),
+        pDone -> ImmutableMap.of(),
+        transform,
+        input.getExecutionEnvironment());
+  }
+
+  public void applyNoOutputBeamPTransform(
+      Map<String, ? extends DataStream<?>> inputs, PTransform<PCollectionTuple, PDone> transform) {
+    applyBeamPTransformInternal(
+        inputs,
+        BeamAdapterUtils::mapToTuple,
+        pDone -> ImmutableMap.of(),
+        transform,
+        inputs.values().stream().findAny().get().getExecutionEnvironment());
+  }
+
+  public void applyNoOutputBeamPTransform(
+      StreamExecutionEnvironment executionEnvironment, PTransform<PBegin, PDone> transform) {
+    applyBeamPTransformInternal(
+        ImmutableMap.of(),
+        (pipeline, map) -> PBegin.in(pipeline),
+        pDone -> ImmutableMap.of(),
+        transform,
+        executionEnvironment);
+  }
+
+  private <BeamInputT extends PInput, BeamOutputT extends POutput>
+      Map<String, DataStream<?>> applyBeamPTransformInternal(
+          Map<String, ? extends DataStream<?>> inputs,
+          BiFunction<Pipeline, Map<String, PCollection<?>>, BeamInputT> toBeamInput,
+          Function<BeamOutputT, Map<String, PCollection<?>>> fromBeamOutput,
+          PTransform<? super BeamInputT, BeamOutputT> transform,
+          StreamExecutionEnvironment executionEnvironment) {
+    return BeamAdapterUtils.applyBeamPTransformInternal(
+        inputs,
+        toBeamInput,
+        fromBeamOutput,
+        transform,
+        executionEnvironment,
+        false,
+        dataStream -> dataStream.getType(),
+        pipelineOptions,
+        coderRegistry,
+        (inputs1, pipelineProto, executionEnvironment1) -> {
+          Map<String, DataStream<?>> outputs = new HashMap<>();
+          FlinkStreamingPortablePipelineTranslator translator =
+              new FlinkStreamingPortablePipelineTranslator(
+                  ImmutableMap.of(
+                      FlinkInput.URN, flinkInputTranslator(inputs1),
+                      FlinkOutput.URN, flinkOutputTranslator(outputs)));
+          FlinkStreamingPortablePipelineTranslator.StreamingTranslationContext context =
+              translator.createTranslationContext(
+                  JobInfo.create(
+                      "unusedJobId",
+                      "unusedJobName",
+                      "unusedRetrievalToken",
+                      PipelineOptionsTranslation.toProto(pipelineOptions)),
+                  pipelineOptions.as(FlinkPipelineOptions.class),
+                  executionEnvironment1);
+          translator.translate(context, translator.prepareForTranslation(pipelineProto));
+          return outputs;
+        });
+  }
+
+  private <InputT>
+      FlinkStreamingPortablePipelineTranslator.PTransformTranslator<
+              FlinkStreamingPortablePipelineTranslator.StreamingTranslationContext>
+          flinkInputTranslator(Map<String, ? extends DataStream<?>> inputMap) {
+    return (String id,
+        RunnerApi.Pipeline p,
+        FlinkStreamingPortablePipelineTranslator.StreamingTranslationContext context) -> {
+      // When we run into a FlinkInput operator, it "produces" the corresponding input as its
+      // "computed result."
+      RunnerApi.PTransform transform = p.getComponents().getTransformsOrThrow(id);
+      String inputId = transform.getSpec().getPayload().toStringUtf8();
+      DataStream<InputT> flinkInput =
+          Preconditions.checkNotNull((DataStream<InputT>) inputMap.get(inputId));
+      context.addDataStream(
+          Iterables.getOnlyElement(transform.getOutputsMap().values()),
+          flinkInput.process(
+              new ProcessFunction<InputT, WindowedValue<InputT>>() {
+                @Override
+                public void processElement(
+                    InputT value,
+                    ProcessFunction<InputT, WindowedValue<InputT>>.Context ctx,
+                    Collector<WindowedValue<InputT>> out)
+                    throws Exception {
+                  out.collect(
+                      WindowedValue.timestampedValueInGlobalWindow(
+                          value,
+                          ctx.timestamp() == null
+                              ? BoundedWindow.TIMESTAMP_MIN_VALUE
+                              : Instant.ofEpochMilli(ctx.timestamp())));
+                }
+              },
+              BeamAdapterCoderUtils.coderToTypeInformation(
+                  WindowedValue.getFullCoder(
+                      BeamAdapterCoderUtils.typeInformationToCoder(
+                          flinkInput.getType(), coderRegistry),
+                      GlobalWindow.Coder.INSTANCE),
+                  pipelineOptions)));
+    };
+  }
+
+  private <InputT>
+      FlinkStreamingPortablePipelineTranslator.PTransformTranslator<
+              FlinkStreamingPortablePipelineTranslator.StreamingTranslationContext>
+          flinkOutputTranslator(Map<String, DataStream<?>> outputMap) {
+    return (String id,
+        RunnerApi.Pipeline p,
+        FlinkStreamingPortablePipelineTranslator.StreamingTranslationContext context) -> {
+      // When we run into a FlinkOutput operator, we cache the computed PCollection to return to the
+      // user.
+      RunnerApi.PTransform transform = p.getComponents().getTransformsOrThrow(id);
+      DataStream<WindowedValue<InputT>> inputDataStream =
+          context.getDataStreamOrThrow(Iterables.getOnlyElement(transform.getInputsMap().values()));
+      String outputId = transform.getSpec().getPayload().toStringUtf8();
+      Coder<InputT> outputCoder =
+          BeamAdapterCoderUtils.lookupCoder(
+              p, Iterables.getOnlyElement(transform.getInputsMap().values()));
+      // TODO(robertwb): Also handle or disable length prefix coding (for embedded mode at least).
+      outputMap.put(
+          outputId,
+          inputDataStream.transform(
+              "StripWindows",
+              BeamAdapterCoderUtils.coderToTypeInformation(outputCoder, pipelineOptions),
+              new UnwrapWindowOperator<InputT>()));
+    };
+  }
+
+  /**
+   * Forwards the Beam timestamps to the underlying Flink timestamps, but unlike {@link
+   * DataStream#assignTimestampsAndWatermarks(WatermarkStrategy)} does not discard the underlying
+   * watermark signals.
+   *
+   * @param <T> user element type
+   */
+  private static class UnwrapWindowOperator<T> extends AbstractStreamOperator<T>
+      implements OneInputStreamOperator<WindowedValue<T>, T> {
+    @Override
+    public void processElement(StreamRecord<WindowedValue<T>> element) {
+      output.collect(
+          element.replace(
+              element.getValue().getValue(), element.getValue().getTimestamp().getMillis()));
+    }
+  }
+
+  private <K, V> V getNonNull(Map<K, V> map, K key) {
+    return Preconditions.checkNotNull(map.get(Preconditions.checkNotNull(key)));

Review Comment:
   Done.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add translator for Flink DataStreams. [beam]

Posted by "robertwb (via GitHub)" <gi...@apache.org>.
robertwb merged PR #30486:
URL: https://github.com/apache/beam/pull/30486


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org