|
| 1 | +/* |
| 2 | + * Licensed to the Apache Software Foundation (ASF) under one |
| 3 | + * or more contributor license agreements. See the NOTICE file |
| 4 | + * distributed with this work for additional information |
| 5 | + * regarding copyright ownership. The ASF licenses this file |
| 6 | + * to you under the Apache License, Version 2.0 (the |
| 7 | + * "License"); you may not use this file except in compliance |
| 8 | + * with the License. You may obtain a copy of the License at |
| 9 | + * |
| 10 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | + * |
| 12 | + * Unless required by applicable law or agreed to in writing, software |
| 13 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 14 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 15 | + * See the License for the specific language governing permissions and |
| 16 | + * limitations under the License. |
| 17 | + */ |
| 18 | +package org.apache.beam.runners.kafka.streams.translation; |
| 19 | + |
| 20 | +import java.util.ArrayList; |
| 21 | +import java.util.List; |
| 22 | +import org.apache.beam.sdk.coders.Coder; |
| 23 | +import org.apache.beam.sdk.coders.CoderException; |
| 24 | +import org.apache.beam.sdk.coders.IterableCoder; |
| 25 | +import org.apache.beam.sdk.transforms.windowing.BoundedWindow; |
| 26 | +import org.apache.beam.sdk.transforms.windowing.GlobalWindow; |
| 27 | +import org.apache.beam.sdk.util.CoderUtils; |
| 28 | +import org.apache.beam.sdk.values.KV; |
| 29 | +import org.apache.beam.sdk.values.WindowedValue; |
| 30 | +import org.apache.beam.sdk.values.WindowedValues; |
| 31 | +import org.apache.kafka.streams.processor.api.Processor; |
| 32 | +import org.apache.kafka.streams.processor.api.ProcessorContext; |
| 33 | +import org.apache.kafka.streams.processor.api.Record; |
| 34 | +import org.apache.kafka.streams.state.KeyValueIterator; |
| 35 | +import org.apache.kafka.streams.state.KeyValueStore; |
| 36 | +import org.checkerframework.checker.nullness.qual.Nullable; |
| 37 | +import org.joda.time.Instant; |
| 38 | + |
| 39 | +/** |
| 40 | + * Executes a {@code GroupByKey} (GlobalWindow, default trigger, no allowed lateness). |
| 41 | + * |
| 42 | + * <p>Records arrive on the repartition topic keyed by the encoded Beam key, so every value of a key |
| 43 | + * is co-located here. Each value is appended to a per-key buffer in a Kafka Streams state store. |
| 44 | + * Watermark reports are fed to a {@link WatermarkManager}; when the input watermark reaches {@link |
| 45 | + * BoundedWindow#TIMESTAMP_MAX_VALUE} (the end of the global window) every buffered key is emitted |
| 46 | + * once as {@code KV<K, Iterable<V>>} and the buffer cleared, then the watermark is forwarded |
| 47 | + * downstream. |
| 48 | + * |
| 49 | + * <p>Buffering whole value lists and re-encoding on each append is O(n^2) per key; fine for this |
| 50 | + * first GroupByKey, and replaced when this moves to runner-core {@code GroupAlsoByWindow}. |
| 51 | + */ |
| 52 | +class GroupByKeyProcessor |
| 53 | + implements Processor<byte[], KStreamsPayload<?>, byte[], KStreamsPayload<?>> { |
| 54 | + |
| 55 | + private final String stateStoreName; |
| 56 | + private final Coder<Object> keyCoder; |
| 57 | + private final IterableCoder<@Nullable Object> bufferCoder; |
| 58 | + |
| 59 | + private final WatermarkManager watermarkManager = new WatermarkManager(); |
| 60 | + private Instant lastForwardedWatermark = BoundedWindow.TIMESTAMP_MIN_VALUE; |
| 61 | + // The global window fires exactly once, when the watermark first reaches its end. Later watermark |
| 62 | + // reports (e.g. the same terminal watermark broadcast across repartition partitions) must not |
| 63 | + // re-fire. This flag is in-memory only; restart correctness comes from the state store plus |
| 64 | + // exactly-once-v2: the buffered values and consumer offsets are committed atomically, and the |
| 65 | + // store is empty once a key has fired, so a restart cannot double-emit. Persisting watermark |
| 66 | + // holds is part of the separate WatermarkManager persistence work, not this initial GroupByKey. |
| 67 | + private boolean fired = false; |
| 68 | + |
| 69 | + private @Nullable ProcessorContext<byte[], KStreamsPayload<?>> context; |
| 70 | + private @Nullable KeyValueStore<byte[], byte[]> store; |
| 71 | + |
| 72 | + GroupByKeyProcessor( |
| 73 | + String stateStoreName, Coder<Object> keyCoder, Coder<@Nullable Object> valueCoder) { |
| 74 | + this.stateStoreName = stateStoreName; |
| 75 | + this.keyCoder = keyCoder; |
| 76 | + this.bufferCoder = IterableCoder.of(valueCoder); |
| 77 | + } |
| 78 | + |
| 79 | + @Override |
| 80 | + public void init(ProcessorContext<byte[], KStreamsPayload<?>> context) { |
| 81 | + this.context = context; |
| 82 | + this.store = context.getStateStore(stateStoreName); |
| 83 | + } |
| 84 | + |
| 85 | + @Override |
| 86 | + public void process(Record<byte[], KStreamsPayload<?>> record) { |
| 87 | + KStreamsPayload<?> payload = record.value(); |
| 88 | + if (payload.isData()) { |
| 89 | + byte[] encodedKey = record.key(); |
| 90 | + Object element = payload.getData().getValue(); |
| 91 | + if (encodedKey == null || element == null) { |
| 92 | + throw new IllegalStateException("GroupByKey data record is missing its key or value"); |
| 93 | + } |
| 94 | + appendValue(encodedKey, element); |
| 95 | + return; |
| 96 | + } |
| 97 | + WatermarkPayload report = payload.asWatermark(); |
| 98 | + watermarkManager.observe( |
| 99 | + report.getSourcePartition(), |
| 100 | + new Instant(report.getWatermarkMillis()), |
| 101 | + report.getTotalSourcePartitions()); |
| 102 | + Instant advanced = watermarkManager.advance(); |
| 103 | + if (!fired && !advanced.isBefore(BoundedWindow.TIMESTAMP_MAX_VALUE)) { |
| 104 | + fireAll(record); |
| 105 | + fired = true; |
| 106 | + } |
| 107 | + if (advanced.isAfter(lastForwardedWatermark)) { |
| 108 | + lastForwardedWatermark = advanced; |
| 109 | + forwardWatermark(record, advanced.getMillis()); |
| 110 | + } |
| 111 | + } |
| 112 | + |
| 113 | + private void appendValue(byte[] encodedKey, Object kvObject) { |
| 114 | + KV<?, ?> kv = (KV<?, ?>) kvObject; |
| 115 | + KeyValueStore<byte[], byte[]> kvStore = checkInitialized(store); |
| 116 | + byte[] existing = kvStore.get(encodedKey); |
| 117 | + List<@Nullable Object> values = existing == null ? new ArrayList<>() : decodeBuffer(existing); |
| 118 | + values.add(kv.getValue()); |
| 119 | + kvStore.put(encodedKey, encodeBuffer(values)); |
| 120 | + } |
| 121 | + |
| 122 | + private void fireAll(Record<byte[], KStreamsPayload<?>> trigger) { |
| 123 | + // NOTE: this emits every buffered key in a single watermark turn. For a very large key space |
| 124 | + // that risks memory pressure and exceeding the poll / transaction timeout. Acceptable for this |
| 125 | + // initial GlobalWindow GroupByKey (fire once at end of input); incremental, timer-driven output |
| 126 | + // via runner-core GroupAlsoByWindow lands with the windowing/timers work. |
| 127 | + ProcessorContext<byte[], KStreamsPayload<?>> ctx = checkInitialized(context); |
| 128 | + KeyValueStore<byte[], byte[]> kvStore = checkInitialized(store); |
| 129 | + List<byte[]> firedKeys = new ArrayList<>(); |
| 130 | + try (KeyValueIterator<byte[], byte[]> it = kvStore.all()) { |
| 131 | + while (it.hasNext()) { |
| 132 | + org.apache.kafka.streams.KeyValue<byte[], byte[]> entry = it.next(); |
| 133 | + Object key = decodeKey(entry.key); |
| 134 | + List<@Nullable Object> values = decodeBuffer(entry.value); |
| 135 | + // The pane fires at the end of the global window, so the grouped element carries the |
| 136 | + // window's max timestamp (END_OF_GLOBAL_WINDOW). Emitting at TIMESTAMP_MIN_VALUE (the |
| 137 | + // default of valueInGlobalWindow) would make the output appear arbitrarily late and be |
| 138 | + // dropped downstream once the watermark has advanced. |
| 139 | + WindowedValue<KV<Object, Iterable<@Nullable Object>>> output = |
| 140 | + WindowedValues.timestampedValueInGlobalWindow( |
| 141 | + KV.of(key, (Iterable<@Nullable Object>) values), |
| 142 | + GlobalWindow.INSTANCE.maxTimestamp()); |
| 143 | + ctx.forward( |
| 144 | + new Record<byte[], KStreamsPayload<?>>( |
| 145 | + entry.key, KStreamsPayload.data(output), trigger.timestamp())); |
| 146 | + firedKeys.add(entry.key); |
| 147 | + } |
| 148 | + } |
| 149 | + for (byte[] key : firedKeys) { |
| 150 | + kvStore.delete(key); |
| 151 | + } |
| 152 | + } |
| 153 | + |
| 154 | + private void forwardWatermark(Record<byte[], KStreamsPayload<?>> trigger, long watermarkMillis) { |
| 155 | + ProcessorContext<byte[], KStreamsPayload<?>> ctx = checkInitialized(context); |
| 156 | + // GroupByKey is a single logical source for the next stage; report it as partition 0 of 1. |
| 157 | + ctx.forward( |
| 158 | + new Record<byte[], KStreamsPayload<?>>( |
| 159 | + trigger.key(), KStreamsPayload.watermark(watermarkMillis, 0, 1), trigger.timestamp())); |
| 160 | + } |
| 161 | + |
| 162 | + private byte[] encodeBuffer(List<@Nullable Object> values) { |
| 163 | + try { |
| 164 | + return CoderUtils.encodeToByteArray(bufferCoder, values); |
| 165 | + } catch (CoderException e) { |
| 166 | + throw new RuntimeException("Failed to encode GroupByKey value buffer", e); |
| 167 | + } |
| 168 | + } |
| 169 | + |
| 170 | + private List<@Nullable Object> decodeBuffer(byte[] bytes) { |
| 171 | + try { |
| 172 | + List<@Nullable Object> values = new ArrayList<>(); |
| 173 | + for (@Nullable Object value : CoderUtils.decodeFromByteArray(bufferCoder, bytes)) { |
| 174 | + values.add(value); |
| 175 | + } |
| 176 | + return values; |
| 177 | + } catch (CoderException e) { |
| 178 | + throw new RuntimeException("Failed to decode GroupByKey value buffer", e); |
| 179 | + } |
| 180 | + } |
| 181 | + |
| 182 | + private Object decodeKey(byte[] bytes) { |
| 183 | + try { |
| 184 | + return CoderUtils.decodeFromByteArray(keyCoder, bytes); |
| 185 | + } catch (CoderException e) { |
| 186 | + throw new RuntimeException("Failed to decode GroupByKey key", e); |
| 187 | + } |
| 188 | + } |
| 189 | + |
| 190 | + private static <T> T checkInitialized(@Nullable T value) { |
| 191 | + if (value == null) { |
| 192 | + throw new IllegalStateException("GroupByKeyProcessor used before init()"); |
| 193 | + } |
| 194 | + return value; |
| 195 | + } |
| 196 | +} |
0 commit comments