Skip to content

Instantly share code, notes, and snippets.

@damondouglas
Last active February 21, 2024 23:08
Show Gist options
  • Save damondouglas/8bc283b9fb6e6d316d83487a7cfed64d to your computer and use it in GitHub Desktop.
Save damondouglas/8bc283b9fb6e6d316d83487a7cfed64d 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 StreamProcessTimerExample {
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.PROCESSING_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. We would expect PT1.nnn, PT2.nnn, and so on because we set the interval to be 1s. Every so often we see something like PT467.370S followed by PT469.121S but most of the time they are approximately 1s apart.

PT466.068S: 11256
PT467.370S: 11281
PT469.121S: 11306
PT470.373S: 11331
PT471.991S: 11356

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