-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
PubsubClient.java
448 lines (383 loc) · 15.6 KB
/
PubsubClient.java
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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
/*
* 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 org.apache.beam.sdk.io.gcp.pubsub;
import static org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Preconditions.checkArgument;
import static org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Preconditions.checkState;
import com.google.api.client.util.DateTime;
import com.google.auto.value.AutoValue;
import com.google.protobuf.ByteString;
import com.google.pubsub.v1.PubsubMessage;
import java.io.Closeable;
import java.io.IOException;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Objects;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Preconditions;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Splitter;
import org.checkerframework.checker.nullness.qual.Nullable;
/** An (abstract) helper class for talking to Pubsub via an underlying transport. */
@SuppressWarnings({
"nullness" // TODO(https://github.com/apache/beam/issues/20497)
})
public abstract class PubsubClient implements Closeable {
/** Factory for creating clients. */
public interface PubsubClientFactory extends Serializable {
/**
* Construct a new Pubsub client. It should be closed via {@link #close} in order to ensure tidy
* cleanup of underlying netty resources (or use the try-with-resources construct). Uses {@code
* options} to derive pubsub endpoints and application credentials. If non-{@literal null}, use
* {@code timestampAttribute} and {@code idAttribute} to store custom timestamps/ids within
* message metadata.
*/
PubsubClient newClient(
@Nullable String timestampAttribute,
@Nullable String idAttribute,
PubsubOptions options,
@Nullable String rootUrlOverride)
throws IOException;
PubsubClient newClient(
@Nullable String timestampAttribute, @Nullable String idAttribute, PubsubOptions options)
throws IOException;
/** Return the display name for this factory. Eg "Json", "gRPC". */
String getKind();
}
/**
* Return timestamp as ms-since-unix-epoch corresponding to {@code timestamp}. Throw {@link
* IllegalArgumentException} if timestamp cannot be recognized.
*/
protected static Long parseTimestampAsMsSinceEpoch(String timestamp) {
if (timestamp.isEmpty()) {
throw new IllegalArgumentException("Empty timestamp.");
}
try {
// Try parsing as milliseconds since epoch. Note there is no way to parse a
// string in RFC 3339 format here.
// Expected IllegalArgumentException if parsing fails; we use that to fall back
// to RFC 3339.
return Long.parseLong(timestamp);
} catch (IllegalArgumentException e1) {
// Try parsing as RFC3339 string. DateTime.parseRfc3339 will throw an
// IllegalArgumentException if parsing fails, and the caller should handle.
return DateTime.parseRfc3339(timestamp).getValue();
}
}
/**
* Return the timestamp (in ms since unix epoch) to use for a Pubsub message with {@code
* timestampAttribute} and {@code attriutes}.
*
* <p>The message attributes must contain {@code timestampAttribute}, and the value of that
* attribute will be taken as the timestamp.
*
* @throws IllegalArgumentException if the timestamp cannot be recognized as a ms-since-unix-epoch
* or RFC3339 time.
*/
protected static long extractTimestampAttribute(
String timestampAttribute, @Nullable Map<String, String> attributes) {
Preconditions.checkState(!timestampAttribute.isEmpty());
String value = attributes == null ? null : attributes.get(timestampAttribute);
checkArgument(
value != null,
"PubSub message is missing a value for timestamp attribute %s",
timestampAttribute);
Long timestampMsSinceEpoch = parseTimestampAsMsSinceEpoch(value);
checkArgument(
timestampMsSinceEpoch != null,
"Cannot interpret value of attribute %s as timestamp: %s",
timestampAttribute,
value);
return timestampMsSinceEpoch;
}
/** Path representing a cloud project id. */
public static class ProjectPath implements Serializable {
private final String projectId;
/**
* Creates a {@link ProjectPath} from a {@link String} representation, which must be of the form
* {@code "projects/" + projectId}.
*/
ProjectPath(String path) {
List<String> splits = Splitter.on('/').splitToList(path);
checkArgument(
splits.size() == 2 && "projects".equals(splits.get(0)),
"Malformed project path \"%s\": must be of the form \"projects/\" + <project id>",
path);
this.projectId = splits.get(1);
}
public String getPath() {
return String.format("projects/%s", projectId);
}
public String getId() {
return projectId;
}
@Override
public boolean equals(@Nullable Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ProjectPath that = (ProjectPath) o;
return projectId.equals(that.projectId);
}
@Override
public int hashCode() {
return projectId.hashCode();
}
@Override
public String toString() {
return getPath();
}
}
public static ProjectPath projectPathFromPath(String path) {
return new ProjectPath(path);
}
public static ProjectPath projectPathFromId(String projectId) {
return new ProjectPath(String.format("projects/%s", projectId));
}
/** Path representing a Pubsub subscription. */
public static class SubscriptionPath implements Serializable {
private final String projectId;
private final String subscriptionName;
SubscriptionPath(String path) {
List<String> splits = Splitter.on('/').splitToList(path);
checkState(
splits.size() == 4
&& "projects".equals(splits.get(0))
&& "subscriptions".equals(splits.get(2)),
"Malformed subscription path %s: "
+ "must be of the form \"projects/\" + <project id> + \"subscriptions\"",
path);
this.projectId = splits.get(1);
this.subscriptionName = splits.get(3);
}
public String getPath() {
return String.format("projects/%s/subscriptions/%s", projectId, subscriptionName);
}
public String getName() {
return subscriptionName;
}
public String getFullPath() {
return String.format("/subscriptions/%s/%s", projectId, subscriptionName);
}
@Override
public boolean equals(@Nullable Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SubscriptionPath that = (SubscriptionPath) o;
return this.subscriptionName.equals(that.subscriptionName)
&& this.projectId.equals(that.projectId);
}
@Override
public int hashCode() {
return Objects.hashCode(projectId, subscriptionName);
}
@Override
public String toString() {
return getPath();
}
}
public static SubscriptionPath subscriptionPathFromPath(String path) {
return new SubscriptionPath(path);
}
public static SubscriptionPath subscriptionPathFromName(
String projectId, String subscriptionName) {
return new SubscriptionPath(
String.format("projects/%s/subscriptions/%s", projectId, subscriptionName));
}
/** Path representing a Pubsub topic. */
public static class TopicPath implements Serializable {
private final String path;
TopicPath(String path) {
this.path = path;
}
public String getPath() {
return path;
}
public String getName() {
List<String> splits = Splitter.on('/').splitToList(path);
checkState(splits.size() == 4, "Malformed topic path %s", path);
return splits.get(3);
}
public String getFullPath() {
List<String> splits = Splitter.on('/').splitToList(path);
checkState(splits.size() == 4, "Malformed topic path %s", path);
return String.format("/topics/%s/%s", splits.get(1), splits.get(3));
}
@Override
public boolean equals(@Nullable Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
TopicPath topicPath = (TopicPath) o;
return path.equals(topicPath.path);
}
@Override
public int hashCode() {
return path.hashCode();
}
@Override
public String toString() {
return path;
}
}
public static TopicPath topicPathFromPath(String path) {
return new TopicPath(path);
}
public static TopicPath topicPathFromName(String projectId, String topicName) {
return new TopicPath(String.format("projects/%s/topics/%s", projectId, topicName));
}
/**
* A message to be sent to Pubsub.
*
* <p>NOTE: This class is {@link Serializable} only to support the {@link PubsubTestClient}. Java
* serialization is never used for non-test clients.
*/
@AutoValue
public abstract static class OutgoingMessage implements Serializable {
/** Underlying Message. May not have publish timestamp set. */
public abstract PubsubMessage message();
/** Timestamp for element (ms since epoch). */
public abstract long timestampMsSinceEpoch();
/**
* If using an id attribute, the record id to associate with this record's metadata so the
* receiver can reject duplicates. Otherwise {@literal null}.
*/
public abstract @Nullable String recordId();
public static OutgoingMessage of(
PubsubMessage message, long timestampMsSinceEpoch, @Nullable String recordId) {
return new AutoValue_PubsubClient_OutgoingMessage(message, timestampMsSinceEpoch, recordId);
}
public static OutgoingMessage of(
org.apache.beam.sdk.io.gcp.pubsub.PubsubMessage message,
long timestampMsSinceEpoch,
@Nullable String recordId) {
PubsubMessage.Builder builder =
PubsubMessage.newBuilder().setData(ByteString.copyFrom(message.getPayload()));
if (message.getAttributeMap() != null) {
builder.putAllAttributes(message.getAttributeMap());
}
if (message.getOrderingKey() != null) {
builder.setOrderingKey(message.getOrderingKey());
}
return of(builder.build(), timestampMsSinceEpoch, recordId);
}
}
/**
* A message received from Pubsub.
*
* <p>NOTE: This class is {@link Serializable} only to support the {@link PubsubTestClient}. Java
* serialization is never used for non-test clients.
*/
@AutoValue
abstract static class IncomingMessage implements Serializable {
/** Underlying Message. */
public abstract PubsubMessage message();
/**
* Timestamp for element (ms since epoch). Either Pubsub's processing time, or the custom
* timestamp associated with the message.
*/
public abstract long timestampMsSinceEpoch();
/** Timestamp (in system time) at which we requested the message (ms since epoch). */
public abstract long requestTimeMsSinceEpoch();
/** Id to pass back to Pubsub to acknowledge receipt of this message. */
public abstract String ackId();
/** Id to pass to the runner to distinguish this message from all others. */
public abstract String recordId();
public static IncomingMessage of(
PubsubMessage message,
long timestampMsSinceEpoch,
long requestTimeMsSinceEpoch,
String ackId,
String recordId) {
return new AutoValue_PubsubClient_IncomingMessage(
message, timestampMsSinceEpoch, requestTimeMsSinceEpoch, ackId, recordId);
}
}
/**
* Publish {@code outgoingMessages} to Pubsub {@code topic}. Return number of messages published.
*/
public abstract int publish(TopicPath topic, List<OutgoingMessage> outgoingMessages)
throws IOException;
/**
* Request the next batch of up to {@code batchSize} messages from {@code subscription}. Return
* the received messages, or empty collection if none were available. Does not wait for messages
* to arrive if {@code returnImmediately} is {@literal true}. Returned messages will record their
* request time as {@code requestTimeMsSinceEpoch}.
*/
public abstract List<IncomingMessage> pull(
long requestTimeMsSinceEpoch,
SubscriptionPath subscription,
int batchSize,
boolean returnImmediately)
throws IOException;
/** Acknowldege messages from {@code subscription} with {@code ackIds}. */
public abstract void acknowledge(SubscriptionPath subscription, List<String> ackIds)
throws IOException;
/**
* Modify the ack deadline for messages from {@code subscription} with {@code ackIds} to be {@code
* deadlineSeconds} from now.
*/
public abstract void modifyAckDeadline(
SubscriptionPath subscription, List<String> ackIds, int deadlineSeconds) throws IOException;
/** Create {@code topic}. */
public abstract void createTopic(TopicPath topic) throws IOException;
/*
* Delete {@code topic}.
*/
public abstract void deleteTopic(TopicPath topic) throws IOException;
/** Return a list of topics for {@code project}. */
public abstract List<TopicPath> listTopics(ProjectPath project) throws IOException;
/** Create {@code subscription} to {@code topic}. */
public abstract void createSubscription(
TopicPath topic, SubscriptionPath subscription, int ackDeadlineSeconds) throws IOException;
/**
* Create a random subscription for {@code topic}. Return the {@link SubscriptionPath}. It is the
* responsibility of the caller to later delete the subscription.
*/
public SubscriptionPath createRandomSubscription(
ProjectPath project, TopicPath topic, int ackDeadlineSeconds) throws IOException {
// Create a randomized subscription derived from the topic name.
String subscriptionName = topic.getName() + "_beam_" + ThreadLocalRandom.current().nextLong();
SubscriptionPath subscription =
PubsubClient.subscriptionPathFromName(project.getId(), subscriptionName);
createSubscription(topic, subscription, ackDeadlineSeconds);
return subscription;
}
/** Delete {@code subscription}. */
public abstract void deleteSubscription(SubscriptionPath subscription) throws IOException;
/** Return a list of subscriptions for {@code topic} in {@code project}. */
public abstract List<SubscriptionPath> listSubscriptions(ProjectPath project, TopicPath topic)
throws IOException;
/** Return the ack deadline, in seconds, for {@code subscription}. */
public abstract int ackDeadlineSeconds(SubscriptionPath subscription) throws IOException;
/**
* Return {@literal true} if {@link #pull} will always return empty list. Actual clients will
* return {@literal false}. Test clients may return {@literal true} to signal that all expected
* messages have been pulled and the test may complete.
*/
public abstract boolean isEOF();
}