|
| 1 | +/* |
| 2 | + * Copyright 2024 Google LLC |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package com.google.cloud.pubsublite.cloudpubsub.internal; |
| 18 | + |
| 19 | +import com.google.api.core.ApiFuture; |
| 20 | +import com.google.api.core.ApiFutures; |
| 21 | +import com.google.api.core.SettableApiFuture; |
| 22 | +import com.google.api.gax.rpc.StatusCode.Code; |
| 23 | +import com.google.cloud.pubsublite.MessageMetadata; |
| 24 | +import com.google.cloud.pubsublite.Offset; |
| 25 | +import com.google.cloud.pubsublite.Partition; |
| 26 | +import com.google.cloud.pubsublite.cloudpubsub.PublisherSettings; |
| 27 | +import com.google.cloud.pubsublite.internal.CheckedApiException; |
| 28 | +import com.google.cloud.pubsublite.internal.ProxyService; |
| 29 | +import com.google.cloud.pubsublite.internal.Publisher; |
| 30 | +import com.google.cloud.pubsublite.proto.PubSubMessage; |
| 31 | +import java.util.ArrayList; |
| 32 | +import java.util.List; |
| 33 | +import java.util.concurrent.ConcurrentLinkedQueue; |
| 34 | +import org.apache.kafka.clients.producer.KafkaProducer; |
| 35 | +import org.apache.kafka.clients.producer.ProducerRecord; |
| 36 | +import org.apache.kafka.common.header.Header; |
| 37 | +import org.apache.kafka.common.header.internals.RecordHeader; |
| 38 | + |
| 39 | +/** Adapts a Kafka producer to the internal Publisher interface for a specific partition. */ |
| 40 | +public class KafkaPartitionPublisher extends ProxyService implements Publisher<MessageMetadata> { |
| 41 | + |
| 42 | + private final KafkaProducer<byte[], byte[]> producer; |
| 43 | + private final String topicName; |
| 44 | + private final Partition partition; |
| 45 | + private final PublisherSettings settings; |
| 46 | + private final ConcurrentLinkedQueue<SettableApiFuture<MessageMetadata>> pendingFutures; |
| 47 | + |
| 48 | + public KafkaPartitionPublisher( |
| 49 | + KafkaProducer<byte[], byte[]> producer, |
| 50 | + String topicName, |
| 51 | + Partition partition, |
| 52 | + PublisherSettings settings) { |
| 53 | + this.producer = producer; |
| 54 | + this.topicName = topicName; |
| 55 | + this.partition = partition; |
| 56 | + this.settings = settings; |
| 57 | + this.pendingFutures = new ConcurrentLinkedQueue<>(); |
| 58 | + } |
| 59 | + |
| 60 | + @Override |
| 61 | + public ApiFuture<MessageMetadata> publish(PubSubMessage message) { |
| 62 | + if (state() == State.FAILED) { |
| 63 | + return ApiFutures.immediateFailedFuture( |
| 64 | + new CheckedApiException("Publisher has failed", Code.FAILED_PRECONDITION).underlying); |
| 65 | + } |
| 66 | + |
| 67 | + try { |
| 68 | + // Convert to Kafka ProducerRecord |
| 69 | + ProducerRecord<byte[], byte[]> record = convertToKafkaRecord(message); |
| 70 | + |
| 71 | + // Create future for response |
| 72 | + SettableApiFuture<MessageMetadata> future = SettableApiFuture.create(); |
| 73 | + pendingFutures.add(future); |
| 74 | + |
| 75 | + // Send to Kafka |
| 76 | + producer.send( |
| 77 | + record, |
| 78 | + (metadata, exception) -> { |
| 79 | + pendingFutures.remove(future); |
| 80 | + |
| 81 | + if (exception != null) { |
| 82 | + CheckedApiException apiException = new CheckedApiException(exception, Code.INTERNAL); |
| 83 | + future.setException(apiException.underlying); |
| 84 | + |
| 85 | + // If this is a permanent error, fail the publisher |
| 86 | + if (isPermanentError(exception)) { |
| 87 | + onPermanentError(apiException); |
| 88 | + } |
| 89 | + } else { |
| 90 | + // Convert Kafka metadata to MessageMetadata |
| 91 | + MessageMetadata messageMetadata = |
| 92 | + MessageMetadata.of( |
| 93 | + Partition.of(metadata.partition()), Offset.of(metadata.offset())); |
| 94 | + future.set(messageMetadata); |
| 95 | + } |
| 96 | + }); |
| 97 | + |
| 98 | + return future; |
| 99 | + |
| 100 | + } catch (Exception e) { |
| 101 | + CheckedApiException apiException = new CheckedApiException(e, Code.INTERNAL); |
| 102 | + onPermanentError(apiException); |
| 103 | + return ApiFutures.immediateFailedFuture(apiException.underlying); |
| 104 | + } |
| 105 | + } |
| 106 | + |
| 107 | + @Override |
| 108 | + public void flush() { |
| 109 | + producer.flush(); |
| 110 | + } |
| 111 | + |
| 112 | + @Override |
| 113 | + public void cancelOutstandingPublishes() { |
| 114 | + CheckedApiException exception = |
| 115 | + new CheckedApiException("Publisher is shutting down", Code.CANCELLED); |
| 116 | + |
| 117 | + pendingFutures.forEach(future -> future.setException(exception.underlying)); |
| 118 | + pendingFutures.clear(); |
| 119 | + } |
| 120 | + |
| 121 | + // Note: doStart() and doStop() are handled by ProxyService |
| 122 | + |
| 123 | + private ProducerRecord<byte[], byte[]> convertToKafkaRecord(PubSubMessage message) { |
| 124 | + // Extract key - use ordering key if available |
| 125 | + byte[] key = message.getKey().isEmpty() ? null : message.getKey().toByteArray(); |
| 126 | + |
| 127 | + // Create record with explicit partition |
| 128 | + ProducerRecord<byte[], byte[]> record = |
| 129 | + new ProducerRecord<byte[], byte[]>( |
| 130 | + topicName, |
| 131 | + Integer.valueOf((int) partition.value()), // Use explicit partition |
| 132 | + key, |
| 133 | + message.getData().toByteArray()); |
| 134 | + |
| 135 | + // Convert attributes to headers |
| 136 | + List<Header> headers = new ArrayList<>(); |
| 137 | + message.getAttributesMap().forEach((k, v) -> headers.add(new RecordHeader(k, v.toByteArray()))); |
| 138 | + |
| 139 | + // Add event time as header if present |
| 140 | + if (message.hasEventTime()) { |
| 141 | + headers.add( |
| 142 | + new RecordHeader( |
| 143 | + "pubsublite.event_time", |
| 144 | + String.valueOf(message.getEventTime().getSeconds()).getBytes())); |
| 145 | + } |
| 146 | + |
| 147 | + headers.forEach(record.headers()::add); |
| 148 | + |
| 149 | + return record; |
| 150 | + } |
| 151 | + |
| 152 | + private boolean isPermanentError(Exception e) { |
| 153 | + // Determine if error is permanent and should fail the publisher |
| 154 | + String message = e.getMessage(); |
| 155 | + return message != null |
| 156 | + && (message.contains("InvalidTopicException") |
| 157 | + || message.contains("AuthorizationException") |
| 158 | + || message.contains("SecurityDisabledException")); |
| 159 | + } |
| 160 | +} |
0 commit comments