-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathPublisher.java
More file actions
364 lines (316 loc) · 12.4 KB
/
Publisher.java
File metadata and controls
364 lines (316 loc) · 12.4 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
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
/*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* Licensed 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 com.google.cloud.pubsub;
import com.google.auth.Credentials;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.pubsub.v1.PubsubMessage;
import io.grpc.ManagedChannelBuilder;
import java.io.IOException;
import java.util.concurrent.ScheduledExecutorService;
import org.joda.time.Duration;
/**
* A Cloud Pub/Sub <a href="https://cloud.google.com/pubsub/docs/publisher">publisher</a>, that is
* associated with a specific topic at creation.
*
* <p>A {@link Publisher} provides built-in capabilities to automatically handle bundling of
* messages, controlling memory utilization, and retrying API calls on transient errors.
*
* <p>With customizable options that control:
*
* <ul>
* <li>Message bundling: such as number of messages or max bundle byte size.
* <li>Flow control: such as max outstanding messages and maximum outstanding bytes.
* <li>Retries: such as the maximum duration of retries for a failing bundle of messages.
* </ul>
*
* <p>If no credentials are provided, the {@link Publisher} will use application default credentials
* through {@link GoogleCredentials#getApplicationDefault}.
*
* <p>For example, a {@link Publisher} can be constructed and used to publish a list of messages as
* follows:
*
* <pre>
* Publisher publisher =
* Publisher.Builder.newBuilder(MY_TOPIC)
* .setMaxBundleDuration(new Duration(10 * 1000))
* .build();
* List<ListenableFuture<String>> results = new ArrayList<>();
*
* for (PubsubMessage messages : messagesToPublish) {
* results.add(publisher.publish(message));
* }
*
* Futures.addCallback(
* Futures.allAsList(results),
* new FutureCallback<List<String>>() {
* @Override
* public void onSuccess(List<String> messageIds) {
* // ... process the acknowledgement of publish ...
* }
* @Override
* public void onFailure(Throwable t) {
* // .. handle the failure ...
* }
* });
*
* // Ensure all the outstanding messages have been published before shutting down your process.
* publisher.shutdown();
* </pre>
*/
public interface Publisher {
String PUBSUB_API_ADDRESS = "pubsub.googleapis.com";
String PUBSUB_API_SCOPE = "https://www.googleapis.com/auth/pubsub";
// API limits.
int MAX_BUNDLE_MESSAGES = 1000;
int MAX_BUNDLE_BYTES = 10 * 1000 * 1000; // 10 megabytes (https://en.wikipedia.org/wiki/Megabyte)
// Meaningful defaults.
int DEFAULT_MAX_BUNDLE_MESSAGES = 100;
int DEFAULT_MAX_BUNDLE_BYTES = 1000; // 1 kB
Duration DEFAULT_MAX_BUNDLE_DURATION = new Duration(1); // 1ms
Duration DEFAULT_REQUEST_TIMEOUT = new Duration(10 * 1000); // 10 seconds
Duration MIN_SEND_BUNDLE_DURATION = new Duration(10 * 1000); // 10 seconds
Duration MIN_REQUEST_TIMEOUT = new Duration(10); // 10 milliseconds
/** Topic to which the publisher publishes to. */
String getTopic();
/**
* Schedules the publishing of a message. The publishing of the message may occur immediately or
* be delayed based on the publisher bundling options.
*
* <p>Depending on chosen flow control {@link #failOnFlowControlLimits option}, the returned
* future might immediately fail with a {@link CloudPubsubFlowControlException} or block the
* current thread until there are more resources available to publish.
*
* @param message the message to publish.
* @return the message ID wrapped in a future.
*/
ListenableFuture<String> publish(PubsubMessage message);
/** Maximum amount of time to wait until scheduling the publishing of messages. */
Duration getMaxBundleDuration();
/** Maximum number of bytes to bundle before publishing. */
long getMaxBundleBytes();
/** Maximum number of messages to bundle before publishing. */
long getMaxBundleMessages();
/**
* Maximum number of outstanding (i.e. pending to publish) messages before limits are enforced.
* See {@link #failOnFlowControlLimits()}.
*/
Optional<Integer> getMaxOutstandingMessages();
/**
* Maximum number of outstanding (i.e. pending to publish) bytes before limits are enforced. See
* {@link #failOnFlowControlLimits()}.
*/
Optional<Integer> getMaxOutstandingBytes();
/**
* Whether to block publish calls when reaching flow control limits (see {@link
* #getMaxOutstandingBytes()} & {@link #getMaxOutstandingMessages()}).
*
* <p>If set to false, a publish call will fail with either {@link
* MaxOutstandingBytesReachedException} or {@link MaxOutstandingMessagesReachedException}, as
* appropriate, when flow control limits are reached.
*/
boolean failOnFlowControlLimits();
/** Retrieves a snapshot of the publisher current {@link PublisherStats statistics}. */
PublisherStats getStats();
/**
* Schedules immediate publishing of any outstanding messages and waits until all are processed.
*
* <p>Sends remaining outstanding messages and prevents future calls to publish. This method
* should be invoked prior to deleting the {@link Publisher} object in order to ensure that no
* pending messages are lost.
*/
void shutdown();
/** A builder of {@link Publisher}s. */
final class Builder {
String topic;
// Bundling options
int maxBundleMessages;
int maxBundleBytes;
Duration maxBundleDuration;
// Client-side flow control options
Optional<Integer> maxOutstandingMessages;
Optional<Integer> maxOutstandingBytes;
boolean failOnFlowControlLimits;
// Send bundle deadline
Duration sendBundleDeadline;
// RPC options
Duration requestTimeout;
// Channels and credentials
Optional<Credentials> userCredentials;
Optional<ManagedChannelBuilder<? extends ManagedChannelBuilder<?>>> channelBuilder;
Optional<ScheduledExecutorService> executor;
/** Constructs a new {@link Builder} using the given topic. */
public static Builder newBuilder(String topic) {
return new Builder(topic);
}
Builder(String topic) {
this.topic = Preconditions.checkNotNull(topic);
setDefaults();
}
private void setDefaults() {
userCredentials = Optional.absent();
channelBuilder = Optional.absent();
maxOutstandingMessages = Optional.absent();
maxOutstandingBytes = Optional.absent();
maxBundleMessages = DEFAULT_MAX_BUNDLE_MESSAGES;
maxBundleBytes = DEFAULT_MAX_BUNDLE_BYTES;
maxBundleDuration = DEFAULT_MAX_BUNDLE_DURATION;
requestTimeout = DEFAULT_REQUEST_TIMEOUT;
sendBundleDeadline = MIN_SEND_BUNDLE_DURATION;
failOnFlowControlLimits = false;
executor = Optional.absent();
}
/**
* Credentials to authenticate with.
*
* <p>Must be properly scoped for accessing Cloud Pub/Sub APIs.
*/
public Builder setCredentials(Credentials userCredentials) {
this.userCredentials = Optional.of(Preconditions.checkNotNull(userCredentials));
return this;
}
/**
* ManagedChannelBuilder to use to create Channels.
*
* <p>Must point at Cloud Pub/Sub endpoint.
*/
public Builder setChannelBuilder(
ManagedChannelBuilder<? extends ManagedChannelBuilder<?>> channelBuilder) {
this.channelBuilder =
Optional.<ManagedChannelBuilder<? extends ManagedChannelBuilder<?>>>of(
Preconditions.checkNotNull(channelBuilder));
return this;
}
// Bundling options
/**
* Maximum number of messages to send per publish call.
*
* <p>It also sets a target to when to trigger a publish.
*/
public Builder setMaxBundleMessages(int messages) {
Preconditions.checkArgument(messages > 0);
maxBundleMessages = messages;
return this;
}
/**
* Maximum number of bytes to send per publish call.
*
* <p>It also sets a target to when to trigger a publish.
*
* <p>This will not be honored if a single message is published that exceeds this maximum.
*/
public Builder setMaxBundleBytes(int bytes) {
Preconditions.checkArgument(bytes > 0);
maxBundleBytes = bytes;
return this;
}
/**
* Time to wait, since the first message is kept in memory for bundling, before triggering a
* publish call.
*/
public Builder setMaxBundleDuration(Duration duration) {
Preconditions.checkArgument(duration.getMillis() >= 0);
maxBundleDuration = duration;
return this;
}
// Flow control options
/** Maximum number of outstanding messages to keep in memory before enforcing flow control. */
public Builder setMaxOutstandingMessages(int messages) {
Preconditions.checkArgument(messages > 0);
maxOutstandingMessages = Optional.of(messages);
return this;
}
/** Maximum number of outstanding messages to keep in memory before enforcing flow control. */
public Builder setMaxOutstandingBytes(int bytes) {
Preconditions.checkArgument(bytes > 0);
maxOutstandingBytes = Optional.of(bytes);
return this;
}
/**
* Whether to fail publish when reaching any of the flow control limits, with either a {@link
* MaxOutstandingBytesReachedException} or {@link MaxOutstandingMessagesReachedException} as
* appropriate.
*
* <p>If set to false, then publish operations will block the current thread until the
* outstanding requests go under the limits.
*/
public Builder setFailOnFlowControlLimits(boolean fail) {
failOnFlowControlLimits = fail;
return this;
}
/** Maximum time to attempt sending (and retrying) a bundle of messages before giving up. */
public Builder setSendBundleDeadline(Duration deadline) {
Preconditions.checkArgument(deadline.compareTo(MIN_SEND_BUNDLE_DURATION) >= 0);
sendBundleDeadline = deadline;
return this;
}
// Runtime options
/** Time to wait for a publish call to return from the server. */
public Builder setRequestTimeout(Duration timeout) {
Preconditions.checkArgument(timeout.compareTo(MIN_REQUEST_TIMEOUT) >= 0);
requestTimeout = timeout;
return this;
}
/** Gives the ability to set a custom executor to be used by the library. */
public Builder setExecutor(ScheduledExecutorService executor) {
this.executor = Optional.of(Preconditions.checkNotNull(executor));
return this;
}
public Publisher build() throws IOException {
return new PublisherImpl(this);
}
}
/** Base exception that signals a flow control state. */
abstract class CloudPubsubFlowControlException extends Exception {}
/**
* Returned as a future exception when client-side flow control is enforced based on the maximum
* number of outstanding in-memory messages.
*/
final class MaxOutstandingMessagesReachedException extends CloudPubsubFlowControlException {
private final int currentMaxMessages;
public MaxOutstandingMessagesReachedException(int currentMaxMessages) {
this.currentMaxMessages = currentMaxMessages;
}
public int getCurrentMaxBundleMessages() {
return currentMaxMessages;
}
@Override
public String toString() {
return String.format(
"The maximum number of bundle messages: %d have been reached.", currentMaxMessages);
}
}
/**
* Returned as a future exception when client-side flow control is enforced based on the maximum
* number of unacknowledged in-memory bytes.
*/
final class MaxOutstandingBytesReachedException extends CloudPubsubFlowControlException {
private final int currentMaxBytes;
public MaxOutstandingBytesReachedException(int currentMaxBytes) {
this.currentMaxBytes = currentMaxBytes;
}
public int getCurrentMaxBundleBytes() {
return currentMaxBytes;
}
@Override
public String toString() {
return String.format(
"The maximum number of bundle bytes: %d have been reached.", currentMaxBytes);
}
}
}