-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTopicProducer.java
More file actions
326 lines (285 loc) · 12.1 KB
/
Copy pathTopicProducer.java
File metadata and controls
326 lines (285 loc) · 12.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
package com.danubemessaging.client.internal.producer;
import com.danubemessaging.client.ProducerOptions;
import com.danubemessaging.client.SchemaRegistryClient;
import com.danubemessaging.client.errors.DanubeClientException;
import com.danubemessaging.client.internal.auth.AuthService;
import com.danubemessaging.client.internal.connection.BrokerAddress;
import com.danubemessaging.client.internal.connection.ConnectionManager;
import com.danubemessaging.client.internal.health.HealthCheckService;
import com.danubemessaging.client.internal.lookup.LookupService;
import com.danubemessaging.client.internal.retry.RetryManager;
import com.danubemessaging.client.schema.SchemaInfo;
import com.danubemessaging.client.schema.SchemaReference;
import com.google.protobuf.ByteString;
import danube.DanubeApi;
import danube.ProducerServiceGrpc;
import io.grpc.Metadata;
import io.grpc.stub.MetadataUtils;
import java.net.URI;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
/**
* Producer bound to one concrete topic (or partition topic).
*/
public final class TopicProducer {
private enum LifecycleState {
NEW,
CREATED,
CLOSED
}
private final URI serviceUri;
private final ConnectionManager connectionManager;
private final LookupService lookupService;
private final AuthService authService;
private final HealthCheckService healthCheckService;
private final SchemaRegistryClient schemaRegistryClient;
private final RetryManager retryManager;
private final ProducerOptions options;
private final String topic;
private final String producerName;
private final AtomicLong requestId = new AtomicLong();
private final AtomicReference<LifecycleState> lifecycleState = new AtomicReference<>(LifecycleState.NEW);
private volatile BrokerAddress brokerAddress;
private volatile long producerId;
private volatile Long cachedSchemaId;
private volatile Integer cachedSchemaVersion;
private final AtomicBoolean stopSignal = new AtomicBoolean(false);
private volatile Thread healthCheckThread;
public TopicProducer(
URI serviceUri,
ConnectionManager connectionManager,
LookupService lookupService,
AuthService authService,
HealthCheckService healthCheckService,
SchemaRegistryClient schemaRegistryClient,
RetryManager retryManager,
ProducerOptions options,
String topic,
String producerName) {
this.serviceUri = serviceUri;
this.connectionManager = connectionManager;
this.lookupService = lookupService;
this.authService = authService;
this.healthCheckService = healthCheckService;
this.schemaRegistryClient = schemaRegistryClient;
this.retryManager = retryManager;
this.options = options;
this.topic = topic;
this.producerName = producerName;
}
public synchronized long create() {
ensureOpen();
if (lifecycleState.get() == LifecycleState.CREATED && producerId != 0) {
return producerId;
}
brokerAddress = lookupService.tryLookup(serviceUri, topic);
int attempts = 0;
while (true) {
try {
return tryCreate();
} catch (RuntimeException error) {
if (!retryManager.isRetryable(error)) {
throw error;
}
attempts++;
if (attempts > retryManager.maxRetries()) {
throw error;
}
brokerAddress = lookupService.tryLookup(serviceUri, topic);
sleepBackoff(retryManager.calculateBackoff(attempts - 1));
}
}
}
private long tryCreate() {
var connection = connectionManager.getConnection(brokerAddress.brokerUrl(), brokerAddress.connectUrl());
var stub = ProducerServiceGrpc.newBlockingStub(connection.grpcChannel());
stub = stub.withInterceptors(MetadataUtils.newAttachHeadersInterceptor(metadata()));
DanubeApi.ProducerRequest.Builder requestBuilder = DanubeApi.ProducerRequest.newBuilder()
.setRequestId(requestId.incrementAndGet())
.setProducerName(producerName)
.setTopicName(topic)
.setProducerAccessMode(options.accessMode().toProto())
.setDispatchStrategy(options.dispatchStrategy().toProto());
if (options.schemaReference() != null) {
requestBuilder.setSchemaRef(options.schemaReference().toProto());
}
DanubeApi.ProducerRequest request = requestBuilder.build();
try {
DanubeApi.ProducerResponse response = stub.createProducer(request);
producerId = response.getProducerId();
if (options.schemaReference() != null) {
resolveSchemaMetadata(options.schemaReference());
}
startBackgroundHealthCheck();
lifecycleState.set(LifecycleState.CREATED);
notifyProducerCreated(producerId);
return producerId;
} catch (Exception e) {
throw new DanubeClientException("Failed to create producer for topic: " + topic, e);
}
}
public long send(byte[] payload, Map<String, String> attributes, String routingKey) {
ensureOpen();
if (lifecycleState.get() != LifecycleState.CREATED || producerId == 0) {
create();
}
if (stopSignal.compareAndSet(true, false)) {
relookupAndCreate();
}
var connection = connectionManager.getConnection(brokerAddress.brokerUrl(), brokerAddress.connectUrl());
var stub = ProducerServiceGrpc.newBlockingStub(connection.grpcChannel());
stub = stub.withInterceptors(MetadataUtils.newAttachHeadersInterceptor(metadata()));
DanubeApi.MsgID msgId = DanubeApi.MsgID.newBuilder()
.setProducerId(producerId)
.setTopicName(topic)
.setBrokerAddr(brokerAddress.brokerUrl().toString())
.build();
DanubeApi.StreamMessage.Builder messageBuilder = DanubeApi.StreamMessage.newBuilder()
.setRequestId(requestId.incrementAndGet())
.setMsgId(msgId)
.setPayload(ByteString.copyFrom(payload))
.setPublishTime(System.currentTimeMillis())
.setProducerName(producerName)
.putAllAttributes(attributes);
if (cachedSchemaId != null) {
messageBuilder.setSchemaId(cachedSchemaId);
}
if (cachedSchemaVersion != null) {
messageBuilder.setSchemaVersion(cachedSchemaVersion);
}
if (routingKey != null) {
messageBuilder.setRoutingKey(routingKey);
}
DanubeApi.StreamMessage message = messageBuilder.build();
try {
DanubeApi.MessageResponse response = stub.sendMessage(message);
long sentRequestId = response.getRequestId();
notifyMessageSent(sentRequestId, payload.length, attributes.size());
return sentRequestId;
} catch (Exception e) {
throw new DanubeClientException("Failed to send message for topic: " + topic, e);
}
}
public String topic() {
return topic;
}
public String producerName() {
return producerName;
}
public synchronized void relookupAndCreate() {
ensureOpen();
cancelHealthCheckTask();
producerId = 0;
create();
}
public synchronized void close() {
if (lifecycleState.get() == LifecycleState.CLOSED) {
return;
}
cancelHealthCheckTask();
lifecycleState.set(LifecycleState.CLOSED);
producerId = 0;
notifyProducerClosed();
}
private void ensureOpen() {
if (lifecycleState.get() == LifecycleState.CLOSED) {
throw new DanubeClientException("Topic producer is closed: " + topic);
}
}
private void notifyProducerCreated(long id) {
try {
options.eventListener().onProducerCreated(topic, producerName, id);
} catch (RuntimeException ignore) {
// Listener errors must never break client flow.
}
}
private void notifyMessageSent(long requestIdValue, int payloadBytes, int attributeCount) {
try {
options.eventListener().onMessageSent(
topic,
producerName,
requestIdValue,
payloadBytes,
attributeCount);
} catch (RuntimeException ignore) {
// Listener errors must never break client flow.
}
}
private void notifyProducerClosed() {
try {
options.eventListener().onProducerClosed(topic, producerName);
} catch (RuntimeException ignore) {
// Listener errors must never break client flow.
}
}
private void resolveSchemaMetadata(SchemaReference schemaRef) {
if (schemaRegistryClient == null) {
throw new DanubeClientException(
"Schema reference is set but no schema registry client is available for topic: " + topic);
}
if (schemaRef.useLatest()) {
SchemaInfo latest = schemaRegistryClient.getLatestSchema(schemaRef.subject());
cachedSchemaId = latest.schemaId();
cachedSchemaVersion = latest.version();
} else if (schemaRef.pinnedVersion() != null) {
SchemaInfo latest = schemaRegistryClient.getLatestSchema(schemaRef.subject());
int pinned = schemaRef.pinnedVersion();
if (pinned > latest.version()) {
throw new DanubeClientException(
"Pinned version " + pinned + " does not exist for subject '" + schemaRef.subject()
+ "'. Latest version is " + latest.version());
}
if (pinned == latest.version()) {
cachedSchemaId = latest.schemaId();
cachedSchemaVersion = latest.version();
} else {
SchemaInfo pinnedSchema = schemaRegistryClient.getSchemaById(latest.schemaId(), pinned);
cachedSchemaId = pinnedSchema.schemaId();
cachedSchemaVersion = pinnedSchema.version();
}
} else if (schemaRef.minVersion() != null) {
SchemaInfo latest = schemaRegistryClient.getLatestSchema(schemaRef.subject());
int min = schemaRef.minVersion();
if (latest.version() < min) {
throw new DanubeClientException(
"Latest version " + latest.version() + " does not meet minimum version requirement "
+ min + " for subject '" + schemaRef.subject() + "'");
}
cachedSchemaId = latest.schemaId();
cachedSchemaVersion = latest.version();
}
}
private void startBackgroundHealthCheck() {
cancelHealthCheckTask();
stopSignal.set(false);
healthCheckThread = healthCheckService.startBackgroundHealthCheck(
serviceUri,
brokerAddress,
DanubeApi.HealthCheckRequest.ClientType.Producer,
producerId,
stopSignal);
}
private void cancelHealthCheckTask() {
Thread t = healthCheckThread;
if (t != null) {
t.interrupt();
healthCheckThread = null;
}
}
private Metadata metadata() {
Metadata metadata = new Metadata();
authService.insertTokenIfNeeded(metadata, serviceUri);
RetryManager.insertProxyHeader(metadata, brokerAddress.brokerUrl().toString(), brokerAddress.proxy());
return metadata;
}
private static void sleepBackoff(java.time.Duration backoff) {
try {
Thread.sleep(backoff);
} catch (InterruptedException interrupted) {
Thread.currentThread().interrupt();
throw new DanubeClientException("Interrupted while backing off for retry", interrupted);
}
}
}