-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
HTTP2Connection.java
484 lines (418 loc) · 13.3 KB
/
HTTP2Connection.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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
//
// ========================================================================
// Copyright (c) 1995-2021 Mort Bay Consulting Pty Ltd and others.
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License v. 2.0 which is available at
// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
// which is available at https://www.apache.org/licenses/LICENSE-2.0.
//
// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
// ========================================================================
//
package org.eclipse.jetty.http2;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayDeque;
import java.util.Queue;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicLong;
import org.eclipse.jetty.http2.frames.DataFrame;
import org.eclipse.jetty.http2.parser.Parser;
import org.eclipse.jetty.io.AbstractConnection;
import org.eclipse.jetty.io.Connection;
import org.eclipse.jetty.io.EndPoint;
import org.eclipse.jetty.io.RetainableByteBuffer;
import org.eclipse.jetty.io.RetainableByteBufferPool;
import org.eclipse.jetty.io.WriteFlusher;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.Callback;
import org.eclipse.jetty.util.component.LifeCycle;
import org.eclipse.jetty.util.thread.AutoLock;
import org.eclipse.jetty.util.thread.ExecutionStrategy;
import org.eclipse.jetty.util.thread.strategy.AdaptiveExecutionStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HTTP2Connection extends AbstractConnection implements WriteFlusher.Listener, Connection.UpgradeTo
{
protected static final Logger LOG = LoggerFactory.getLogger(HTTP2Connection.class);
private final AutoLock lock = new AutoLock();
private final Queue<Runnable> tasks = new ArrayDeque<>();
private final HTTP2Producer producer = new HTTP2Producer();
private final AtomicLong bytesIn = new AtomicLong();
private final RetainableByteBufferPool retainableByteBufferPool;
private final Parser parser;
private final ISession session;
private final int bufferSize;
private final ExecutionStrategy strategy;
private boolean useInputDirectByteBuffers;
private boolean useOutputDirectByteBuffers;
protected HTTP2Connection(RetainableByteBufferPool retainableByteBufferPool, Executor executor, EndPoint endPoint, Parser parser, ISession session, int bufferSize)
{
super(endPoint, executor);
this.retainableByteBufferPool = retainableByteBufferPool;
this.parser = parser;
this.session = session;
this.bufferSize = bufferSize;
this.strategy = new AdaptiveExecutionStrategy(producer, executor);
LifeCycle.start(strategy);
parser.init(ParserListener::new);
}
@Override
public long getMessagesIn()
{
HTTP2Session session = (HTTP2Session)getSession();
return session.getStreamsOpened();
}
@Override
public long getMessagesOut()
{
HTTP2Session session = (HTTP2Session)getSession();
return session.getStreamsClosed();
}
@Override
public long getBytesIn()
{
return bytesIn.get();
}
@Override
public long getBytesOut()
{
return session.getBytesWritten();
}
public ISession getSession()
{
return session;
}
protected Parser getParser()
{
return parser;
}
@Override
public void onUpgradeTo(ByteBuffer buffer)
{
if (LOG.isDebugEnabled())
LOG.debug("HTTP2 onUpgradeTo {} {}", this, BufferUtil.toDetailString(buffer));
producer.setInputBuffer(buffer);
}
public boolean isUseInputDirectByteBuffers()
{
return useInputDirectByteBuffers;
}
public void setUseInputDirectByteBuffers(boolean useInputDirectByteBuffers)
{
this.useInputDirectByteBuffers = useInputDirectByteBuffers;
}
public boolean isUseOutputDirectByteBuffers()
{
return useOutputDirectByteBuffers;
}
public void setUseOutputDirectByteBuffers(boolean useOutputDirectByteBuffers)
{
this.useOutputDirectByteBuffers = useOutputDirectByteBuffers;
}
@Override
public void onOpen()
{
if (LOG.isDebugEnabled())
LOG.debug("HTTP2 Open {} ", this);
super.onOpen();
}
@Override
public void onClose(Throwable cause)
{
if (LOG.isDebugEnabled())
LOG.debug("HTTP2 Close {} ", this);
super.onClose(cause);
LifeCycle.stop(strategy);
}
@Override
public void onFillable()
{
if (LOG.isDebugEnabled())
LOG.debug("HTTP2 onFillable {} ", this);
produce();
}
private int fill(EndPoint endPoint, ByteBuffer buffer)
{
try
{
if (endPoint.isInputShutdown())
return -1;
return endPoint.fill(buffer);
}
catch (IOException x)
{
if (LOG.isDebugEnabled())
LOG.debug("Could not read from {}", endPoint, x);
return -1;
}
}
@Override
public boolean onIdleExpired()
{
boolean idle = isFillInterested();
if (idle)
{
boolean close = session.onIdleTimeout();
if (close)
session.close(ErrorCode.NO_ERROR.code, "idle_timeout", Callback.NOOP);
}
return false;
}
protected void offerTask(Runnable task, boolean dispatch)
{
offerTask(task);
if (dispatch)
dispatch();
else
produce();
}
private void offerTask(Runnable task)
{
try (AutoLock l = lock.lock())
{
tasks.offer(task);
}
}
protected void produce()
{
if (LOG.isDebugEnabled())
LOG.debug("HTTP2 produce {} ", this);
strategy.produce();
}
protected void dispatch()
{
if (LOG.isDebugEnabled())
LOG.debug("HTTP2 dispatch {} ", this);
strategy.dispatch();
}
@Override
public void close()
{
// We don't call super from here, otherwise we close the
// endPoint and we're not able to read or write anymore.
session.close(ErrorCode.NO_ERROR.code, "close", Callback.NOOP);
}
private Runnable pollTask()
{
try (AutoLock l = lock.lock())
{
return tasks.poll();
}
}
@Override
public void onFlushed(long bytes) throws IOException
{
session.onFlushed(bytes);
}
protected class HTTP2Producer implements ExecutionStrategy.Producer
{
private final Callback fillableCallback = new FillableCallback();
private NetworkBuffer networkBuffer;
private boolean shutdown;
private boolean failed;
private void setInputBuffer(ByteBuffer byteBuffer)
{
acquireNetworkBuffer();
// TODO handle buffer overflow?
networkBuffer.put(byteBuffer);
}
@Override
public Runnable produce()
{
Runnable task = pollTask();
if (LOG.isDebugEnabled())
LOG.debug("Dequeued task {}", String.valueOf(task));
if (task != null)
return task;
if (isFillInterested() || shutdown || failed)
return null;
boolean interested = false;
acquireNetworkBuffer();
try
{
boolean parse = networkBuffer.hasRemaining();
while (true)
{
if (parse)
{
while (networkBuffer.hasRemaining())
{
parser.parse(networkBuffer.getBuffer());
if (failed)
return null;
}
task = pollTask();
if (LOG.isDebugEnabled())
LOG.debug("Dequeued new task {}", task);
if (task != null)
return task;
// If more references than 1 (ie not just us), don't refill into buffer and risk compaction.
if (networkBuffer.isRetained())
reacquireNetworkBuffer();
}
// Here we know that this.networkBuffer is not retained by
// application code: either it has been released, or it's a new one.
int filled = fill(getEndPoint(), networkBuffer.getBuffer());
if (LOG.isDebugEnabled())
LOG.debug("Filled {} bytes in {}", filled, networkBuffer);
if (filled > 0)
{
bytesIn.addAndGet(filled);
parse = true;
}
else if (filled == 0)
{
interested = true;
return null;
}
else
{
shutdown = true;
session.onShutdown();
return null;
}
}
}
finally
{
releaseNetworkBuffer();
if (interested)
getEndPoint().fillInterested(fillableCallback);
}
}
private void acquireNetworkBuffer()
{
if (networkBuffer == null)
{
networkBuffer = new NetworkBuffer();
if (LOG.isDebugEnabled())
LOG.debug("Acquired {}", networkBuffer);
}
}
private void reacquireNetworkBuffer()
{
NetworkBuffer currentBuffer = networkBuffer;
if (currentBuffer == null)
throw new IllegalStateException();
if (currentBuffer.hasRemaining())
throw new IllegalStateException();
currentBuffer.release();
networkBuffer = new NetworkBuffer();
if (LOG.isDebugEnabled())
LOG.debug("Reacquired {}<-{}", currentBuffer, networkBuffer);
}
private void releaseNetworkBuffer()
{
NetworkBuffer currentBuffer = networkBuffer;
if (currentBuffer == null)
throw new IllegalStateException();
if (currentBuffer.hasRemaining() && !shutdown && !failed)
throw new IllegalStateException();
currentBuffer.release();
networkBuffer = null;
if (LOG.isDebugEnabled())
LOG.debug("Released {}", currentBuffer);
}
@Override
public String toString()
{
return String.format("%s@%x", getClass().getSimpleName(), hashCode());
}
}
private class FillableCallback implements Callback
{
@Override
public void succeeded()
{
onFillable();
}
@Override
public void failed(Throwable x)
{
onFillInterestedFailed(x);
}
@Override
public InvocationType getInvocationType()
{
return InvocationType.EITHER;
}
}
private class ParserListener extends Parser.Listener.Wrapper
{
private ParserListener(Parser.Listener listener)
{
super(listener);
}
@Override
public void onData(DataFrame frame)
{
NetworkBuffer networkBuffer = producer.networkBuffer;
networkBuffer.retain();
Callback callback = networkBuffer;
session.onData(frame, callback);
}
@Override
public void onConnectionFailure(int error, String reason)
{
producer.failed = true;
super.onConnectionFailure(error, reason);
}
}
private class NetworkBuffer implements Callback
{
private final RetainableByteBuffer delegate;
private NetworkBuffer()
{
delegate = retainableByteBufferPool.acquire(bufferSize, isUseInputDirectByteBuffers());
}
public ByteBuffer getBuffer()
{
return delegate.getBuffer();
}
public boolean isRetained()
{
return delegate.isRetained();
}
public boolean hasRemaining()
{
return delegate.hasRemaining();
}
public boolean release()
{
return delegate.release();
}
public void retain()
{
delegate.retain();
}
private void put(ByteBuffer source)
{
BufferUtil.append(delegate.getBuffer(), source);
}
@Override
public void succeeded()
{
completed(null);
}
@Override
public void failed(Throwable failure)
{
completed(failure);
}
private void completed(Throwable failure)
{
if (delegate.release())
{
if (LOG.isDebugEnabled())
LOG.debug("Released retained {}", this, failure);
}
}
@Override
public InvocationType getInvocationType()
{
return InvocationType.NON_BLOCKING;
}
}
}