/
SimpleSubscribeResponseHandler.java
277 lines (249 loc) · 12.2 KB
/
SimpleSubscribeResponseHandler.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
/**
* 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.hedwig.client.netty.impl.simple;
import java.net.InetSocketAddress;
import java.util.Set;
import java.util.Collections;
import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureListener;
import com.google.protobuf.ByteString;
import org.apache.hedwig.client.api.MessageHandler;
import org.apache.hedwig.client.conf.ClientConfiguration;
import org.apache.hedwig.client.data.PubSubData;
import org.apache.hedwig.client.data.TopicSubscriber;
import org.apache.hedwig.client.exceptions.AlreadyStartDeliveryException;
import org.apache.hedwig.client.handlers.SubscribeResponseHandler;
import org.apache.hedwig.client.netty.HChannel;
import org.apache.hedwig.client.netty.HChannelManager;
import org.apache.hedwig.client.netty.impl.AbstractHChannelManager;
import org.apache.hedwig.client.netty.impl.AbstractSubscribeResponseHandler;
import org.apache.hedwig.client.netty.impl.ActiveSubscriber;
import org.apache.hedwig.client.netty.impl.HChannelImpl;
import org.apache.hedwig.exceptions.PubSubException;
import org.apache.hedwig.exceptions.PubSubException.ClientNotSubscribedException;
import org.apache.hedwig.protocol.PubSubProtocol.Message;
import org.apache.hedwig.protocol.PubSubProtocol.PubSubResponse;
import org.apache.hedwig.protocol.PubSubProtocol.ResponseBody;
import org.apache.hedwig.protocol.PubSubProtocol.SubscriptionEvent;
import org.apache.hedwig.protocol.PubSubProtocol.SubscriptionPreferences;
import org.apache.hedwig.protocol.PubSubProtocol.StatusCode;
import org.apache.hedwig.protoextensions.MessageIdUtils;
import org.apache.hedwig.util.Callback;
import org.apache.hedwig.util.Either;
public class SimpleSubscribeResponseHandler extends AbstractSubscribeResponseHandler {
private static Logger logger = LoggerFactory.getLogger(SimpleSubscribeResponseHandler.class);
/**
* Simple Active Subscriber enabling client-side throttling.
*/
static class SimpleActiveSubscriber extends ActiveSubscriber {
// Set to store all of the outstanding subscribed messages that are pending
// to be consumed by the client app's MessageHandler. If this ever grows too
// big (e.g. problem at the client end for message consumption), we can
// throttle things by temporarily setting the Subscribe Netty Channel
// to not be readable. When the Set has shrunk sufficiently, we can turn the
// channel back on to read new messages.
private final Set<Message> outstandingMsgSet;
public SimpleActiveSubscriber(ClientConfiguration cfg,
AbstractHChannelManager channelManager,
TopicSubscriber ts, PubSubData op,
SubscriptionPreferences preferences,
Channel channel,
HChannel hChannel) {
super(cfg, channelManager, ts, op, preferences, channel, hChannel);
outstandingMsgSet = Collections.newSetFromMap(
new ConcurrentHashMap<Message, Boolean>(
cfg.getMaximumOutstandingMessages(), 1.0f));
}
@Override
protected void unsafeDeliverMessage(Message message) {
// Add this "pending to be consumed" message to the outstandingMsgSet.
outstandingMsgSet.add(message);
// Check if we've exceeded the max size for the outstanding message set.
if (outstandingMsgSet.size() >= cfg.getMaximumOutstandingMessages() &&
channel.isReadable()) {
// Too many outstanding messages so throttle it by setting the Netty
// Channel to not be readable.
if (logger.isDebugEnabled()) {
logger.debug("Too many outstanding messages ({}) so throttling the subscribe netty Channel",
outstandingMsgSet.size());
}
channel.setReadable(false);
}
super.unsafeDeliverMessage(message);
}
@Override
public synchronized void messageConsumed(Message message) {
super.messageConsumed(message);
// Remove this consumed message from the outstanding Message Set.
outstandingMsgSet.remove(message);
// Check if we throttled message consumption previously when the
// outstanding message limit was reached. For now, only turn the
// delivery back on if there are no more outstanding messages to
// consume. We could make this a configurable parameter if needed.
if (!channel.isReadable() && outstandingMsgSet.size() == 0) {
if (logger.isDebugEnabled())
logger.debug("Message consumption has caught up so okay to turn off"
+ " throttling of messages on the subscribe channel for {}",
topicSubscriber);
channel.setReadable(true);
}
}
@Override
public synchronized void startDelivery(MessageHandler messageHandler)
throws AlreadyStartDeliveryException, ClientNotSubscribedException {
super.startDelivery(messageHandler);
// Now make the TopicSubscriber Channel readable (it is set to not be
// readable when the initial subscription is done). Note that this is an
// asynchronous call. If this fails (not likely), the futureListener
// will just log an error message for now.
ChannelFuture future = channel.setReadable(true);
future.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (!future.isSuccess()) {
logger.error("Unable to make subscriber Channel readable in startDelivery call for {}",
topicSubscriber);
}
}
});
}
@Override
public synchronized void stopDelivery() {
super.stopDelivery();
// Now make the TopicSubscriber channel not-readable. This will buffer
// up messages if any are sent from the server. Note that this is an
// asynchronous call. If this fails (not likely), the futureListener
// will just log an error message for now.
ChannelFuture future = channel.setReadable(false);
future.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (!future.isSuccess()) {
logger.error("Unable to make subscriber Channel not readable in stopDelivery call for {}",
topicSubscriber);
}
}
});
}
}
// Track which subscriber is alive in this response handler
// Which is used for backward compat, since old version hub
// server doesn't carry (topic, subscriberid) in each message.
private volatile TopicSubscriber origTopicSubscriber;
private volatile ActiveSubscriber origActiveSubscriber;
private SimpleHChannelManager sChannelManager;
protected SimpleSubscribeResponseHandler(ClientConfiguration cfg,
HChannelManager channelManager) {
super(cfg, channelManager);
sChannelManager = (SimpleHChannelManager) channelManager;
}
@Override
protected ActiveSubscriber createActiveSubscriber(
ClientConfiguration cfg, AbstractHChannelManager channelManager,
TopicSubscriber ts, PubSubData op, SubscriptionPreferences preferences,
Channel channel, HChannel hChannel) {
return new SimpleActiveSubscriber(cfg, channelManager, ts, op, preferences, channel, hChannel);
}
@Override
protected synchronized ActiveSubscriber getActiveSubscriber(TopicSubscriber ts) {
if (null == origTopicSubscriber || !origTopicSubscriber.equals(ts)) {
return null;
}
return origActiveSubscriber;
}
private synchronized ActiveSubscriber getActiveSubscriber() {
return origActiveSubscriber;
}
@Override
public synchronized boolean hasSubscription(TopicSubscriber ts) {
if (null == origTopicSubscriber) {
return false;
}
return origTopicSubscriber.equals(ts);
}
@Override
protected synchronized boolean removeSubscription(TopicSubscriber ts, ActiveSubscriber ss) {
if (null != origTopicSubscriber && !origTopicSubscriber.equals(ts)) {
return false;
}
origTopicSubscriber = null;
origActiveSubscriber = null;
return super.removeSubscription(ts, ss);
}
@Override
public void handleResponse(PubSubResponse response, PubSubData pubSubData,
Channel channel) throws Exception {
// If this was not a successful response to the Subscribe request, we
// won't be using the Netty Channel created so just close it.
if (!response.getStatusCode().equals(StatusCode.SUCCESS)) {
HChannelImpl.getHChannelHandlerFromChannel(channel).closeExplicitly();
channel.close();
}
super.handleResponse(response, pubSubData, channel);
}
@Override
public void handleSubscribeMessage(PubSubResponse response) {
Message message = response.getMessage();
ActiveSubscriber ss = getActiveSubscriber();
if (null == ss) {
logger.error("No Subscriber is alive receiving its message {}.",
MessageIdUtils.msgIdToReadableString(message.getMsgId()));
return;
}
ss.handleMessage(message);
}
@Override
protected Either<StatusCode, HChannel> handleSuccessResponse(
TopicSubscriber ts, PubSubData pubSubData, Channel channel) {
// Store the mapping for the TopicSubscriber to the Channel.
// This is so we can control the starting and stopping of
// message deliveries from the server on that Channel. Store
// this only on a successful ack response from the server.
Either<Boolean, HChannel> result =
sChannelManager.storeSubscriptionChannel(ts, pubSubData, channel);
if (result.left()) {
return Either.of(StatusCode.SUCCESS, result.right());
} else {
StatusCode code;
if (pubSubData.isResubscribeRequest()) {
code = StatusCode.RESUBSCRIBE_EXCEPTION;
} else {
code = StatusCode.CLIENT_ALREADY_SUBSCRIBED;
}
return Either.of(code, null);
}
}
@Override
protected synchronized void postHandleSuccessResponse(
TopicSubscriber ts, ActiveSubscriber as) {
origTopicSubscriber = ts;
origActiveSubscriber = as;
}
@Override
public void asyncCloseSubscription(final TopicSubscriber topicSubscriber,
final Callback<ResponseBody> callback,
final Object context) {
// nothing to do just clear status
// channel manager takes the responsibility to close the channel
callback.operationFinished(context, (ResponseBody)null);
}
}