• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

grpc / grpc-java / #19159

08 Apr 2024 07:52PM UTC coverage: 88.154% (+0.02%) from 88.134%
#19159

push

github

web-flow
buildscripts: Migrate PSM Interop to Artifact Registry (#11079) (#11095)

From Container Registry (gcr.io) to Artifact Registry (pkg.dev).

30839 of 34983 relevant lines covered (88.15%)

0.88 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

92.83
/../okhttp/src/main/java/io/grpc/okhttp/OkHttpServerTransport.java
1
/*
2
 * Copyright 2022 The gRPC Authors
3
 *
4
 * Licensed under the Apache License, Version 2.0 (the "License");
5
 * you may not use this file except in compliance with the License.
6
 * You may obtain a copy of the License at
7
 *
8
 *     http://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 * Unless required by applicable law or agreed to in writing, software
11
 * distributed under the License is distributed on an "AS IS" BASIS,
12
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 * See the License for the specific language governing permissions and
14
 * limitations under the License.
15
 */
16

17
package io.grpc.okhttp;
18

19
import static io.grpc.okhttp.OkHttpServerBuilder.MAX_CONNECTION_AGE_NANOS_DISABLED;
20
import static io.grpc.okhttp.OkHttpServerBuilder.MAX_CONNECTION_IDLE_NANOS_DISABLED;
21

22
import com.google.common.base.Preconditions;
23
import com.google.common.util.concurrent.Futures;
24
import com.google.common.util.concurrent.ListenableFuture;
25
import io.grpc.Attributes;
26
import io.grpc.InternalChannelz;
27
import io.grpc.InternalLogId;
28
import io.grpc.InternalStatus;
29
import io.grpc.Metadata;
30
import io.grpc.ServerStreamTracer;
31
import io.grpc.Status;
32
import io.grpc.internal.GrpcUtil;
33
import io.grpc.internal.KeepAliveEnforcer;
34
import io.grpc.internal.KeepAliveManager;
35
import io.grpc.internal.LogExceptionRunnable;
36
import io.grpc.internal.MaxConnectionIdleManager;
37
import io.grpc.internal.ObjectPool;
38
import io.grpc.internal.SerializingExecutor;
39
import io.grpc.internal.ServerTransport;
40
import io.grpc.internal.ServerTransportListener;
41
import io.grpc.internal.StatsTraceContext;
42
import io.grpc.internal.TransportTracer;
43
import io.grpc.okhttp.internal.framed.ErrorCode;
44
import io.grpc.okhttp.internal.framed.FrameReader;
45
import io.grpc.okhttp.internal.framed.FrameWriter;
46
import io.grpc.okhttp.internal.framed.Header;
47
import io.grpc.okhttp.internal.framed.HeadersMode;
48
import io.grpc.okhttp.internal.framed.Http2;
49
import io.grpc.okhttp.internal.framed.Settings;
50
import io.grpc.okhttp.internal.framed.Variant;
51
import java.io.IOException;
52
import java.net.Socket;
53
import java.util.List;
54
import java.util.Locale;
55
import java.util.Map;
56
import java.util.TreeMap;
57
import java.util.concurrent.Executor;
58
import java.util.concurrent.ScheduledExecutorService;
59
import java.util.concurrent.ScheduledFuture;
60
import java.util.concurrent.TimeUnit;
61
import java.util.logging.Level;
62
import java.util.logging.Logger;
63
import javax.annotation.Nullable;
64
import javax.annotation.concurrent.GuardedBy;
65
import okio.Buffer;
66
import okio.BufferedSource;
67
import okio.ByteString;
68
import okio.Okio;
69

70
/**
71
 * OkHttp-based server transport.
72
 */
73
final class OkHttpServerTransport implements ServerTransport,
74
      ExceptionHandlingFrameWriter.TransportExceptionHandler, OutboundFlowController.Transport {
75
  private static final Logger log = Logger.getLogger(OkHttpServerTransport.class.getName());
1✔
76
  private static final int GRACEFUL_SHUTDOWN_PING = 0x1111;
77

78
  private static final long GRACEFUL_SHUTDOWN_PING_TIMEOUT_NANOS = TimeUnit.SECONDS.toNanos(1);
1✔
79

80
  private static final int KEEPALIVE_PING = 0xDEAD;
81
  private static final ByteString HTTP_METHOD = ByteString.encodeUtf8(":method");
1✔
82
  private static final ByteString CONNECT_METHOD = ByteString.encodeUtf8("CONNECT");
1✔
83
  private static final ByteString POST_METHOD = ByteString.encodeUtf8("POST");
1✔
84
  private static final ByteString SCHEME = ByteString.encodeUtf8(":scheme");
1✔
85
  private static final ByteString PATH = ByteString.encodeUtf8(":path");
1✔
86
  private static final ByteString AUTHORITY = ByteString.encodeUtf8(":authority");
1✔
87
  private static final ByteString CONNECTION = ByteString.encodeUtf8("connection");
1✔
88
  private static final ByteString HOST = ByteString.encodeUtf8("host");
1✔
89
  private static final ByteString TE = ByteString.encodeUtf8("te");
1✔
90
  private static final ByteString TE_TRAILERS = ByteString.encodeUtf8("trailers");
1✔
91
  private static final ByteString CONTENT_TYPE = ByteString.encodeUtf8("content-type");
1✔
92
  private static final ByteString CONTENT_LENGTH = ByteString.encodeUtf8("content-length");
1✔
93

94
  private final Config config;
95
  private final Socket bareSocket;
96
  private final Variant variant = new Http2();
1✔
97
  private final TransportTracer tracer;
98
  private final InternalLogId logId;
99
  private ServerTransportListener listener;
100
  private Executor transportExecutor;
101
  private ScheduledExecutorService scheduledExecutorService;
102
  private Attributes attributes;
103
  private KeepAliveManager keepAliveManager;
104
  private MaxConnectionIdleManager maxConnectionIdleManager;
105
  private ScheduledFuture<?> maxConnectionAgeMonitor;
106
  private final KeepAliveEnforcer keepAliveEnforcer;
107

108
  private final Object lock = new Object();
1✔
109
  @GuardedBy("lock")
110
  private boolean abruptShutdown;
111
  @GuardedBy("lock")
112
  private boolean gracefulShutdown;
113
  @GuardedBy("lock")
114
  private boolean handshakeShutdown;
115
  @GuardedBy("lock")
116
  private InternalChannelz.Security securityInfo;
117
  @GuardedBy("lock")
118
  private ExceptionHandlingFrameWriter frameWriter;
119
  @GuardedBy("lock")
120
  private OutboundFlowController outboundFlow;
121
  @GuardedBy("lock")
1✔
122
  private final Map<Integer, StreamState> streams = new TreeMap<>();
123
  @GuardedBy("lock")
124
  private int lastStreamId;
125
  @GuardedBy("lock")
1✔
126
  private int goAwayStreamId = Integer.MAX_VALUE;
127
  /**
128
   * Indicates the transport is in go-away state: no new streams will be processed, but existing
129
   * streams may continue.
130
   */
131
  @GuardedBy("lock")
132
  private Status goAwayStatus;
133
  /** Non-{@code null} when gracefully shutting down and have not yet sent second GOAWAY. */
134
  @GuardedBy("lock")
135
  private ScheduledFuture<?> secondGoawayTimer;
136
  /** Non-{@code null} when waiting for forceful close GOAWAY to be sent. */
137
  @GuardedBy("lock")
138
  private ScheduledFuture<?> forcefulCloseTimer;
139
  @GuardedBy("lock")
1✔
140
  private Long gracefulShutdownPeriod = null;
141

142
  public OkHttpServerTransport(Config config, Socket bareSocket) {
1✔
143
    this.config = Preconditions.checkNotNull(config, "config");
1✔
144
    this.bareSocket = Preconditions.checkNotNull(bareSocket, "bareSocket");
1✔
145

146
    tracer = config.transportTracerFactory.create();
1✔
147
    tracer.setFlowControlWindowReader(this::readFlowControlWindow);
1✔
148
    logId = InternalLogId.allocate(getClass(), bareSocket.getRemoteSocketAddress().toString());
1✔
149
    transportExecutor = config.transportExecutorPool.getObject();
1✔
150
    scheduledExecutorService = config.scheduledExecutorServicePool.getObject();
1✔
151
    keepAliveEnforcer = new KeepAliveEnforcer(config.permitKeepAliveWithoutCalls,
1✔
152
        config.permitKeepAliveTimeInNanos, TimeUnit.NANOSECONDS);
153
  }
1✔
154

155
  public void start(ServerTransportListener listener) {
156
    this.listener = Preconditions.checkNotNull(listener, "listener");
1✔
157

158
    SerializingExecutor serializingExecutor = new SerializingExecutor(transportExecutor);
1✔
159
    serializingExecutor.execute(() -> startIo(serializingExecutor));
1✔
160
  }
1✔
161

162
  private void startIo(SerializingExecutor serializingExecutor) {
163
    try {
164
      bareSocket.setTcpNoDelay(true);
1✔
165
      HandshakerSocketFactory.HandshakeResult result =
1✔
166
          config.handshakerSocketFactory.handshake(bareSocket, Attributes.EMPTY);
1✔
167
      Socket socket = result.socket;
1✔
168
      this.attributes = result.attributes;
1✔
169

170
      int maxQueuedControlFrames = 10000;
1✔
171
      AsyncSink asyncSink = AsyncSink.sink(serializingExecutor, this, maxQueuedControlFrames);
1✔
172
      asyncSink.becomeConnected(Okio.sink(socket), socket);
1✔
173
      FrameWriter rawFrameWriter = asyncSink.limitControlFramesWriter(
1✔
174
          variant.newWriter(Okio.buffer(asyncSink), false));
1✔
175
      FrameWriter writeMonitoringFrameWriter = new ForwardingFrameWriter(rawFrameWriter) {
1✔
176
        @Override
177
        public void synReply(boolean outFinished, int streamId, List<Header> headerBlock)
178
            throws IOException {
179
          keepAliveEnforcer.resetCounters();
1✔
180
          super.synReply(outFinished, streamId, headerBlock);
1✔
181
        }
1✔
182

183
        @Override
184
        public void headers(int streamId, List<Header> headerBlock) throws IOException {
185
          keepAliveEnforcer.resetCounters();
1✔
186
          super.headers(streamId, headerBlock);
1✔
187
        }
1✔
188

189
        @Override
190
        public void data(boolean outFinished, int streamId, Buffer source, int byteCount)
191
            throws IOException {
192
          keepAliveEnforcer.resetCounters();
1✔
193
          super.data(outFinished, streamId, source, byteCount);
1✔
194
        }
1✔
195
      };
196
      synchronized (lock) {
1✔
197
        this.securityInfo = result.securityInfo;
1✔
198

199
        // Handle FrameWriter exceptions centrally, since there are many callers. Note that
200
        // errors coming from rawFrameWriter are generally broken invariants/bugs, as AsyncSink
201
        // does not propagate syscall errors through the FrameWriter. But we handle the
202
        // AsyncSink failures with the same TransportExceptionHandler instance so it is all
203
        // mixed back together.
204
        frameWriter = new ExceptionHandlingFrameWriter(this, writeMonitoringFrameWriter);
1✔
205
        outboundFlow = new OutboundFlowController(this, frameWriter);
1✔
206

207
        // These writes will be queued in the serializingExecutor waiting for this function to
208
        // return.
209
        frameWriter.connectionPreface();
1✔
210
        Settings settings = new Settings();
1✔
211
        OkHttpSettingsUtil.set(settings,
1✔
212
            OkHttpSettingsUtil.INITIAL_WINDOW_SIZE, config.flowControlWindow);
213
        OkHttpSettingsUtil.set(settings,
1✔
214
            OkHttpSettingsUtil.MAX_HEADER_LIST_SIZE, config.maxInboundMetadataSize);
215
        frameWriter.settings(settings);
1✔
216
        if (config.flowControlWindow > Utils.DEFAULT_WINDOW_SIZE) {
1✔
217
          frameWriter.windowUpdate(
1✔
218
              Utils.CONNECTION_STREAM_ID, config.flowControlWindow - Utils.DEFAULT_WINDOW_SIZE);
219
        }
220
        frameWriter.flush();
1✔
221
      }
1✔
222

223
      if (config.keepAliveTimeNanos != GrpcUtil.KEEPALIVE_TIME_NANOS_DISABLED) {
1✔
224
        keepAliveManager = new KeepAliveManager(
1✔
225
            new KeepAlivePinger(), scheduledExecutorService, config.keepAliveTimeNanos,
226
            config.keepAliveTimeoutNanos, true);
227
        keepAliveManager.onTransportStarted();
1✔
228
      }
229

230
      if (config.maxConnectionIdleNanos != MAX_CONNECTION_IDLE_NANOS_DISABLED) {
1✔
231
        maxConnectionIdleManager = new MaxConnectionIdleManager(config.maxConnectionIdleNanos);
1✔
232
        maxConnectionIdleManager.start(this::shutdown, scheduledExecutorService);
1✔
233
      }
234

235
      if (config.maxConnectionAgeInNanos != MAX_CONNECTION_AGE_NANOS_DISABLED) {
1✔
236
        long maxConnectionAgeInNanos =
1✔
237
            (long) ((.9D + Math.random() * .2D) * config.maxConnectionAgeInNanos);
1✔
238
        maxConnectionAgeMonitor = scheduledExecutorService.schedule(
1✔
239
            new LogExceptionRunnable(() -> shutdown(config.maxConnectionAgeGraceInNanos)),
1✔
240
            maxConnectionAgeInNanos,
241
            TimeUnit.NANOSECONDS);
242
      }
243

244
      transportExecutor.execute(
1✔
245
          new FrameHandler(variant.newReader(Okio.buffer(Okio.source(socket)), false)));
1✔
246
    } catch (Error | IOException | RuntimeException ex) {
1✔
247
      synchronized (lock) {
1✔
248
        if (!handshakeShutdown) {
1✔
249
          log.log(Level.INFO, "Socket failed to handshake", ex);
1✔
250
        }
251
      }
1✔
252
      GrpcUtil.closeQuietly(bareSocket);
1✔
253
      terminated();
1✔
254
    }
1✔
255
  }
1✔
256

257
  @Override
258
  public void shutdown() {
259
    shutdown(null);
1✔
260
  }
1✔
261

262
  private void shutdown(@Nullable Long gracefulShutdownPeriod) {
263
    synchronized (lock) {
1✔
264
      if (gracefulShutdown || abruptShutdown) {
1✔
265
        return;
1✔
266
      }
267
      gracefulShutdown = true;
1✔
268
      this.gracefulShutdownPeriod = gracefulShutdownPeriod;
1✔
269
      if (frameWriter == null) {
1✔
270
        handshakeShutdown = true;
1✔
271
        GrpcUtil.closeQuietly(bareSocket);
1✔
272
      } else {
273
        // RFC7540 §6.8. Begin double-GOAWAY graceful shutdown. To wait one RTT we use a PING, but
274
        // we also set a timer to limit the upper bound in case the PING is excessively stalled or
275
        // the client is malicious.
276
        secondGoawayTimer = scheduledExecutorService.schedule(
1✔
277
            this::triggerGracefulSecondGoaway,
278
            GRACEFUL_SHUTDOWN_PING_TIMEOUT_NANOS, TimeUnit.NANOSECONDS);
279
        frameWriter.goAway(Integer.MAX_VALUE, ErrorCode.NO_ERROR, new byte[0]);
1✔
280
        frameWriter.ping(false, 0, GRACEFUL_SHUTDOWN_PING);
1✔
281
        frameWriter.flush();
1✔
282
      }
283
    }
1✔
284
  }
1✔
285

286
  private void triggerGracefulSecondGoaway() {
287
    synchronized (lock) {
1✔
288
      if (secondGoawayTimer == null) {
1✔
289
        return;
×
290
      }
291
      secondGoawayTimer.cancel(false);
1✔
292
      secondGoawayTimer = null;
1✔
293
      frameWriter.goAway(lastStreamId, ErrorCode.NO_ERROR, new byte[0]);
1✔
294
      goAwayStreamId = lastStreamId;
1✔
295
      if (streams.isEmpty()) {
1✔
296
        frameWriter.close();
1✔
297
      } else {
298
        frameWriter.flush();
1✔
299
      }
300
      if (gracefulShutdownPeriod != null) {
1✔
301
        forcefulCloseTimer = scheduledExecutorService.schedule(
1✔
302
            this::triggerForcefulClose, gracefulShutdownPeriod, TimeUnit.NANOSECONDS);
1✔
303
      }
304
    }
1✔
305
  }
1✔
306

307
  @Override
308
  public void shutdownNow(Status reason) {
309
    synchronized (lock) {
1✔
310
      if (frameWriter == null) {
1✔
311
        handshakeShutdown = true;
1✔
312
        GrpcUtil.closeQuietly(bareSocket);
1✔
313
        return;
1✔
314
      }
315
    }
1✔
316
    abruptShutdown(ErrorCode.NO_ERROR, "", reason, true);
1✔
317
  }
1✔
318

319
  /**
320
   * Finish all active streams due to an IOException, then close the transport.
321
   */
322
  @Override
323
  public void onException(Throwable failureCause) {
324
    Preconditions.checkNotNull(failureCause, "failureCause");
1✔
325
    Status status = Status.UNAVAILABLE.withCause(failureCause);
1✔
326
    abruptShutdown(ErrorCode.INTERNAL_ERROR, "I/O failure", status, false);
1✔
327
  }
1✔
328

329
  private void abruptShutdown(
330
      ErrorCode errorCode, String moreDetail, Status reason, boolean rstStreams) {
331
    synchronized (lock) {
1✔
332
      if (abruptShutdown) {
1✔
333
        return;
1✔
334
      }
335
      abruptShutdown = true;
1✔
336
      goAwayStatus = reason;
1✔
337

338
      if (secondGoawayTimer != null) {
1✔
339
        secondGoawayTimer.cancel(false);
1✔
340
        secondGoawayTimer = null;
1✔
341
      }
342
      for (Map.Entry<Integer, StreamState> entry : streams.entrySet()) {
1✔
343
        if (rstStreams) {
1✔
344
          frameWriter.rstStream(entry.getKey(), ErrorCode.CANCEL);
1✔
345
        }
346
        entry.getValue().transportReportStatus(reason);
1✔
347
      }
1✔
348
      streams.clear();
1✔
349

350
      // RFC7540 §5.4.1. Attempt to inform the client what went wrong. We try to write the GOAWAY
351
      // _and then_ close our side of the connection. But place an upper-bound for how long we wait
352
      // for I/O with a timer, which forcefully closes the socket.
353
      frameWriter.goAway(lastStreamId, errorCode, moreDetail.getBytes(GrpcUtil.US_ASCII));
1✔
354
      goAwayStreamId = lastStreamId;
1✔
355
      frameWriter.close();
1✔
356
      forcefulCloseTimer = scheduledExecutorService.schedule(
1✔
357
          this::triggerForcefulClose, 1, TimeUnit.SECONDS);
358
    }
1✔
359
  }
1✔
360

361
  private void triggerForcefulClose() {
362
    // Safe to do unconditionally; no need to check if timer cancellation raced
363
    GrpcUtil.closeQuietly(bareSocket);
1✔
364
  }
1✔
365

366
  private void terminated() {
367
    synchronized (lock) {
1✔
368
      if (forcefulCloseTimer != null) {
1✔
369
        forcefulCloseTimer.cancel(false);
1✔
370
        forcefulCloseTimer = null;
1✔
371
      }
372
    }
1✔
373
    if (keepAliveManager != null) {
1✔
374
      keepAliveManager.onTransportTermination();
1✔
375
    }
376
    if (maxConnectionIdleManager != null) {
1✔
377
      maxConnectionIdleManager.onTransportTermination();
1✔
378
    }
379

380
    if (maxConnectionAgeMonitor != null) {
1✔
381
      maxConnectionAgeMonitor.cancel(false);
1✔
382
    }
383
    transportExecutor = config.transportExecutorPool.returnObject(transportExecutor);
1✔
384
    scheduledExecutorService =
1✔
385
        config.scheduledExecutorServicePool.returnObject(scheduledExecutorService);
1✔
386
    listener.transportTerminated();
1✔
387
  }
1✔
388

389
  @Override
390
  public ScheduledExecutorService getScheduledExecutorService() {
391
    return scheduledExecutorService;
1✔
392
  }
393

394
  @Override
395
  public ListenableFuture<InternalChannelz.SocketStats> getStats() {
396
    synchronized (lock) {
1✔
397
      return Futures.immediateFuture(new InternalChannelz.SocketStats(
1✔
398
          tracer.getStats(),
1✔
399
          bareSocket.getLocalSocketAddress(),
1✔
400
          bareSocket.getRemoteSocketAddress(),
1✔
401
          Utils.getSocketOptions(bareSocket),
1✔
402
          securityInfo));
403
    }
404
  }
405

406
  private TransportTracer.FlowControlWindows readFlowControlWindow() {
407
    synchronized (lock) {
1✔
408
      long local = outboundFlow == null ? -1 : outboundFlow.windowUpdate(null, 0);
1✔
409
      // connectionUnacknowledgedBytesRead is only readable by FrameHandler, so we provide a lower
410
      // bound.
411
      long remote = (long) (config.flowControlWindow * Utils.DEFAULT_WINDOW_UPDATE_RATIO);
1✔
412
      return new TransportTracer.FlowControlWindows(local, remote);
1✔
413
    }
414
  }
415

416
  @Override
417
  public InternalLogId getLogId() {
418
    return logId;
1✔
419
  }
420

421
  @Override
422
  public OutboundFlowController.StreamState[] getActiveStreams() {
423
    synchronized (lock) {
1✔
424
      OutboundFlowController.StreamState[] flowStreams =
1✔
425
          new OutboundFlowController.StreamState[streams.size()];
1✔
426
      int i = 0;
1✔
427
      for (StreamState stream : streams.values()) {
1✔
428
        flowStreams[i++] = stream.getOutboundFlowState();
1✔
429
      }
1✔
430
      return flowStreams;
1✔
431
    }
432
  }
433

434
  /**
435
   * Notify the transport that the stream was closed. Any frames for the stream must be enqueued
436
   * before calling.
437
   */
438
  void streamClosed(int streamId, boolean flush) {
439
    synchronized (lock) {
1✔
440
      streams.remove(streamId);
1✔
441
      if (streams.isEmpty()) {
1✔
442
        keepAliveEnforcer.onTransportIdle();
1✔
443
        if (maxConnectionIdleManager != null) {
1✔
444
          maxConnectionIdleManager.onTransportIdle();
1✔
445
        }
446
      }
447
      if (gracefulShutdown && streams.isEmpty()) {
1✔
448
        frameWriter.close();
1✔
449
      } else {
450
        if (flush) {
1✔
451
          frameWriter.flush();
1✔
452
        }
453
      }
454
    }
1✔
455
  }
1✔
456

457
  private static String asciiString(ByteString value) {
458
    // utf8() string is cached in ByteString, so we prefer it when the contents are ASCII. This
459
    // provides benefit if the header was reused via HPACK.
460
    for (int i = 0; i < value.size(); i++) {
1✔
461
      if (value.getByte(i) >= 0x80) {
1✔
462
        return value.string(GrpcUtil.US_ASCII);
×
463
      }
464
    }
465
    return value.utf8();
1✔
466
  }
467

468
  private static int headerFind(List<Header> header, ByteString key, int startIndex) {
469
    for (int i = startIndex; i < header.size(); i++) {
1✔
470
      if (header.get(i).name.equals(key)) {
1✔
471
        return i;
1✔
472
      }
473
    }
474
    return -1;
1✔
475
  }
476

477
  private static boolean headerContains(List<Header> header, ByteString key) {
478
    return headerFind(header, key, 0) != -1;
1✔
479
  }
480

481
  private static void headerRemove(List<Header> header, ByteString key) {
482
    int i = 0;
1✔
483
    while ((i = headerFind(header, key, i)) != -1) {
1✔
484
      header.remove(i);
1✔
485
    }
486
  }
1✔
487

488
  /** Assumes that caller requires this field, so duplicates are treated as missing. */
489
  private static ByteString headerGetRequiredSingle(List<Header> header, ByteString key) {
490
    int i = headerFind(header, key, 0);
1✔
491
    if (i == -1) {
1✔
492
      return null;
1✔
493
    }
494
    if (headerFind(header, key, i + 1) != -1) {
1✔
495
      return null;
1✔
496
    }
497
    return header.get(i).value;
1✔
498
  }
499

500
  static final class Config {
501
    final List<? extends ServerStreamTracer.Factory> streamTracerFactories;
502
    final ObjectPool<Executor> transportExecutorPool;
503
    final ObjectPool<ScheduledExecutorService> scheduledExecutorServicePool;
504
    final TransportTracer.Factory transportTracerFactory;
505
    final HandshakerSocketFactory handshakerSocketFactory;
506
    final long keepAliveTimeNanos;
507
    final long keepAliveTimeoutNanos;
508
    final int flowControlWindow;
509
    final int maxInboundMessageSize;
510
    final int maxInboundMetadataSize;
511
    final long maxConnectionIdleNanos;
512
    final boolean permitKeepAliveWithoutCalls;
513
    final long permitKeepAliveTimeInNanos;
514
    final long maxConnectionAgeInNanos;
515
    final long maxConnectionAgeGraceInNanos;
516

517
    public Config(
518
        OkHttpServerBuilder builder,
519
        List<? extends ServerStreamTracer.Factory> streamTracerFactories) {
1✔
520
      this.streamTracerFactories = Preconditions.checkNotNull(
1✔
521
          streamTracerFactories, "streamTracerFactories");
522
      transportExecutorPool = Preconditions.checkNotNull(
1✔
523
          builder.transportExecutorPool, "transportExecutorPool");
524
      scheduledExecutorServicePool = Preconditions.checkNotNull(
1✔
525
          builder.scheduledExecutorServicePool, "scheduledExecutorServicePool");
526
      transportTracerFactory = Preconditions.checkNotNull(
1✔
527
          builder.transportTracerFactory, "transportTracerFactory");
528
      handshakerSocketFactory = Preconditions.checkNotNull(
1✔
529
          builder.handshakerSocketFactory, "handshakerSocketFactory");
530
      keepAliveTimeNanos = builder.keepAliveTimeNanos;
1✔
531
      keepAliveTimeoutNanos = builder.keepAliveTimeoutNanos;
1✔
532
      flowControlWindow = builder.flowControlWindow;
1✔
533
      maxInboundMessageSize = builder.maxInboundMessageSize;
1✔
534
      maxInboundMetadataSize = builder.maxInboundMetadataSize;
1✔
535
      maxConnectionIdleNanos = builder.maxConnectionIdleInNanos;
1✔
536
      permitKeepAliveWithoutCalls = builder.permitKeepAliveWithoutCalls;
1✔
537
      permitKeepAliveTimeInNanos = builder.permitKeepAliveTimeInNanos;
1✔
538
      maxConnectionAgeInNanos = builder.maxConnectionAgeInNanos;
1✔
539
      maxConnectionAgeGraceInNanos = builder.maxConnectionAgeGraceInNanos;
1✔
540
    }
1✔
541
  }
542

543
  /**
544
   * Runnable which reads frames and dispatches them to in flight calls.
545
   */
546
  class FrameHandler implements FrameReader.Handler, Runnable {
547
    private final OkHttpFrameLogger frameLogger =
1✔
548
        new OkHttpFrameLogger(Level.FINE, OkHttpServerTransport.class);
549
    private final FrameReader frameReader;
550
    private boolean receivedSettings;
551
    private int connectionUnacknowledgedBytesRead;
552

553
    public FrameHandler(FrameReader frameReader) {
1✔
554
      this.frameReader = frameReader;
1✔
555
    }
1✔
556

557
    @Override
558
    public void run() {
559
      String threadName = Thread.currentThread().getName();
1✔
560
      Thread.currentThread().setName("OkHttpServerTransport");
1✔
561
      try {
562
        frameReader.readConnectionPreface();
1✔
563
        if (!frameReader.nextFrame(this)) {
1✔
564
          connectionError(ErrorCode.INTERNAL_ERROR, "Failed to read initial SETTINGS");
×
565
          return;
×
566
        }
567
        if (!receivedSettings) {
1✔
568
          connectionError(ErrorCode.PROTOCOL_ERROR,
1✔
569
              "First HTTP/2 frame must be SETTINGS. RFC7540 section 3.5");
570
          return;
1✔
571
        }
572
        // Read until the underlying socket closes.
573
        while (frameReader.nextFrame(this)) {
1✔
574
          if (keepAliveManager != null) {
1✔
575
            keepAliveManager.onDataReceived();
1✔
576
          }
577
        }
578
        // frameReader.nextFrame() returns false when the underlying read encounters an IOException,
579
        // it may be triggered by the socket closing, in such case, the startGoAway() will do
580
        // nothing, otherwise, we finish all streams since it's a real IO issue.
581
        Status status;
582
        synchronized (lock) {
1✔
583
          status = goAwayStatus;
1✔
584
        }
1✔
585
        if (status == null) {
1✔
586
          status = Status.UNAVAILABLE.withDescription("TCP connection closed or IOException");
1✔
587
        }
588
        abruptShutdown(ErrorCode.INTERNAL_ERROR, "I/O failure", status, false);
1✔
589
      } catch (Throwable t) {
1✔
590
        log.log(Level.WARNING, "Error decoding HTTP/2 frames", t);
1✔
591
        abruptShutdown(ErrorCode.INTERNAL_ERROR, "Error in frame decoder",
1✔
592
            Status.INTERNAL.withDescription("Error decoding HTTP/2 frames").withCause(t), false);
1✔
593
      } finally {
594
        // Wait for the abrupt shutdown to be processed by AsyncSink and close the socket
595
        try {
596
          GrpcUtil.exhaust(bareSocket.getInputStream());
1✔
597
        } catch (IOException ex) {
1✔
598
          // Unable to wait, so just proceed to tear-down. The socket is probably already closed so
599
          // the GOAWAY can't be sent anyway.
600
        }
1✔
601
        GrpcUtil.closeQuietly(bareSocket);
1✔
602
        terminated();
1✔
603
        Thread.currentThread().setName(threadName);
1✔
604
      }
605
    }
1✔
606

607
    /**
608
     * Handle HTTP2 HEADER and CONTINUATION frames.
609
     */
610
    @Override
611
    public void headers(boolean outFinished,
612
        boolean inFinished,
613
        int streamId,
614
        int associatedStreamId,
615
        List<Header> headerBlock,
616
        HeadersMode headersMode) {
617
      frameLogger.logHeaders(
1✔
618
          OkHttpFrameLogger.Direction.INBOUND, streamId, headerBlock, inFinished);
619
      // streamId == 0 checking is in HTTP/2 decoder
620
      if ((streamId & 1) == 0) {
1✔
621
        // The server doesn't use PUSH_PROMISE, so all even streams are IDLE
622
        connectionError(ErrorCode.PROTOCOL_ERROR,
1✔
623
            "Clients cannot open even numbered streams. RFC7540 section 5.1.1");
624
        return;
1✔
625
      }
626
      boolean newStream;
627
      synchronized (lock) {
1✔
628
        if (streamId > goAwayStreamId) {
1✔
629
          return;
×
630
        }
631
        newStream = streamId > lastStreamId;
1✔
632
        if (newStream) {
1✔
633
          lastStreamId = streamId;
1✔
634
        }
635
      }
1✔
636

637
      int metadataSize = headerBlockSize(headerBlock);
1✔
638
      if (metadataSize > config.maxInboundMetadataSize) {
1✔
639
        respondWithHttpError(streamId, inFinished, 431, Status.Code.RESOURCE_EXHAUSTED,
1✔
640
            String.format(
1✔
641
                Locale.US,
642
                "Request metadata larger than %d: %d",
643
                config.maxInboundMetadataSize,
1✔
644
                metadataSize));
1✔
645
        return;
1✔
646
      }
647

648
      headerRemove(headerBlock, ByteString.EMPTY);
1✔
649

650
      ByteString httpMethod = null;
1✔
651
      ByteString scheme = null;
1✔
652
      ByteString path = null;
1✔
653
      ByteString authority = null;
1✔
654
      while (headerBlock.size() > 0 && headerBlock.get(0).name.getByte(0) == ':') {
1✔
655
        Header header = headerBlock.remove(0);
1✔
656
        if (HTTP_METHOD.equals(header.name) && httpMethod == null) {
1✔
657
          httpMethod = header.value;
1✔
658
        } else if (SCHEME.equals(header.name) && scheme == null) {
1✔
659
          scheme = header.value;
1✔
660
        } else if (PATH.equals(header.name) && path == null) {
1✔
661
          path = header.value;
1✔
662
        } else if (AUTHORITY.equals(header.name) && authority == null) {
1✔
663
          authority = header.value;
1✔
664
        } else {
665
          streamError(streamId, ErrorCode.PROTOCOL_ERROR,
1✔
666
              "Unexpected pseudo header. RFC7540 section 8.1.2.1");
667
          return;
1✔
668
        }
669
      }
1✔
670
      for (int i = 0; i < headerBlock.size(); i++) {
1✔
671
        if (headerBlock.get(i).name.getByte(0) == ':') {
1✔
672
          streamError(streamId, ErrorCode.PROTOCOL_ERROR,
1✔
673
              "Pseudo header not before regular headers. RFC7540 section 8.1.2.1");
674
          return;
1✔
675
        }
676
      }
677
      if (!CONNECT_METHOD.equals(httpMethod)
1✔
678
          && newStream
679
          && (httpMethod == null || scheme == null || path == null)) {
680
        streamError(streamId, ErrorCode.PROTOCOL_ERROR,
1✔
681
            "Missing required pseudo header. RFC7540 section 8.1.2.3");
682
        return;
1✔
683
      }
684
      if (headerContains(headerBlock, CONNECTION)) {
1✔
685
        streamError(streamId, ErrorCode.PROTOCOL_ERROR,
1✔
686
            "Connection-specific headers not permitted. RFC7540 section 8.1.2.2");
687
        return;
1✔
688
      }
689

690
      if (!newStream) {
1✔
691
        if (inFinished) {
1✔
692
          synchronized (lock) {
1✔
693
            StreamState stream = streams.get(streamId);
1✔
694
            if (stream == null) {
1✔
695
              streamError(streamId, ErrorCode.STREAM_CLOSED, "Received headers for closed stream");
×
696
              return;
×
697
            }
698
            if (stream.hasReceivedEndOfStream()) {
1✔
699
              streamError(streamId, ErrorCode.STREAM_CLOSED,
1✔
700
                  "Received HEADERS for half-closed (remote) stream. RFC7540 section 5.1");
701
              return;
1✔
702
            }
703
            // Ignore the trailers, but still half-close the stream
704
            stream.inboundDataReceived(new Buffer(), 0, true);
1✔
705
            return;
1✔
706
          }
707
        } else {
708
          streamError(streamId, ErrorCode.PROTOCOL_ERROR,
1✔
709
              "Headers disallowed in the middle of the stream. RFC7540 section 8.1");
710
          return;
1✔
711
        }
712
      }
713

714
      if (authority == null) {
1✔
715
        int i = headerFind(headerBlock, HOST, 0);
1✔
716
        if (i != -1) {
1✔
717
          if (headerFind(headerBlock, HOST, i + 1) != -1) {
1✔
718
            respondWithHttpError(streamId, inFinished, 400, Status.Code.INTERNAL,
1✔
719
                "Multiple host headers disallowed. RFC7230 section 5.4");
720
            return;
1✔
721
          }
722
          authority = headerBlock.get(i).value;
1✔
723
        }
724
      }
725
      headerRemove(headerBlock, HOST);
1✔
726

727
      // Remove the leading slash of the path and get the fully qualified method name
728
      if (path.size() == 0 || path.getByte(0) != '/') {
1✔
729
        respondWithHttpError(streamId, inFinished, 404, Status.Code.UNIMPLEMENTED,
1✔
730
            "Expected path to start with /: " + asciiString(path));
1✔
731
        return;
1✔
732
      }
733
      String method = asciiString(path).substring(1);
1✔
734

735
      ByteString contentType = headerGetRequiredSingle(headerBlock, CONTENT_TYPE);
1✔
736
      if (contentType == null) {
1✔
737
        respondWithHttpError(streamId, inFinished, 415, Status.Code.INTERNAL,
1✔
738
            "Content-Type is missing or duplicated");
739
        return;
1✔
740
      }
741
      String contentTypeString = asciiString(contentType);
1✔
742
      if (!GrpcUtil.isGrpcContentType(contentTypeString)) {
1✔
743
        respondWithHttpError(streamId, inFinished, 415, Status.Code.INTERNAL,
1✔
744
            "Content-Type is not supported: " + contentTypeString);
745
        return;
1✔
746
      }
747

748
      if (!POST_METHOD.equals(httpMethod)) {
1✔
749
        respondWithHttpError(streamId, inFinished, 405, Status.Code.INTERNAL,
1✔
750
            "HTTP Method is not supported: " + asciiString(httpMethod));
1✔
751
        return;
1✔
752
      }
753

754
      ByteString te = headerGetRequiredSingle(headerBlock, TE);
1✔
755
      if (!TE_TRAILERS.equals(te)) {
1✔
756
        respondWithGrpcError(streamId, inFinished, Status.Code.INTERNAL,
1✔
757
            String.format("Expected header TE: %s, but %s is received. "
1✔
758
              + "Some intermediate proxy may not support trailers",
759
              asciiString(TE_TRAILERS), te == null ? "<missing>" : asciiString(te)));
1✔
760
        return;
1✔
761
      }
762
      headerRemove(headerBlock, CONTENT_LENGTH);
1✔
763

764
      Metadata metadata = Utils.convertHeaders(headerBlock);
1✔
765
      StatsTraceContext statsTraceCtx =
1✔
766
          StatsTraceContext.newServerContext(config.streamTracerFactories, method, metadata);
1✔
767
      synchronized (lock) {
1✔
768
        OkHttpServerStream.TransportState stream = new OkHttpServerStream.TransportState(
1✔
769
            OkHttpServerTransport.this,
770
            streamId,
771
            config.maxInboundMessageSize,
1✔
772
            statsTraceCtx,
773
            lock,
1✔
774
            frameWriter,
1✔
775
            outboundFlow,
1✔
776
            config.flowControlWindow,
1✔
777
            tracer,
1✔
778
            method);
779
        OkHttpServerStream streamForApp = new OkHttpServerStream(
1✔
780
            stream,
781
            attributes,
1✔
782
            authority == null ? null : asciiString(authority),
1✔
783
            statsTraceCtx,
784
            tracer);
1✔
785
        if (streams.isEmpty()) {
1✔
786
          keepAliveEnforcer.onTransportActive();
1✔
787
          if (maxConnectionIdleManager != null) {
1✔
788
            maxConnectionIdleManager.onTransportActive();
1✔
789
          }
790
        }
791
        streams.put(streamId, stream);
1✔
792
        listener.streamCreated(streamForApp, method, metadata);
1✔
793
        stream.onStreamAllocated();
1✔
794
        if (inFinished) {
1✔
795
          stream.inboundDataReceived(new Buffer(), 0, inFinished);
1✔
796
        }
797
      }
1✔
798
    }
1✔
799

800
    private int headerBlockSize(List<Header> headerBlock) {
801
      // Calculate as defined for SETTINGS_MAX_HEADER_LIST_SIZE in RFC 7540 §6.5.2.
802
      long size = 0;
1✔
803
      for (int i = 0; i < headerBlock.size(); i++) {
1✔
804
        Header header = headerBlock.get(i);
1✔
805
        size += 32 + header.name.size() + header.value.size();
1✔
806
      }
807
      size = Math.min(size, Integer.MAX_VALUE);
1✔
808
      return (int) size;
1✔
809
    }
810

811
    /**
812
     * Handle an HTTP2 DATA frame.
813
     */
814
    @Override
815
    public void data(boolean inFinished, int streamId, BufferedSource in, int length)
816
        throws IOException {
817
      frameLogger.logData(
1✔
818
          OkHttpFrameLogger.Direction.INBOUND, streamId, in.getBuffer(), length, inFinished);
1✔
819
      if (streamId == 0) {
1✔
820
        connectionError(ErrorCode.PROTOCOL_ERROR,
1✔
821
            "Stream 0 is reserved for control messages. RFC7540 section 5.1.1");
822
        return;
1✔
823
      }
824
      if ((streamId & 1) == 0) {
1✔
825
        // The server doesn't use PUSH_PROMISE, so all even streams are IDLE
826
        connectionError(ErrorCode.PROTOCOL_ERROR,
1✔
827
            "Clients cannot open even numbered streams. RFC7540 section 5.1.1");
828
        return;
1✔
829
      }
830

831
      // Wait until the frame is complete. We only support 16 KiB frames, and the max permitted in
832
      // HTTP/2 is 16 MiB. This is verified in OkHttp's Http2 deframer, so we don't need to be
833
      // concerned with the window being exceeded at this point.
834
      in.require(length);
1✔
835

836
      synchronized (lock) {
1✔
837
        StreamState stream = streams.get(streamId);
1✔
838
        if (stream == null) {
1✔
839
          in.skip(length);
1✔
840
          streamError(streamId, ErrorCode.STREAM_CLOSED, "Received data for closed stream");
1✔
841
          return;
1✔
842
        }
843
        if (stream.hasReceivedEndOfStream()) {
1✔
844
          in.skip(length);
1✔
845
          streamError(streamId, ErrorCode.STREAM_CLOSED,
1✔
846
              "Received DATA for half-closed (remote) stream. RFC7540 section 5.1");
847
          return;
1✔
848
        }
849
        if (stream.inboundWindowAvailable() < length) {
1✔
850
          in.skip(length);
×
851
          streamError(streamId, ErrorCode.FLOW_CONTROL_ERROR,
×
852
              "Received DATA size exceeded window size. RFC7540 section 6.9");
853
          return;
×
854
        }
855
        Buffer buf = new Buffer();
1✔
856
        buf.write(in.getBuffer(), length);
1✔
857
        stream.inboundDataReceived(buf, length, inFinished);
1✔
858
      }
1✔
859

860
      // connection window update
861
      connectionUnacknowledgedBytesRead += length;
1✔
862
      if (connectionUnacknowledgedBytesRead
1✔
863
          >= config.flowControlWindow * Utils.DEFAULT_WINDOW_UPDATE_RATIO) {
1✔
864
        synchronized (lock) {
1✔
865
          frameWriter.windowUpdate(0, connectionUnacknowledgedBytesRead);
1✔
866
          frameWriter.flush();
1✔
867
        }
1✔
868
        connectionUnacknowledgedBytesRead = 0;
1✔
869
      }
870
    }
1✔
871

872
    @Override
873
    public void rstStream(int streamId, ErrorCode errorCode) {
874
      frameLogger.logRstStream(OkHttpFrameLogger.Direction.INBOUND, streamId, errorCode);
1✔
875
      // streamId == 0 checking is in HTTP/2 decoder
876

877
      if (!(ErrorCode.NO_ERROR.equals(errorCode)
1✔
878
            || ErrorCode.CANCEL.equals(errorCode)
1✔
879
            || ErrorCode.STREAM_CLOSED.equals(errorCode))) {
1✔
880
        log.log(Level.INFO, "Received RST_STREAM: " + errorCode);
×
881
      }
882
      Status status = GrpcUtil.Http2Error.statusForCode(errorCode.httpCode)
1✔
883
          .withDescription("RST_STREAM");
1✔
884
      synchronized (lock) {
1✔
885
        StreamState stream = streams.get(streamId);
1✔
886
        if (stream != null) {
1✔
887
          stream.inboundRstReceived(status);
1✔
888
          streamClosed(streamId, /*flush=*/ false);
1✔
889
        }
890
      }
1✔
891
    }
1✔
892

893
    @Override
894
    public void settings(boolean clearPrevious, Settings settings) {
895
      frameLogger.logSettings(OkHttpFrameLogger.Direction.INBOUND, settings);
1✔
896
      synchronized (lock) {
1✔
897
        boolean outboundWindowSizeIncreased = false;
1✔
898
        if (OkHttpSettingsUtil.isSet(settings, OkHttpSettingsUtil.INITIAL_WINDOW_SIZE)) {
1✔
899
          int initialWindowSize = OkHttpSettingsUtil.get(
1✔
900
              settings, OkHttpSettingsUtil.INITIAL_WINDOW_SIZE);
901
          outboundWindowSizeIncreased = outboundFlow.initialOutboundWindowSize(initialWindowSize);
1✔
902
        }
903

904
        // The changed settings are not finalized until SETTINGS acknowledgment frame is sent. Any
905
        // writes due to update in settings must be sent after SETTINGS acknowledgment frame,
906
        // otherwise it will cause a stream error (RST_STREAM).
907
        frameWriter.ackSettings(settings);
1✔
908
        frameWriter.flush();
1✔
909
        if (!receivedSettings) {
1✔
910
          receivedSettings = true;
1✔
911
          attributes = listener.transportReady(attributes);
1✔
912
        }
913

914
        // send any pending bytes / streams
915
        if (outboundWindowSizeIncreased) {
1✔
916
          outboundFlow.writeStreams();
1✔
917
        }
918
      }
1✔
919
    }
1✔
920

921
    @Override
922
    public void ping(boolean ack, int payload1, int payload2) {
923
      if (!keepAliveEnforcer.pingAcceptable()) {
1✔
924
        abruptShutdown(ErrorCode.ENHANCE_YOUR_CALM, "too_many_pings",
1✔
925
            Status.RESOURCE_EXHAUSTED.withDescription("Too many pings from client"), false);
1✔
926
        return;
1✔
927
      }
928
      long payload = (((long) payload1) << 32) | (payload2 & 0xffffffffL);
1✔
929
      if (!ack) {
1✔
930
        frameLogger.logPing(OkHttpFrameLogger.Direction.INBOUND, payload);
1✔
931
        synchronized (lock) {
1✔
932
          frameWriter.ping(true, payload1, payload2);
1✔
933
          frameWriter.flush();
1✔
934
        }
1✔
935
      } else {
936
        frameLogger.logPingAck(OkHttpFrameLogger.Direction.INBOUND, payload);
1✔
937
        if (KEEPALIVE_PING == payload) {
1✔
938
          return;
×
939
        }
940
        if (GRACEFUL_SHUTDOWN_PING == payload) {
1✔
941
          triggerGracefulSecondGoaway();
1✔
942
          return;
1✔
943
        }
944
        log.log(Level.INFO, "Received unexpected ping ack: " + payload);
×
945
      }
946
    }
1✔
947

948
    @Override
949
    public void ackSettings() {}
1✔
950

951
    @Override
952
    public void goAway(int lastGoodStreamId, ErrorCode errorCode, ByteString debugData) {
953
      frameLogger.logGoAway(
1✔
954
          OkHttpFrameLogger.Direction.INBOUND, lastGoodStreamId, errorCode, debugData);
955
      String description = String.format("Received GOAWAY: %s '%s'", errorCode, debugData.utf8());
1✔
956
      Status status = GrpcUtil.Http2Error.statusForCode(errorCode.httpCode)
1✔
957
          .withDescription(description);
1✔
958
      if (!ErrorCode.NO_ERROR.equals(errorCode)) {
1✔
959
        log.log(
×
960
            Level.WARNING, "Received GOAWAY: {0} {1}", new Object[] {errorCode, debugData.utf8()});
×
961
      }
962
      synchronized (lock) {
1✔
963
        goAwayStatus = status;
1✔
964
      }
1✔
965
    }
1✔
966

967
    @Override
968
    public void pushPromise(int streamId, int promisedStreamId, List<Header> requestHeaders)
969
        throws IOException {
970
      frameLogger.logPushPromise(OkHttpFrameLogger.Direction.INBOUND,
1✔
971
          streamId, promisedStreamId, requestHeaders);
972
      // streamId == 0 checking is in HTTP/2 decoder.
973
      // The server doesn't use PUSH_PROMISE, so all even streams are IDLE, and odd streams are not
974
      // peer-initiated.
975
      connectionError(ErrorCode.PROTOCOL_ERROR,
1✔
976
          "PUSH_PROMISE only allowed on peer-initiated streams. RFC7540 section 6.6");
977
    }
1✔
978

979
    @Override
980
    public void windowUpdate(int streamId, long delta) {
981
      frameLogger.logWindowsUpdate(OkHttpFrameLogger.Direction.INBOUND, streamId, delta);
1✔
982
      // delta == 0 checking is in HTTP/2 decoder. And it isn't quite right, as it will always cause
983
      // a GOAWAY. RFC7540 section 6.9 says to use RST_STREAM if the stream id isn't 0. Doesn't
984
      // matter much though.
985
      synchronized (lock) {
1✔
986
        if (streamId == Utils.CONNECTION_STREAM_ID) {
1✔
987
          outboundFlow.windowUpdate(null, (int) delta);
1✔
988
        } else {
989
          StreamState stream = streams.get(streamId);
1✔
990
          if (stream != null) {
1✔
991
            outboundFlow.windowUpdate(stream.getOutboundFlowState(), (int) delta);
1✔
992
          }
993
        }
994
      }
1✔
995
    }
1✔
996

997
    @Override
998
    public void priority(int streamId, int streamDependency, int weight, boolean exclusive) {
999
      frameLogger.logPriority(
1✔
1000
          OkHttpFrameLogger.Direction.INBOUND, streamId, streamDependency, weight, exclusive);
1001
      // streamId == 0 checking is in HTTP/2 decoder.
1002
      // Ignore priority change.
1003
    }
1✔
1004

1005
    @Override
1006
    public void alternateService(int streamId, String origin, ByteString protocol, String host,
1007
        int port, long maxAge) {}
×
1008

1009
    /**
1010
     * Send GOAWAY to the server, then finish all streams and close the transport. RFC7540 §5.4.1.
1011
     */
1012
    private void connectionError(ErrorCode errorCode, String moreDetail) {
1013
      Status status = GrpcUtil.Http2Error.statusForCode(errorCode.httpCode)
1✔
1014
          .withDescription(String.format("HTTP2 connection error: %s '%s'", errorCode, moreDetail));
1✔
1015
      abruptShutdown(errorCode, moreDetail, status, false);
1✔
1016
    }
1✔
1017

1018
    /**
1019
     * Respond with RST_STREAM, making sure to kill the associated stream if it exists. Reason will
1020
     * rarely be seen. RFC7540 §5.4.2.
1021
     */
1022
    private void streamError(int streamId, ErrorCode errorCode, String reason) {
1023
      if (errorCode == ErrorCode.PROTOCOL_ERROR) {
1✔
1024
        log.log(
1✔
1025
            Level.FINE, "Responding with RST_STREAM {0}: {1}", new Object[] {errorCode, reason});
1026
      }
1027
      synchronized (lock) {
1✔
1028
        frameWriter.rstStream(streamId, errorCode);
1✔
1029
        frameWriter.flush();
1✔
1030
        StreamState stream = streams.get(streamId);
1✔
1031
        if (stream != null) {
1✔
1032
          stream.transportReportStatus(
1✔
1033
              Status.INTERNAL.withDescription(
1✔
1034
                  String.format("Responded with RST_STREAM %s: %s", errorCode, reason)));
1✔
1035
          streamClosed(streamId, /*flush=*/ false);
1✔
1036
        }
1037
      }
1✔
1038
    }
1✔
1039

1040
    private void respondWithHttpError(
1041
        int streamId, boolean inFinished, int httpCode, Status.Code statusCode, String msg) {
1042
      Metadata metadata = new Metadata();
1✔
1043
      metadata.put(InternalStatus.CODE_KEY, statusCode.toStatus());
1✔
1044
      metadata.put(InternalStatus.MESSAGE_KEY, msg);
1✔
1045
      List<Header> headers =
1✔
1046
          Headers.createHttpResponseHeaders(httpCode, "text/plain; charset=utf-8", metadata);
1✔
1047
      Buffer data = new Buffer().writeUtf8(msg);
1✔
1048

1049
      synchronized (lock) {
1✔
1050
        Http2ErrorStreamState stream =
1✔
1051
            new Http2ErrorStreamState(streamId, lock, outboundFlow, config.flowControlWindow);
1✔
1052
        if (streams.isEmpty()) {
1✔
1053
          keepAliveEnforcer.onTransportActive();
1✔
1054
          if (maxConnectionIdleManager != null) {
1✔
1055
            maxConnectionIdleManager.onTransportActive();
1✔
1056
          }
1057
        }
1058
        streams.put(streamId, stream);
1✔
1059
        if (inFinished) {
1✔
1060
          stream.inboundDataReceived(new Buffer(), 0, true);
×
1061
        }
1062
        frameWriter.headers(streamId, headers);
1✔
1063
        outboundFlow.data(
1✔
1064
            /*outFinished=*/true, stream.getOutboundFlowState(), data, /*flush=*/true);
1✔
1065
        outboundFlow.notifyWhenNoPendingData(
1✔
1066
            stream.getOutboundFlowState(), () -> rstOkAtEndOfHttpError(stream));
1✔
1067
      }
1✔
1068
    }
1✔
1069

1070
    private void rstOkAtEndOfHttpError(Http2ErrorStreamState stream) {
1071
      synchronized (lock) {
1✔
1072
        if (!stream.hasReceivedEndOfStream()) {
1✔
1073
          frameWriter.rstStream(stream.streamId, ErrorCode.NO_ERROR);
1✔
1074
        }
1075
        streamClosed(stream.streamId, /*flush=*/ true);
1✔
1076
      }
1✔
1077
    }
1✔
1078

1079
    private void respondWithGrpcError(
1080
        int streamId, boolean inFinished, Status.Code statusCode, String msg) {
1081
      Metadata metadata = new Metadata();
1✔
1082
      metadata.put(InternalStatus.CODE_KEY, statusCode.toStatus());
1✔
1083
      metadata.put(InternalStatus.MESSAGE_KEY, msg);
1✔
1084
      List<Header> headers = Headers.createResponseTrailers(metadata, false);
1✔
1085

1086
      synchronized (lock) {
1✔
1087
        frameWriter.synReply(true, streamId, headers);
1✔
1088
        if (!inFinished) {
1✔
1089
          frameWriter.rstStream(streamId, ErrorCode.NO_ERROR);
1✔
1090
        }
1091
        frameWriter.flush();
1✔
1092
      }
1✔
1093
    }
1✔
1094
  }
1095

1096
  private final class KeepAlivePinger implements KeepAliveManager.KeepAlivePinger {
1✔
1097
    @Override
1098
    public void ping() {
1099
      synchronized (lock) {
×
1100
        frameWriter.ping(false, 0, KEEPALIVE_PING);
×
1101
        frameWriter.flush();
×
1102
      }
×
1103
      tracer.reportKeepAliveSent();
×
1104
    }
×
1105

1106
    @Override
1107
    public void onPingTimeout() {
1108
      synchronized (lock) {
×
1109
        goAwayStatus = Status.UNAVAILABLE
×
1110
            .withDescription("Keepalive failed. Considering connection dead");
×
1111
        GrpcUtil.closeQuietly(bareSocket);
×
1112
      }
×
1113
    }
×
1114
  }
1115

1116
  interface StreamState {
1117
    /** Must be holding 'lock' when calling. */
1118
    void inboundDataReceived(Buffer frame, int windowConsumed, boolean endOfStream);
1119

1120
    /** Must be holding 'lock' when calling. */
1121
    boolean hasReceivedEndOfStream();
1122

1123
    /** Must be holding 'lock' when calling. */
1124
    int inboundWindowAvailable();
1125

1126
    /** Must be holding 'lock' when calling. */
1127
    void transportReportStatus(Status status);
1128

1129
    /** Must be holding 'lock' when calling. */
1130
    void inboundRstReceived(Status status);
1131

1132
    OutboundFlowController.StreamState getOutboundFlowState();
1133
  }
1134

1135
  static class Http2ErrorStreamState implements StreamState, OutboundFlowController.Stream {
1136
    private final int streamId;
1137
    private final Object lock;
1138
    private final OutboundFlowController.StreamState outboundFlowState;
1139
    @GuardedBy("lock")
1140
    private int window;
1141
    @GuardedBy("lock")
1142
    private boolean receivedEndOfStream;
1143

1144
    Http2ErrorStreamState(
1145
        int streamId, Object lock, OutboundFlowController outboundFlow, int initialWindowSize) {
1✔
1146
      this.streamId = streamId;
1✔
1147
      this.lock = lock;
1✔
1148
      this.outboundFlowState = outboundFlow.createState(this, streamId);
1✔
1149
      this.window = initialWindowSize;
1✔
1150
    }
1✔
1151

1152
    @Override public void onSentBytes(int frameBytes) {}
1✔
1153

1154
    @Override public void inboundDataReceived(
1155
        Buffer frame, int windowConsumed, boolean endOfStream) {
1156
      synchronized (lock) {
×
1157
        if (endOfStream) {
×
1158
          receivedEndOfStream = true;
×
1159
        }
1160
        window -= windowConsumed;
×
1161
        try {
1162
          frame.skip(frame.size()); // Recycle segments
×
1163
        } catch (IOException ex) {
×
1164
          throw new AssertionError(ex);
×
1165
        }
×
1166
      }
×
1167
    }
×
1168

1169
    @Override public boolean hasReceivedEndOfStream() {
1170
      synchronized (lock) {
1✔
1171
        return receivedEndOfStream;
1✔
1172
      }
1173
    }
1174

1175
    @Override public int inboundWindowAvailable() {
1176
      synchronized (lock) {
×
1177
        return window;
×
1178
      }
1179
    }
1180

1181
    @Override public void transportReportStatus(Status status) {}
×
1182

1183
    @Override public void inboundRstReceived(Status status) {}
×
1184

1185
    @Override public OutboundFlowController.StreamState getOutboundFlowState() {
1186
      synchronized (lock) {
1✔
1187
        return outboundFlowState;
1✔
1188
      }
1189
    }
1190
  }
1191
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc