/*
 * 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.sdk.fn.splittabledofn;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;

import java.util.concurrent.CountDownLatch;
import java.util.function.Consumer;
import org.apache.beam.sdk.transforms.splittabledofn.ManualWatermarkEstimator;
import org.apache.beam.sdk.transforms.splittabledofn.TimestampObservingWatermarkEstimator;
import org.apache.beam.sdk.transforms.splittabledofn.WatermarkEstimator;
import org.apache.beam.sdk.transforms.windowing.GlobalWindow;
import org.apache.beam.sdk.values.KV;
import org.joda.time.Instant;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** Tests for {@link WatermarkEstimators}. */
@RunWith(JUnit4.class)
public class WatermarkEstimatorsTest {

  @Test
  public void testThreadSafeWatermarkEstimator() throws Exception {
    Instant[] reference = new Instant[] {GlobalWindow.TIMESTAMP_MIN_VALUE};
    WatermarkEstimator<Instant> watermarkEstimator =
        new WatermarkEstimator<Instant>() {

          @Override
          public Instant currentWatermark() {
            return reference[0];
          }

          @Override
          public Instant getState() {
            return reference[0];
          }
        };
    testWatermarkEstimatorSnapshotsStateWithCompetingThread(
        watermarkEstimator, (instant) -> reference[0] = instant);
  }

  @Test
  public void testThreadSafeManualWatermarkEstimator() throws Exception {
    ManualWatermarkEstimator<Instant> watermarkEstimator =
        new org.apache.beam.sdk.transforms.splittabledofn.WatermarkEstimators.Manual(
            GlobalWindow.TIMESTAMP_MIN_VALUE);
    testWatermarkEstimatorSnapshotsStateWithCompetingThread(
        watermarkEstimator, watermarkEstimator::setWatermark);
  }

  @Test
  public void testThreadSafeTimestampObservingWatermarkEstimator() throws Exception {
    TimestampObservingWatermarkEstimator<Instant> watermarkEstimator =
        new org.apache.beam.sdk.transforms.splittabledofn.WatermarkEstimators
            .MonotonicallyIncreasing(GlobalWindow.TIMESTAMP_MIN_VALUE);
    testWatermarkEstimatorSnapshotsStateWithCompetingThread(
        watermarkEstimator, watermarkEstimator::observeTimestamp);
  }

  public <WatermarkEstimatorT extends WatermarkEstimator<Instant>>
      void testWatermarkEstimatorSnapshotsStateWithCompetingThread(
          WatermarkEstimatorT watermarkEstimator, Consumer<Instant> watermarkUpdater)
          throws Exception {
    CountDownLatch countDownLatch = new CountDownLatch(1);
    Thread t =
        new Thread(
            () -> {
              countDownLatch.countDown();
              for (int i = 0; i < 1000; ++i) {
                watermarkUpdater.accept(GlobalWindow.TIMESTAMP_MIN_VALUE.plus(i));
              }
            });
    t.start();

    WatermarkEstimators.WatermarkAndStateObserver<Instant> threadsafeWatermarkEstimator =
        WatermarkEstimators.threadSafe(watermarkEstimator);

    // Ensure the thread has started before we start fetching values.
    countDownLatch.await();
    Instant currentMinimum = GlobalWindow.TIMESTAMP_MIN_VALUE;
    for (int i = 0; i < 100; ++i) {
      KV<Instant, Instant> value = threadsafeWatermarkEstimator.getWatermarkAndState();
      // The watermark estimators that we use ensure that state == current watermark so test that
      // they are equal here
      assertEquals(value.getKey(), value.getValue());
      // Also ensure that the watermark is not declining and somehow we are getting an "old" read
      assertFalse(currentMinimum.isAfter(value.getKey()));
    }

    t.join(10000);
  }
}

@@ -1021,87 +1021,8 @@
 er;%0A
-import org.apache.beam.sdk.transforms.splittabledofn.ManualWatermarkEstimator;%0A
 impo
@@ -1509,17 +1509,16 @@
 sTest %7B%0A
-%0A
   @Test%0A
@@ -1757,16 +1757,95 @@
 ant%3E() %7B
+%0A          private Instant currentWatermark = GlobalWindow.TIMESTAMP_MIN_VALUE;
 %0A%0A      
@@ -1916,35 +1916,84 @@
         
-return reference%5B0%5D
+currentWatermark = reference%5B0%5D;%0A            return currentWatermark
 ;%0A      
@@ -2076,28 +2076,32 @@
  return 
-reference%5B0%5D
+currentWatermark
 ;%0A      
@@ -2178,32 +2178,63 @@
 Thread(%0A        
+WatermarkEstimators.threadSafe(
 watermarkEstimat
@@ -2235,16 +2235,17 @@
 stimator
+)
 , (insta
@@ -2317,22 +2317,34 @@
 readSafe
-Manual
+TimestampObserving
 Watermar
@@ -2379,22 +2379,16 @@
 n %7B%0A    
-Manual
 Watermar
@@ -2401,232 +2401,75 @@
 ator
-%3CInstant%3E watermarkEstimator =%0A        new org.apache.beam.sdk.transforms.splittabledofn.WatermarkEstimators.Manual(%0A            GlobalWindow.TIMESTAMP_MIN_VALUE);%0A    testWatermarkEstimatorSnapshotsStateWithCompetingThread(
+s.WatermarkAndStateObserver%3CInstant%3E threadsafeWatermarkEstimator =
 %0A   
@@ -2465,33 +2465,33 @@
 mator =%0A        
-w
+W
 atermarkEstimato
@@ -2495,215 +2495,26 @@
 ator
-, watermarkEstimator::setWatermark);%0A  %7D%0A%0A  @Test%0A  public void testThreadSafeTimestampObservingWatermarkEstimator() throws Exception %7B%0A    TimestampObservingWatermarkEstimator%3CInstant%3E watermarkEstimator =%0A
+s.threadSafe(%0A    
     
@@ -2599,16 +2599,20 @@
         
+ 
+   
 .Monoton
@@ -2661,16 +2661,17 @@
 N_VALUE)
+)
 ;%0A    te
@@ -2725,33 +2725,43 @@
 Thread(%0A        
-w
+threadsafeW
 atermarkEstimato
@@ -2762,18 +2762,76 @@
 timator,
- w
+%0A        ((TimestampObservingWatermarkEstimator) threadsafeW
 atermark
@@ -2839,16 +2839,17 @@
 stimator
+)
 ::observ
@@ -2914,32 +2914,59 @@
 termarkEstimator
+s.WatermarkAndStateObserver
 %3CInstant%3E%3E%0A     
@@ -3481,159 +3481,8 @@
 );%0A%0A
-    WatermarkEstimators.WatermarkAndStateObserver%3CInstant%3E threadsafeWatermarkEstimator =%0A        WatermarkEstimators.threadSafe(watermarkEstimator);%0A%0A
     
@@ -3709,27 +3709,17 @@
 value = 
-threadsafeW
+w
 atermark

Fix threading issue with WatermarkEstimatorsTest