-
Notifications
You must be signed in to change notification settings - Fork 59
/
RequestResponseChannel.java
263 lines (204 loc) · 9.73 KB
/
RequestResponseChannel.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
/*
* Copyright (c) Microsoft. All rights reserved.
* Licensed under the MIT license. See LICENSE file in the project root for full license information.
*/
package com.microsoft.azure.eventhubs.impl;
import com.microsoft.azure.eventhubs.EventHubException;
import org.apache.qpid.proton.Proton;
import org.apache.qpid.proton.amqp.UnsignedLong;
import org.apache.qpid.proton.amqp.messaging.Source;
import org.apache.qpid.proton.amqp.messaging.Target;
import org.apache.qpid.proton.amqp.transport.ErrorCondition;
import org.apache.qpid.proton.amqp.transport.ReceiverSettleMode;
import org.apache.qpid.proton.amqp.transport.SenderSettleMode;
import org.apache.qpid.proton.engine.*;
import org.apache.qpid.proton.message.Message;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
public class RequestResponseChannel implements IOObject {
private final Sender sendLink;
private final Receiver receiveLink;
private final String replyTo;
private final HashMap<Object, OperationResult<Message, Exception>> inflightRequests;
private final AtomicLong requestId;
private final AtomicInteger openRefCount;
private final AtomicInteger closeRefCount;
private OperationResult<Void, Exception> onOpen;
private OperationResult<Void, Exception> onClose; // handles closeLink due to failures
private OperationResult<Void, Exception> onGraceFullClose; // handles intentional close
public RequestResponseChannel(
final String linkName,
final String path,
final Session session) {
this.replyTo = path.replace("$", "") + "-client-reply-to";
this.openRefCount = new AtomicInteger(2);
this.closeRefCount = new AtomicInteger(2);
this.inflightRequests = new HashMap<>();
this.requestId = new AtomicLong(0);
this.sendLink = session.sender(linkName + ":sender");
final Target target = new Target();
target.setAddress(path);
this.sendLink.setTarget(target);
sendLink.setSource(new Source());
this.sendLink.setSenderSettleMode(SenderSettleMode.SETTLED);
BaseHandler.setHandler(this.sendLink, new SendLinkHandler(new RequestHandler(), linkName));
this.receiveLink = session.receiver(linkName + ":receiver");
final Source source = new Source();
source.setAddress(path);
this.receiveLink.setSource(source);
final Target receiverTarget = new Target();
receiverTarget.setAddress(this.replyTo);
this.receiveLink.setTarget(receiverTarget);
this.receiveLink.setSenderSettleMode(SenderSettleMode.SETTLED);
this.receiveLink.setReceiverSettleMode(ReceiverSettleMode.SECOND);
BaseHandler.setHandler(this.receiveLink, new ReceiveLinkHandler(new ResponseHandler(), linkName));
}
// open should be called only once - we use FaultTolerantObject for that
public void open(final OperationResult<Void, Exception> onOpen, final OperationResult<Void, Exception> onClose) {
this.onOpen = onOpen;
this.onClose = onClose;
this.sendLink.open();
this.receiveLink.open();
}
// close should be called exactly once - we use FaultTolerantObject for that
public void close(final OperationResult<Void, Exception> onGraceFullClose) {
this.onGraceFullClose = onGraceFullClose;
this.sendLink.close();
this.receiveLink.close();
}
public Sender getSendLink() {
return this.sendLink;
}
public Receiver getReceiveLink() {
return this.receiveLink;
}
// not thread-safe
// this must be invoked from reactor/dispatcher thread
// & assumes that this is run on Opened Object
public void request(
final Message message,
final OperationResult<Message, Exception> onResponse) {
if (message == null)
throw new IllegalArgumentException("message cannot be null");
if (message.getMessageId() != null)
throw new IllegalArgumentException("message.getMessageId() should be null");
if (message.getReplyTo() != null)
throw new IllegalArgumentException("message.getReplyTo() should be null");
message.setMessageId("request" + UnsignedLong.valueOf(this.requestId.incrementAndGet()).toString());
message.setReplyTo(this.replyTo);
this.inflightRequests.put(message.getMessageId(), onResponse);
sendLink.delivery(UUID.randomUUID().toString().replace("-", StringUtil.EMPTY).getBytes());
final int payloadSize = AmqpUtil.getDataSerializedSize(message) + 512; // need buffer for headers
final byte[] bytes = new byte[payloadSize];
final int encodedSize = message.encode(bytes, 0, payloadSize);
receiveLink.flow(1);
sendLink.send(bytes, 0, encodedSize);
sendLink.advance();
}
private void onLinkOpenComplete(final Exception exception) {
if (openRefCount.decrementAndGet() <= 0 && onOpen != null)
if (exception == null && this.sendLink.getRemoteState() == EndpointState.ACTIVE && this.receiveLink.getRemoteState() == EndpointState.ACTIVE)
onOpen.onComplete(null);
else {
if (exception != null)
onOpen.onError(exception);
else {
final ErrorCondition error = (this.sendLink.getRemoteCondition() != null && this.sendLink.getRemoteCondition().getCondition() != null)
? this.sendLink.getRemoteCondition()
: this.receiveLink.getRemoteCondition();
onOpen.onError(ExceptionUtil.toException(error));
}
}
}
private void onLinkCloseComplete(final Exception exception) {
if (closeRefCount.decrementAndGet() <= 0)
if (exception == null) {
onClose.onComplete(null);
if (onGraceFullClose != null)
onGraceFullClose.onComplete(null);
} else {
onClose.onError(exception);
if (onGraceFullClose != null)
onGraceFullClose.onError(exception);
}
}
@Override
public IOObjectState getState() {
if (sendLink.getLocalState() == EndpointState.UNINITIALIZED || receiveLink.getLocalState() == EndpointState.UNINITIALIZED
|| sendLink.getRemoteState() == EndpointState.UNINITIALIZED || receiveLink.getRemoteState() == EndpointState.UNINITIALIZED)
return IOObjectState.OPENING;
if (sendLink.getRemoteState() == EndpointState.ACTIVE && receiveLink.getRemoteState() == EndpointState.ACTIVE
&& sendLink.getLocalState() == EndpointState.ACTIVE && receiveLink.getRemoteState() == EndpointState.ACTIVE)
return IOObjectState.OPENED;
if (sendLink.getRemoteState() == EndpointState.CLOSED && receiveLink.getRemoteState() == EndpointState.CLOSED)
return IOObjectState.CLOSED;
return IOObjectState.CLOSING; // only left cases are if some are active and some are closed
}
private class RequestHandler implements AmqpSender {
@Override
public void onFlow(int creditIssued) {
}
@Override
public void onSendComplete(Delivery delivery) {
}
@Override
public void onOpenComplete(Exception completionException) {
onLinkOpenComplete(completionException);
}
@Override
public void onError(Exception exception) {
onLinkCloseComplete(exception);
}
@Override
public void onClose(ErrorCondition condition) {
if (condition == null || condition.getCondition() == null)
onLinkCloseComplete(null);
else
onError(ExceptionUtil.toException(condition));
}
}
private class ResponseHandler implements AmqpReceiver {
@Override
public void onReceiveComplete(Delivery delivery) {
final Message response = Proton.message();
final int msgSize = delivery.pending();
final byte[] buffer = new byte[msgSize];
final int read = receiveLink.recv(buffer, 0, msgSize);
response.decode(buffer, 0, read);
delivery.settle();
final OperationResult<Message, Exception> responseCallback = inflightRequests.remove(response.getCorrelationId());
if (responseCallback != null)
responseCallback.onComplete(response);
}
@Override
public void onOpenComplete(Exception completionException) {
onLinkOpenComplete(completionException);
}
@Override
public void onError(Exception exception) {
this.cancelPendingRequests(exception);
if (onClose != null)
onLinkCloseComplete(exception);
}
@Override
public void onClose(ErrorCondition condition) {
if (condition == null || condition.getCondition() == null) {
this.cancelPendingRequests(
new EventHubException(
ClientConstants.DEFAULT_IS_TRANSIENT,
"The underlying request-response channel closed, recreate the channel and retry the request."));
if (onClose != null)
onLinkCloseComplete(null);
} else {
this.onError(ExceptionUtil.toException(condition));
}
}
private void cancelPendingRequests(final Exception exception) {
for (OperationResult<Message, Exception> responseCallback : inflightRequests.values())
responseCallback.onError(exception);
inflightRequests.clear();
}
}
}