m-trieu commented on code in PR #32774:
URL: https://github.com/apache/beam/pull/32774#discussion_r1837626505


##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/windmill/client/ResettableThrowingStreamObserver.java:
##########
@@ -0,0 +1,158 @@
+/*
+ * 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.dataflow.worker.windmill.client;
+
+import java.util.function.Supplier;
+import javax.annotation.Nullable;
+import javax.annotation.concurrent.GuardedBy;
+import javax.annotation.concurrent.ThreadSafe;
+import 
org.apache.beam.runners.dataflow.worker.windmill.client.grpc.observers.StreamObserverCancelledException;
+import 
org.apache.beam.runners.dataflow.worker.windmill.client.grpc.observers.TerminatingStreamObserver;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.vendor.grpc.v1p60p1.io.grpc.stub.StreamObserver;
+import 
org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions;
+import org.slf4j.Logger;
+
+/**
+ * Request observer that allows resetting its internal delegate using the 
given {@link
+ * #streamObserverFactory}.
+ *
+ * @implNote {@link StreamObserver}s generated by {@link 
#streamObserverFactory} are expected to be
+ *     {@link ThreadSafe}. Has same methods declared in {@link 
StreamObserver}, but they throw
+ *     {@link StreamClosedException} and {@link 
WindmillStreamShutdownException}, which much be
+ *     handled by callers.
+ */
+@ThreadSafe
+@Internal
+final class ResettableThrowingStreamObserver<T> {
+  private final Supplier<TerminatingStreamObserver<T>> streamObserverFactory;
+  private final Logger logger;
+
+  @GuardedBy("this")
+  private @Nullable TerminatingStreamObserver<T> delegateStreamObserver;
+
+  @GuardedBy("this")
+  private boolean isPoisoned = false;
+
+  /**
+   * Indicates that the current delegate is closed via {@link #poison() or 
{@link #onCompleted()}}.
+   * If not poisoned, a call to {@link #reset()} is required to perform future 
operations on the
+   * StreamObserver.
+   */
+  @GuardedBy("this")
+  private boolean isCurrentStreamClosed = false;
+
+  ResettableThrowingStreamObserver(
+      Supplier<TerminatingStreamObserver<T>> streamObserverFactory, Logger 
logger) {
+    this.streamObserverFactory = streamObserverFactory;
+    this.logger = logger;
+    this.delegateStreamObserver = null;
+  }
+
+  private synchronized StreamObserver<T> delegate()
+      throws WindmillStreamShutdownException, StreamClosedException {
+    if (isPoisoned) {
+      throw new WindmillStreamShutdownException("Stream is already shutdown.");
+    }
+
+    if (isCurrentStreamClosed) {
+      throw new StreamClosedException(
+          "Current stream is closed, requires reset for future stream 
operations.");
+    }
+
+    return Preconditions.checkNotNull(
+        delegateStreamObserver,
+        "requestObserver cannot be null. Missing a call to startStream() to 
initialize.");
+  }
+
+  /** Creates a new delegate to use for future {@link StreamObserver} methods. 
*/
+  synchronized void reset() throws WindmillStreamShutdownException {
+    if (isPoisoned) {
+      throw new WindmillStreamShutdownException("Stream is already shutdown.");
+    }
+
+    delegateStreamObserver = streamObserverFactory.get();
+    isCurrentStreamClosed = false;
+  }
+
+  /**
+   * Indicates that the request observer should no longer be used. Attempts to 
perform operations on
+   * the request observer will throw an {@link 
WindmillStreamShutdownException}.
+   */
+  synchronized void poison() {
+    if (!isPoisoned) {
+      isPoisoned = true;
+      if (delegateStreamObserver != null) {
+        delegateStreamObserver.terminate(
+            new WindmillStreamShutdownException("Explicit call to shutdown 
stream."));
+        delegateStreamObserver = null;
+        isCurrentStreamClosed = true;
+      }
+    }
+  }
+
+  public void onNext(T t) throws StreamClosedException, 
WindmillStreamShutdownException {
+    // Make sure onNext and onError below to be called on the same 
StreamObserver instance.
+    StreamObserver<T> delegate = delegate();
+    try {
+      // Do NOT lock while sending message over the stream as this will block 
other StreamObserver
+      // operations.
+      delegate.onNext(t);
+    } catch (StreamObserverCancelledException e) {
+      synchronized (this) {
+        if (isPoisoned) {
+          logger.debug("Stream was shutdown during send.", e);
+          return;
+        }
+      }
+
+      try {
+        delegate.onError(e);
+      } catch (RuntimeException ignored) {
+        // If the delegate above was already terminated via onError or 
onComplete from another
+        // thread.
+        logger.warn("StreamObserver was previously cancelled.", e);
+      }
+    }
+  }
+
+  public void onError(Throwable throwable)
+      throws StreamClosedException, WindmillStreamShutdownException {
+    delegate().onError(throwable);
+  }
+
+  public synchronized void onCompleted()

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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to