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

grpc / grpc-java / #20515

09 Oct 2026 12:45PM UTC coverage: 89.353% (-0.03%) from 89.382%
#20515

push

github

web-flow
Revert "core: Delayed deserialization for unary/server-streaming calls (#13004) (#13107)

This reverts commit 8ba4b4872 because
this change breaks grpc-kotlin tests that use InProcessTransport by
causing a deadlock because
[ServerCalls.kt](https://github.com/grpc/grpc-kotlin/blob/master/stub/src/main/java/io/grpc/kotlin/ServerCalls.kt#L214-L215)
only requests the next message after `onMessage` delivers the current
one, and messages get queued because the client hasn't called
`halfClose` yet. When the client halfCloses,
`InProcessTransport.halfClose`
[defers](https://github.com/grpc/grpc-java/blob/master/inprocess/src/main/java/io/grpc/inprocess/InProcessTransport.java#L904)
delivering halfClose if the server's receive queue is non-empty.

**Resulting Deadlock:**
- `ServerCallImpl` waits for `halfClosed()` before dispatching Message
1.
- `InProcessTransport` waits for `call.request(1)` before dispatching
`halfClosed()`.
  - The server waits for Message 1 before calling `call.request(1)`.
- The test hangs indefinitely waiting for `closeStatus.await()` until
the 10s test timeout expires.

There are a few other failures too but those can be fixed in the test
code alone.

Internal Test failures: http://shortn/_If0NinnwQ4

39216 of 43889 relevant lines covered (89.35%)

0.89 hits per line

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

96.49
/../core/src/main/java/io/grpc/internal/ServerCallImpl.java
1
/*
2
 * Copyright 2015 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.internal;
18

19
import static com.google.common.base.Preconditions.checkArgument;
20
import static com.google.common.base.Preconditions.checkNotNull;
21
import static com.google.common.base.Preconditions.checkState;
22
import static io.grpc.internal.GrpcAttributes.ATTR_SECURITY_LEVEL;
23
import static io.grpc.internal.GrpcUtil.ACCEPT_ENCODING_SPLITTER;
24
import static io.grpc.internal.GrpcUtil.CONTENT_LENGTH_KEY;
25
import static io.grpc.internal.GrpcUtil.MESSAGE_ACCEPT_ENCODING_KEY;
26
import static io.grpc.internal.GrpcUtil.MESSAGE_ENCODING_KEY;
27

28
import com.google.common.annotations.VisibleForTesting;
29
import com.google.common.base.Throwables;
30
import com.google.common.util.concurrent.MoreExecutors;
31
import io.grpc.Attributes;
32
import io.grpc.Codec;
33
import io.grpc.Compressor;
34
import io.grpc.CompressorRegistry;
35
import io.grpc.Context;
36
import io.grpc.DecompressorRegistry;
37
import io.grpc.InternalDecompressorRegistry;
38
import io.grpc.InternalStatus;
39
import io.grpc.Metadata;
40
import io.grpc.MethodDescriptor;
41
import io.grpc.SecurityLevel;
42
import io.grpc.ServerCall;
43
import io.grpc.Status;
44
import io.grpc.StatusRuntimeException;
45
import io.perfmark.PerfMark;
46
import io.perfmark.Tag;
47
import io.perfmark.TaskCloseable;
48
import java.io.InputStream;
49
import java.util.logging.Level;
50
import java.util.logging.Logger;
51

52
final class ServerCallImpl<ReqT, RespT> extends ServerCall<ReqT, RespT> {
53

54
  private static final Logger log = Logger.getLogger(ServerCallImpl.class.getName());
1 ✔
55

56
  @VisibleForTesting
57
  static final String TOO_MANY_RESPONSES = "Too many responses";
58
  @VisibleForTesting
59
  static final String MISSING_RESPONSE = "Completed without a response";
60

61
  private final ServerStream stream;
62
  private final MethodDescriptor<ReqT, RespT> method;
63
  private final Tag tag;
64
  private final Context.CancellableContext context;
65
  private final byte[] messageAcceptEncoding;
66
  private final DecompressorRegistry decompressorRegistry;
67
  private final CompressorRegistry compressorRegistry;
68
  private CallTracer serverCallTracer;
69

70
  // state
71
  private volatile boolean cancelled;
72
  private boolean sendHeadersCalled;
73
  private boolean closeCalled;
74
  private Compressor compressor;
75
  private boolean messageSent;
76

77
  ServerCallImpl(ServerStream stream, MethodDescriptor<ReqT, RespT> method,
78
      Metadata inboundHeaders, Context.CancellableContext context,
79
      DecompressorRegistry decompressorRegistry, CompressorRegistry compressorRegistry,
80
      CallTracer serverCallTracer, Tag tag) {
1 ✔
81
    this.stream = stream;
1 ✔
82
    this.method = method;
1 ✔
83
    this.context = context;
1 ✔
84
    this.messageAcceptEncoding = inboundHeaders.get(MESSAGE_ACCEPT_ENCODING_KEY);
1 ✔
85
    this.decompressorRegistry = decompressorRegistry;
1 ✔
86
    this.compressorRegistry = compressorRegistry;
1 ✔
87
    this.serverCallTracer = serverCallTracer;
1 ✔
88
    this.serverCallTracer.reportCallStarted();
1 ✔
89
    this.tag = tag;
1 ✔
90
  }
1 ✔
91

92
  @Override
93
  public void request(int numMessages) {
94
    try (TaskCloseable ignore = PerfMark.traceTask("ServerCall.request")) {
1 ✔
95
      PerfMark.attachTag(tag);
1 ✔
96
      stream.request(numMessages);
1 ✔
97
    }
98
  }
1 ✔
99

100
  @Override
101
  public void sendHeaders(Metadata headers) {
102
    try (TaskCloseable ignore = PerfMark.traceTask("ServerCall.sendHeaders")) {
1 ✔
103
      PerfMark.attachTag(tag);
1 ✔
104
      sendHeadersInternal(headers);
1 ✔
105
    }
106
  }
1 ✔
107

108
  private void sendHeadersInternal(Metadata headers) {
109
    checkState(!sendHeadersCalled, "sendHeaders has already been called");
1 ✔
110
    checkState(!closeCalled, "call is closed");
1 ✔
111

112
    headers.discardAll(CONTENT_LENGTH_KEY);
1 ✔
113
    headers.discardAll(MESSAGE_ENCODING_KEY);
1 ✔
114
    if (compressor == null) {
1 ✔
115
      compressor = Codec.Identity.NONE;
1 ✔
116
    } else {
117
      if (messageAcceptEncoding != null) {
1 ✔
118
        // TODO(carl-mastrangelo): remove the string allocation.
119
        if (!GrpcUtil.iterableContains(
1 ✔
120
            ACCEPT_ENCODING_SPLITTER.split(new String(messageAcceptEncoding, GrpcUtil.US_ASCII)),
1 ✔
121
            compressor.getMessageEncoding())) {
1 ✔
122
          // resort to using no compression.
123
          compressor = Codec.Identity.NONE;
1 ✔
124
        }
125
      } else {
126
        compressor = Codec.Identity.NONE;
1 ✔
127
      }
128
    }
129

130
    // Always put compressor, even if it's identity.
131
    headers.put(MESSAGE_ENCODING_KEY, compressor.getMessageEncoding());
1 ✔
132

133
    stream.setCompressor(compressor);
1 ✔
134

135
    headers.discardAll(MESSAGE_ACCEPT_ENCODING_KEY);
1 ✔
136
    byte[] advertisedEncodings =
1 ✔
137
        InternalDecompressorRegistry.getRawAdvertisedMessageEncodings(decompressorRegistry);
1 ✔
138
    if (advertisedEncodings.length != 0) {
1 ✔
139
      headers.put(MESSAGE_ACCEPT_ENCODING_KEY, advertisedEncodings);
1 ✔
140
    }
141

142
    // Don't check if sendMessage has been called, since it requires that sendHeaders was already
143
    // called.
144
    sendHeadersCalled = true;
1 ✔
145
    stream.writeHeaders(headers, !getMethodDescriptor().getType().serverSendsOneMessage());
1 ✔
146
  }
1 ✔
147

148
  @Override
149
  public void sendMessage(RespT message) {
150
    try (TaskCloseable ignore = PerfMark.traceTask("ServerCall.sendMessage")) {
1 ✔
151
      PerfMark.attachTag(tag);
1 ✔
152
      sendMessageInternal(message);
1 ✔
153
    }
154
  }
1 ✔
155

156
  private void sendMessageInternal(RespT message) {
157
    checkState(sendHeadersCalled, "sendHeaders has not been called");
1 ✔
158
    checkState(!closeCalled, "call is closed");
1 ✔
159

160
    if (method.getType().serverSendsOneMessage() && messageSent) {
1 ✔
161
      handleInternalError(Status.INTERNAL.withDescription(TOO_MANY_RESPONSES).asRuntimeException());
1 ✔
162
      return;
1 ✔
163
    }
164

165
    messageSent = true;
1 ✔
166
    try {
167
      InputStream resp = method.streamResponse(message);
1 ✔
168
      stream.writeMessage(resp);
1 ✔
169
      if (!getMethodDescriptor().getType().serverSendsOneMessage()) {
1 ✔
170
        stream.flush();
1 ✔
171
      }
172
    } catch (RuntimeException e) {
1 ✔
173
      handleInternalError(e);
1 ✔
174
    } catch (Error e) {
×
175
      close(
×
176
          Status.CANCELLED.withDescription("Server sendMessage() failed with Error"),
×
177
          new Metadata());
178
      throw e;
×
179
    }
1 ✔
180
  }
1 ✔
181

182
  @Override
183
  public void setMessageCompression(boolean enable) {
184
    stream.setMessageCompression(enable);
1 ✔
185
  }
1 ✔
186

187
  @Override
188
  public void setOnReadyThreshold(int numBytes) {
189
    stream.setOnReadyThreshold(numBytes);
1 ✔
190
  }
1 ✔
191

192
  @Override
193
  public void setCompression(String compressorName) {
194
    // Added here to give a better error message.
195
    checkState(!sendHeadersCalled, "sendHeaders has been called");
1 ✔
196

197
    compressor = compressorRegistry.lookupCompressor(compressorName);
1 ✔
198
    checkArgument(compressor != null, "Unable to find compressor by name %s", compressorName);
1 ✔
199
  }
1 ✔
200

201
  @Override
202
  public boolean isReady() {
203
    if (closeCalled) {
1 ✔
204
      return false;
1 ✔
205
    }
206
    return stream.isReady();
1 ✔
207
  }
208

209
  @Override
210
  public void close(Status status, Metadata trailers) {
211
    try (TaskCloseable ignore = PerfMark.traceTask("ServerCall.close")) {
1 ✔
212
      PerfMark.attachTag(tag);
1 ✔
213
      closeInternal(status, trailers);
1 ✔
214
    }
215
  }
1 ✔
216

217
  private void closeInternal(Status status, Metadata trailers) {
218
    checkState(!closeCalled, "call already closed");
1 ✔
219
    try {
220
      closeCalled = true;
1 ✔
221

222
      if (status.isOk() && method.getType().serverSendsOneMessage() && !messageSent) {
1 ✔
223
        handleInternalError(Status.INTERNAL.withDescription(MISSING_RESPONSE).asRuntimeException());
1 ✔
224
        return;
1 ✔
225
      }
226

227
      stream.close(status, trailers);
1 ✔
228
    } finally {
229
      serverCallTracer.reportCallEnded(status.isOk());
1 ✔
230
    }
231
  }
1 ✔
232

233
  @Override
234
  public boolean isCancelled() {
235
    return cancelled;
1 ✔
236
  }
237

238
  ServerStreamListener newServerStreamListener(ServerCall.Listener<ReqT> listener) {
239
    return new ServerStreamListenerImpl<>(this, listener, context);
1 ✔
240
  }
241

242
  @Override
243
  public Attributes getAttributes() {
244
    return stream.getAttributes();
1 ✔
245
  }
246

247
  @Override
248
  public String getAuthority() {
249
    return stream.getAuthority();
1 ✔
250
  }
251

252
  @Override
253
  public MethodDescriptor<ReqT, RespT> getMethodDescriptor() {
254
    return method;
1 ✔
255
  }
256

257
  @Override
258
  public void triggerEvent(Object event) {
259
    try (TaskCloseable ignore = PerfMark.traceTask("ServerCall.triggerEvent")) {
1 ✔
260
      PerfMark.attachTag(tag);
1 ✔
261
      stream.triggerEvent(event);
1 ✔
262
    }
263
  }
1 ✔
264

265
  @Override
266
  public SecurityLevel getSecurityLevel() {
267
    final Attributes attributes = getAttributes();
1 ✔
268
    if (attributes == null) {
1 ✔
269
      return super.getSecurityLevel();
1 ✔
270
    }
271
    final SecurityLevel securityLevel = attributes.get(ATTR_SECURITY_LEVEL);
1 ✔
272
    return securityLevel == null ? super.getSecurityLevel() : securityLevel;
1 ✔
273
  }
274

275
  /**
276
   * Close the {@link ServerStream} because an internal error occurred. Allow the application to
277
   * run until completion, but silently ignore interactions with the {@link ServerStream} from now
278
   * on.
279
   */
280
  private void handleInternalError(Throwable internalError) {
281
    log.log(Level.WARNING, "Cancelling the stream because of internal error", internalError);
1 ✔
282
    Status status = (internalError instanceof StatusRuntimeException)
1 ✔
283
        ? ((StatusRuntimeException) internalError).getStatus()
1 ✔
284
        : Status.INTERNAL.withCause(internalError)
1 ✔
285
            .withDescription("Internal error so cancelling stream.");
1 ✔
286
    stream.cancel(status);
1 ✔
287
    serverCallTracer.reportCallEnded(false); // error so always false
1 ✔
288
  }
1 ✔
289

290
  /**
291
   * All of these callbacks are assumed to called on an application thread, and the caller is
292
   * responsible for handling thrown exceptions.
293
   */
294
  @VisibleForTesting
295
  static final class ServerStreamListenerImpl<ReqT> implements ServerStreamListener {
296
    private final ServerCallImpl<ReqT, ?> call;
297
    private final ServerCall.Listener<ReqT> listener;
298
    private final Context.CancellableContext context;
299

300
    public ServerStreamListenerImpl(
301
        ServerCallImpl<ReqT, ?> call, ServerCall.Listener<ReqT> listener,
302
        Context.CancellableContext context) {
1 ✔
303
      this.call = checkNotNull(call, "call");
1 ✔
304
      this.listener = checkNotNull(listener, "listener must not be null");
1 ✔
305
      this.context = checkNotNull(context, "context");
1 ✔
306
      // Wire ourselves up so that if the context is cancelled, our flag call.cancelled also
307
      // reflects the new state. Use a DirectExecutor so that it happens in the same thread
308
      // as the caller of {@link Context#cancel}.
309
      this.context.addListener(
1 ✔
310
          new Context.CancellationListener() {
1 ✔
311
            @Override
312
            public void cancelled(Context context) {
313
              // If the context has a cancellation cause then something exceptional happened
314
              // and we should also mark the call as cancelled.
315
              if (context.cancellationCause() != null) {
1 ✔
316
                ServerStreamListenerImpl.this.call.cancelled = true;
1 ✔
317
              }
318
            }
1 ✔
319
          },
320
          MoreExecutors.directExecutor());
1 ✔
321
    }
1 ✔
322

323
    @Override
324
    public void messagesAvailable(MessageProducer producer) {
325
      try (TaskCloseable ignore = PerfMark.traceTask("ServerStreamListener.messagesAvailable")) {
1 ✔
326
        PerfMark.attachTag(call.tag);
1 ✔
327
        messagesAvailableInternal(producer);
1 ✔
328
      }
329
    }
1 ✔
330

331
    @SuppressWarnings("Finally") // The code avoids suppressing the exception thrown from try
332
    private void messagesAvailableInternal(final MessageProducer producer) {
333
      if (call.cancelled) {
1 ✔
334
        GrpcUtil.closeQuietly(producer);
1 ✔
335
        return;
1 ✔
336
      }
337

338
      InputStream message;
339
      try {
340
        while ((message = producer.next()) != null) {
1 ✔
341
          try {
342
            listener.onMessage(call.method.parseRequest(message));
1 ✔
343
          } catch (Throwable t) {
1 ✔
344
            GrpcUtil.closeQuietly(message);
1 ✔
345
            throw t;
1 ✔
346
          }
1 ✔
347
          message.close();
1 ✔
348
        }
349
      } catch (Throwable t) {
1 ✔
350
        GrpcUtil.closeQuietly(producer);
1 ✔
351
        Throwables.throwIfUnchecked(t);
×
352
        throw new RuntimeException(t);
×
353
      }
1 ✔
354
    }
1 ✔
355

356
    @Override
357
    public void halfClosed() {
358
      try (TaskCloseable ignore = PerfMark.traceTask("ServerStreamListener.halfClosed")) {
1 ✔
359
        PerfMark.attachTag(call.tag);
1 ✔
360
        if (call.cancelled) {
1 ✔
361
          return;
1 ✔
362
        }
363

364
        listener.onHalfClose();
1 ✔
365
      }
366
    }
1 ✔
367

368
    @Override
369
    public void closed(Status status) {
370
      try (TaskCloseable ignore = PerfMark.traceTask("ServerStreamListener.closed")) {
1 ✔
371
        PerfMark.attachTag(call.tag);
1 ✔
372
        closedInternal(status);
1 ✔
373
      }
374
    }
1 ✔
375

376
    private void closedInternal(Status status) {
377
      Throwable cancelCause = null;
1 ✔
378
      try {
379
        if (status.isOk()) {
1 ✔
380
          listener.onComplete();
1 ✔
381
        } else {
382
          call.cancelled = true;
1 ✔
383
          listener.onCancel();
1 ✔
384
          // The status will not have a cause in all failure scenarios, but we want to make sure
385
          // we always cancel the context with one to keep the context cancelled state consistent.
386
          cancelCause = InternalStatus.asRuntimeExceptionWithoutStacktrace(
1 ✔
387
              Status.CANCELLED.withDescription("RPC cancelled"), null);
1 ✔
388
        }
389
      } finally {
390
        // Cancel context after delivering RPC closure notification to allow the application to
391
        // clean up and update any state based on whether onComplete or onCancel was called.
392
        context.cancel(cancelCause);
1 ✔
393
      }
394
    }
1 ✔
395

396
    @Override
397
    public void onReady() {
398
      try (TaskCloseable ignore = PerfMark.traceTask("ServerStreamListener.onReady")) {
1 ✔
399
        PerfMark.attachTag(call.tag);
1 ✔
400
        if (call.cancelled) {
1 ✔
401
          return;
1 ✔
402
        }
403
        listener.onReady();
1 ✔
404
      }
405
    }
1 ✔
406

407
    @Override
408
    public void triggerEvent(Object event) {
409
      try (TaskCloseable ignore = PerfMark.traceTask("ServerStreamListener.triggerEvent")) {
1 ✔
410
        PerfMark.attachTag(call.tag);
1 ✔
411
        if (call.cancelled) {
1 ✔
412
          return;
1 ✔
413
        }
414
        listener.onEvent(event);
1 ✔
415
      }
416
    }
1 ✔
417
  }
418
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc