Skip to content

Instantly share code, notes, and snippets.

@damondouglas
Last active February 21, 2024 23:12
Show Gist options
  • Save damondouglas/e2ea7d0d50dc4453eb10108ed1929684 to your computer and use it in GitHub Desktop.
Save damondouglas/e2ea7d0d50dc4453eb10108ed1929684 to your computer and use it in GitHub Desktop.
/*
* 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 example;
import static org.apache.beam.sdk.util.Preconditions.checkStateNotNull;
import static org.apache.beam.sdk.values.TypeDescriptors.longs;
import java.util.ArrayList;
import java.util.List;
import org.apache.beam.sdk.Pipeline;
import org.apache.beam.sdk.coders.Coder;
import org.apache.beam.sdk.coders.ListCoder;
import org.apache.beam.sdk.coders.VarLongCoder;
import org.apache.beam.sdk.options.PipelineOptions;
import org.apache.beam.sdk.options.PipelineOptionsFactory;
import org.apache.beam.sdk.state.StateSpec;
import org.apache.beam.sdk.state.StateSpecs;
import org.apache.beam.sdk.state.TimeDomain;
import org.apache.beam.sdk.state.Timer;
import org.apache.beam.sdk.state.TimerSpec;
import org.apache.beam.sdk.state.TimerSpecs;
import org.apache.beam.sdk.state.ValueState;
import org.apache.beam.sdk.transforms.DoFn;
import org.apache.beam.sdk.transforms.MapElements;
import org.apache.beam.sdk.transforms.ParDo;
import org.apache.beam.sdk.transforms.PeriodicImpulse;
import org.apache.beam.sdk.transforms.WithKeys;
import org.apache.beam.sdk.transforms.WithTimestamps;
import org.apache.beam.sdk.transforms.windowing.GlobalWindow;
import org.apache.beam.sdk.values.KV;
import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.MoreObjects;
import org.joda.time.Duration;
import org.joda.time.Instant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class StreamEventTimerExample {
public static void main(String[] args) {
Instant start = Instant.now();
PipelineOptions options = PipelineOptionsFactory.fromArgs(args).withValidation().as(PipelineOptions.class);
Pipeline pipeline = Pipeline.create(options);
pipeline
.apply(PeriodicImpulse.create().withInterval(Duration.millis(25L)))
.apply(
MapElements.into(longs())
.via(instant -> checkStateNotNull(instant).getMillis() - start.getMillis()))
.apply(WithTimestamps.of(ignored -> GlobalWindow.INSTANCE.maxTimestamp()))
.apply(WithKeys.of(0L))
.apply(useEventTimeAsTimer(VarLongCoder.of(), Duration.standardSeconds(1L)))
.apply(Log.of());
pipeline.run();
}
private static <T> ParDo.SingleOutput<KV<Long, T>, T> useEventTimeAsTimer(
Coder<T> coder, Duration interval) {
return ParDo.of(new UseEventTimeAsTimerFn<>(coder, interval));
}
private static class UseEventTimeAsTimerFn<T> extends DoFn<KV<Long, T>, T> {
private static final String TIMER_ID = "timerId";
private static final String QUEUE_ID = "queue";
private static final String RECORDED_TIMER_TIMESTAMP_ID = "recordedTimerTimestamp";
@TimerId(TIMER_ID)
private final TimerSpec timerSpec = TimerSpecs.timer(TimeDomain.EVENT_TIME);
@StateId(QUEUE_ID)
private final StateSpec<ValueState<List<T>>> queueStateSpec;
@StateId(RECORDED_TIMER_TIMESTAMP_ID)
private final StateSpec<ValueState<Long>> recordedTimerTimestampStateSpec = StateSpecs.value();
private final Duration interval;
private UseEventTimeAsTimerFn(Coder<T> coder, Duration interval) {
queueStateSpec = StateSpecs.value(ListCoder.of(coder));
this.interval = interval;
}
@ProcessElement
public void process(
@Element KV<Long, T> element,
@Timestamp Instant elementTimestamp,
@StateId(QUEUE_ID) ValueState<List<T>> queueState,
@TimerId(TIMER_ID) Timer timer,
@StateId(RECORDED_TIMER_TIMESTAMP_ID) ValueState<Long> recordedTimerTimestampState) {
List<T> queue = MoreObjects.firstNonNull(queueState.read(), new ArrayList<>());
queue.add(element.getValue());
queueState.write(queue);
if (recordedTimerTimestampState.read() == null) {
timer.offset(interval).setRelative();
recordedTimerTimestampState.write(timer.getCurrentRelativeTime().getMillis());
}
}
@OnTimer(TIMER_ID)
public void onTimer(
@TimerId(TIMER_ID) Timer timer,
@StateId(QUEUE_ID) ValueState<List<T>> queueState,
@StateId(RECORDED_TIMER_TIMESTAMP_ID) ValueState<Long> recordedTimerTimestampState,
OutputReceiver<T> receiver) {
List<T> queue = MoreObjects.firstNonNull(queueState.read(), new ArrayList<>());
if (queue.isEmpty()) {
timer.clear();
return;
}
receiver.output(queue.remove(0));
queueState.write(queue);
if (queue.isEmpty()) {
return;
}
timer.offset(interval).setRelative();
recordedTimerTimestampState.write(timer.getCurrentRelativeTime().getMillis());
}
}
private static class Log {
private static final Logger LOG = LoggerFactory.getLogger(Log.class);
private static final Instant START = Instant.now();
static <T> ParDo.SingleOutput<T, T> of() {
return ParDo.of(new Log.Fn<>());
}
private static class Fn<T> extends DoFn<T, T> {
@ProcessElement
public void process(@Element T t, OutputReceiver<T> receiver) {
Duration elapsed = Duration.millis(Instant.now().getMillis() - START.getMillis());
LOG.info("{}: {}", elapsed, t);
receiver.output(t);
}
}
}
}
@damondouglas
Copy link
Author

Running this using local or Dataflow runner outputs the following (not all shown). The PTn.nnnS are the elapsed durations from the start of the pipeline. As expected, these elapsed durations are not as consistent as ProcessTime domain timers.

PT926.843S: 12465
PT929.045S: 12490

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment