-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
StreamResequencer.java
285 lines (251 loc) · 9.77 KB
/
StreamResequencer.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
/**
* 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.camel.processor;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.camel.AsyncCallback;
import org.apache.camel.AsyncProcessor;
import org.apache.camel.CamelContext;
import org.apache.camel.CamelExchangeException;
import org.apache.camel.Exchange;
import org.apache.camel.Navigate;
import org.apache.camel.Processor;
import org.apache.camel.Traceable;
import org.apache.camel.support.LoggingExceptionHandler;
import org.apache.camel.processor.resequencer.ResequencerEngine;
import org.apache.camel.processor.resequencer.SequenceElementComparator;
import org.apache.camel.processor.resequencer.SequenceSender;
import org.apache.camel.spi.ExceptionHandler;
import org.apache.camel.support.ServiceSupport;
import org.apache.camel.util.AsyncProcessorHelper;
import org.apache.camel.util.ObjectHelper;
import org.apache.camel.util.ServiceHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A resequencer that re-orders a (continuous) stream of {@link Exchange}s. The
* algorithm implemented by {@link ResequencerEngine} is based on the detection
* of gaps in a message stream rather than on a fixed batch size. Gap detection
* in combination with timeouts removes the constraint of having to know the
* number of messages of a sequence (i.e. the batch size) in advance.
* <p>
* Messages must contain a unique sequence number for which a predecessor and a
* successor is known. For example a message with the sequence number 3 has a
* predecessor message with the sequence number 2 and a successor message with
* the sequence number 4. The message sequence 2,3,5 has a gap because the
* successor of 3 is missing. The resequencer therefore has to retain message 5
* until message 4 arrives (or a timeout occurs).
* <p>
* Instances of this class poll for {@link Exchange}s from a given
* <code>endpoint</code>. Resequencing work and the delivery of messages to
* the next <code>processor</code> is done within the single polling thread.
*
* @version
*
* @see ResequencerEngine
*/
public class StreamResequencer extends ServiceSupport implements SequenceSender<Exchange>, AsyncProcessor, Navigate<Processor>, Traceable {
private static final long DELIVERY_ATTEMPT_INTERVAL = 1000L;
private static final Logger LOG = LoggerFactory.getLogger(StreamResequencer.class);
private final CamelContext camelContext;
private final ExceptionHandler exceptionHandler;
private final ResequencerEngine<Exchange> engine;
private final Processor processor;
private Delivery delivery;
private int capacity;
private boolean ignoreInvalidExchanges;
/**
* Creates a new {@link StreamResequencer} instance.
*
* @param processor next processor that processes re-ordered exchanges.
* @param comparator a sequence element comparator for exchanges.
*/
public StreamResequencer(CamelContext camelContext, Processor processor, SequenceElementComparator<Exchange> comparator) {
ObjectHelper.notNull(camelContext, "CamelContext");
this.camelContext = camelContext;
this.engine = new ResequencerEngine<Exchange>(comparator);
this.engine.setSequenceSender(this);
this.processor = processor;
this.exceptionHandler = new LoggingExceptionHandler(camelContext, getClass());
}
/**
* Returns this resequencer's exception handler.
*/
public ExceptionHandler getExceptionHandler() {
return exceptionHandler;
}
/**
* Returns the next processor.
*/
public Processor getProcessor() {
return processor;
}
/**
* Returns this resequencer's capacity. The capacity is the maximum number
* of exchanges that can be managed by this resequencer at a given point in
* time. If the capacity if reached, polling from the endpoint will be
* skipped for <code>timeout</code> milliseconds giving exchanges the
* possibility to time out and to be delivered after the waiting period.
*
* @return this resequencer's capacity.
*/
public int getCapacity() {
return capacity;
}
/**
* Returns this resequencer's timeout. This sets the resequencer engine's
* timeout via {@link ResequencerEngine#setTimeout(long)}. This value is
* also used to define the polling timeout from the endpoint.
*
* @return this resequencer's timeout. (Processor)
* @see ResequencerEngine#setTimeout(long)
*/
public long getTimeout() {
return engine.getTimeout();
}
public void setCapacity(int capacity) {
this.capacity = capacity;
}
public void setTimeout(long timeout) {
engine.setTimeout(timeout);
}
public boolean isIgnoreInvalidExchanges() {
return ignoreInvalidExchanges;
}
public void setRejectOld(Boolean rejectOld) {
engine.setRejectOld(rejectOld);
}
/**
* Sets whether to ignore invalid exchanges which cannot be used by this stream resequencer.
* <p/>
* Default is <tt>false</tt>, by which an {@link CamelExchangeException} is thrown if the {@link Exchange}
* is invalid.
*/
public void setIgnoreInvalidExchanges(boolean ignoreInvalidExchanges) {
this.ignoreInvalidExchanges = ignoreInvalidExchanges;
}
@Override
public String toString() {
return "StreamResequencer[to: " + processor + "]";
}
public String getTraceLabel() {
return "streamResequence";
}
@Override
protected void doStart() throws Exception {
ServiceHelper.startServices(processor);
delivery = new Delivery();
engine.start();
delivery.start();
}
@Override
protected void doStop() throws Exception {
// let's stop everything in the reverse order
// no need to stop the worker thread -- it will stop automatically when this service is stopped
engine.stop();
ServiceHelper.stopServices(processor);
}
/**
* Sends the <code>exchange</code> to the next <code>processor</code>.
*
* @param exchange exchange to send.
*/
public void sendElement(Exchange exchange) throws Exception {
processor.process(exchange);
}
public void process(Exchange exchange) throws Exception {
AsyncProcessorHelper.process(this, exchange);
}
public boolean process(Exchange exchange, AsyncCallback callback) {
while (engine.size() >= capacity) {
try {
Thread.sleep(getTimeout());
} catch (InterruptedException e) {
// we was interrupted so break out
exchange.setException(e);
callback.done(true);
return true;
}
}
try {
engine.insert(exchange);
delivery.request();
} catch (Exception e) {
if (isIgnoreInvalidExchanges()) {
LOG.debug("Invalid Exchange. This Exchange will be ignored: {}", exchange);
} else {
exchange.setException(new CamelExchangeException("Error processing Exchange in StreamResequencer", exchange, e));
}
}
callback.done(true);
return true;
}
public boolean hasNext() {
return processor != null;
}
public List<Processor> next() {
if (!hasNext()) {
return null;
}
List<Processor> answer = new ArrayList<Processor>(1);
answer.add(processor);
return answer;
}
class Delivery extends Thread {
private Lock deliveryRequestLock = new ReentrantLock();
private Condition deliveryRequestCondition = deliveryRequestLock.newCondition();
public Delivery() {
super(camelContext.getExecutorServiceManager().resolveThreadName("Resequencer Delivery"));
}
@Override
public void run() {
while (isRunAllowed()) {
try {
deliveryRequestLock.lock();
try {
deliveryRequestCondition.await(DELIVERY_ATTEMPT_INTERVAL, TimeUnit.MILLISECONDS);
} finally {
deliveryRequestLock.unlock();
}
} catch (InterruptedException e) {
break;
}
try {
engine.deliver();
} catch (Throwable t) {
// a fail safe to handle all exceptions being thrown
getExceptionHandler().handleException(t);
}
}
}
public void cancel() {
interrupt();
}
public void request() {
deliveryRequestLock.lock();
try {
deliveryRequestCondition.signal();
} finally {
deliveryRequestLock.unlock();
}
}
}
}