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

grpc / grpc-java / #20469

10 Sep 2026 08:17AM UTC coverage: 89.337% (+0.06%) from 89.279%
#20469

push

github

web-flow
api: Implement custom events framework in gRPC-Java server (#12980)

This adds triggerEvent/onEvent APIs to `ServerCall` and `ServerCall.Listener` routing them through `ServerStream` transport.

39067 of 43730 relevant lines covered (89.34%)

0.89 hits per line

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

76.47
/../api/src/main/java/io/grpc/ServerCall.java
1
/*
2
 * Copyright 2014 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;
18

19
import static com.google.common.base.Preconditions.checkArgument;
20

21
import javax.annotation.Nullable;
22

23
/**
24
 * Encapsulates a single call received from a remote client. Calls may not simply be unary
25
 * request-response even though this is the most common pattern. Calls may stream any number of
26
 * requests and responses. This API is generally intended for use by generated handlers,
27
 * but applications may use it directly if they need to.
28
 *
29
 * <p>Headers must be sent before any messages, which must be sent before closing.
30
 *
31
 * <p>No generic method for determining message receipt or providing acknowledgement is provided.
32
 * Applications are expected to utilize normal messages for such signals, as a response
33
 * naturally acknowledges its request.
34
 *
35
 * <p>Methods are guaranteed to be non-blocking. Implementations are not required to be thread-safe.
36
 *
37
 * <p>DO NOT MOCK: Use InProcessTransport and make a fake server instead.
38
 *
39
 * @param <ReqT> parsed type of request message.
40
 * @param <RespT> parsed type of response message.
41
 */
42
public abstract class ServerCall<ReqT, RespT> {
1✔
43

44
  /**
45
   * Callbacks for consuming incoming RPC messages.
46
   *
47
   * <p>Any contexts are guaranteed to arrive before any messages, which are guaranteed before half
48
   * close, which is guaranteed before completion.
49
   *
50
   * <p>Implementations are free to block for extended periods of time. Implementations are not
51
   * required to be thread-safe, but they must not be thread-hostile. The caller is free to call
52
   * an instance from multiple threads, but only one call simultaneously. A single thread may
53
   * interleave calls to multiple instances, so implementations using ThreadLocals must be careful
54
   * to avoid leaking inappropriate state (e.g., clearing the ThreadLocal before returning).
55
   */
56
  // TODO(ejona86): We need to decide what to do in the case of server closing with non-cancellation
57
  // before client half closes. It may be that we treat such a case as an error. If we permit such
58
  // a case then we either get to generate a half close or purposefully omit it.
59
  public abstract static class Listener<ReqT> {
1✔
60
    /**
61
     * A request message has been received. For streaming calls, there may be zero or more request
62
     * messages.
63
     *
64
     * @param message a received request message.
65
     */
66
    public void onMessage(ReqT message) {}
1✔
67

68
    /**
69
     * The client completed all message sending. However, the call may still be cancelled.
70
     */
71
    public void onHalfClose() {}
1✔
72

73
    /**
74
     * The call was cancelled and the server is encouraged to abort processing to save resources,
75
     * since the client will not process any further messages. Cancellations can be caused by
76
     * timeouts, explicit cancellation by the client, network errors, etc.
77
     *
78
     * <p>There will be no further callbacks for the call.
79
     */
80
    public void onCancel() {}
1✔
81

82
    /**
83
     * The call is considered complete and {@link #onCancel} is guaranteed not to be called.
84
     * However, the client is not guaranteed to have received all messages.
85
     *
86
     * <p>There will be no further callbacks for the call.
87
     */
88
    public void onComplete() {}
1✔
89

90
    /**
91
     * This indicates that the call may now be capable of sending additional messages (via
92
     * {@link #sendMessage}) without requiring excessive buffering internally. This event is
93
     * just a suggestion and the application is free to ignore it, however doing so may
94
     * result in excessive buffering within the call.
95
     *
96
     * <p>Because there is a processing delay to deliver this notification, it is possible for
97
     * concurrent writes to cause {@code isReady() == false} within this callback. Handle "spurious"
98
     * notifications by checking {@code isReady()}'s current value instead of assuming it is now
99
     * {@code true}. If {@code isReady() == false} the normal expectations apply, so there would be
100
     * <em>another</em> {@code onReady()} callback.
101
     */
102
    public void onReady() {}
1✔
103

104
    /**
105
     * A custom event has been triggered by the call.
106
     *
107
     * <p>This callback is guaranteed to run on the call's executor, serialized with other
108
     * callbacks (like {@link #onMessage}, {@link #onHalfClose}). This means the implementation
109
     * does not need internal synchronization to access call-specific state.
110
     *
111
     * <p><strong>Deadlock avoidance:</strong> In some transports (such as Binder transport)
112
     * or when using a direct executor, this callback may be invoked while transport-level
113
     * locks are held. Implementations should avoid acquiring locks that are held by callers of
114
     * {@link ServerCall} methods (such as {@link ServerCall#triggerEvent},
115
     * {@link ServerCall#close}, or {@link ServerCall#request}), and should avoid calling
116
     * {@link ServerCall} methods while holding application-level locks, as this can lead to
117
     * deadlocks from lock-order inversion.
118
     *
119
     * @param event the triggered event.
120
     */
121
    @ExperimentalApi("https://github.com/grpc/grpc-java/issues/12979")
122
    public void onEvent(Object event) {
123
      // Default no-op
124
    }
1✔
125
  }
126

127
  /**
128
   * Requests up to the given number of messages from the call to be delivered to
129
   * {@link Listener#onMessage(Object)}. Once {@code numMessages} have been delivered
130
   * no further request messages will be delivered until more messages are requested by
131
   * calling this method again.
132
   *
133
   * <p>Servers use this mechanism to provide back-pressure to the client for flow-control.
134
   *
135
   * <p>This method is safe to call from multiple threads without external synchronization.
136
   *
137
   * @param numMessages the requested number of messages to be delivered to the listener.
138
   */
139
  public abstract void request(int numMessages);
140

141
  /**
142
   * Send response header metadata prior to sending a response message. This method may
143
   * only be called once and cannot be called after calls to {@link #sendMessage} or {@link #close}.
144
   *
145
   * <p>Since {@link Metadata} is not thread-safe, the caller must not access (read or write) {@code
146
   * headers} after this point.
147
   *
148
   * @param headers metadata to send prior to any response body.
149
   * @throws IllegalStateException if {@code close} has been called, a message has been sent, or
150
   *     headers have already been sent
151
   */
152
  public abstract void sendHeaders(Metadata headers);
153

154
  /**
155
   * Send a response message. Messages are the primary form of communication associated with
156
   * RPCs. Multiple response messages may exist for streaming calls.
157
   *
158
   * @param message response message.
159
   * @throws IllegalStateException if headers not sent or call is {@link #close}d
160
   */
161
  public abstract void sendMessage(RespT message);
162

163
  /**
164
   * If {@code true}, indicates that the call is capable of sending additional messages
165
   * without requiring excessive buffering internally. This event is
166
   * just a suggestion and the application is free to ignore it, however doing so may
167
   * result in excessive buffering within the call.
168
   *
169
   * <p>If {@code false}, {@link Listener#onReady()} will be called after {@code isReady()}
170
   * transitions to {@code true}.
171
   *
172
   * <p>This abstract class's implementation always returns {@code true}. Implementations generally
173
   * override the method.
174
   */
175
  public boolean isReady() {
176
    return true;
×
177
  }
178

179
  /**
180
   * Close the call with the provided status. No further sending or receiving will occur. If {@link
181
   * Status#isOk} is {@code false}, then the call is said to have failed.
182
   *
183
   * <p>If no errors or cancellations are known to have occurred, then a {@link Listener#onComplete}
184
   * notification should be expected, independent of {@code status}. Otherwise {@link
185
   * Listener#onCancel} has been or will be called.
186
   *
187
   * <p>Since {@link Metadata} is not thread-safe, the caller must not access (read or write) {@code
188
   * trailers} after this point.
189
   *
190
   * <p>This method implies the caller completed processing the RPC, but it does not imply the RPC
191
   * is complete. The call implementation will need additional time to complete the RPC and during
192
   * this time the client is still able to cancel the request or a network error might cause the
193
   * RPC to fail. If you wish to know when the call is actually completed/closed, you have to use
194
   * {@link Listener#onComplete} or {@link Listener#onCancel} instead. This method is not
195
   * necessarily invoked when Listener.onCancel() is called.
196
   *
197
   * @throws IllegalStateException if call is already {@code close}d
198
   */
199
  public abstract void close(Status status, Metadata trailers);
200

201
  /**
202
   * Returns {@code true} when the call is cancelled and the server is encouraged to abort
203
   * processing to save resources, since the client will not be processing any further methods.
204
   * Cancellations can be caused by timeouts, explicit cancel by client, network errors, and
205
   * similar.
206
   *
207
   * <p>This method may safely be called concurrently from multiple threads.
208
   */
209
  public abstract boolean isCancelled();
210

211
  /**
212
   * Enables per-message compression, if an encoding type has been negotiated.  If no message
213
   * encoding has been negotiated, this is a no-op. By default per-message compression is enabled,
214
   * but may not have any effect if compression is not enabled on the call.
215
   */
216
  public void setMessageCompression(boolean enabled) {
217
    // noop
218
  }
×
219

220
  /**
221
   * Sets the compression algorithm for this call.  This compression is utilized for sending.  If
222
   * the server does not support the compression algorithm, the call will fail.  This method may
223
   * only be called before {@link #sendHeaders}.  The compressor to use will be looked up in the
224
   * {@link CompressorRegistry}.  Default gRPC servers support the "gzip" compressor.
225
   *
226
   * <p>It is safe to call this even if the client does not support the compression format chosen.
227
   * The implementation will handle negotiation with the client and may fall back to no compression.
228
   *
229
   * @param compressor the name of the compressor to use.
230
   * @throws IllegalArgumentException if the compressor name can not be found.
231
   */
232
  public void setCompression(String compressor) {
233
    // noop
234
  }
×
235

236
  /**
237
   * A hint to the call that specifies how many bytes must be queued before
238
   * {@link #isReady()} will return false. A call may ignore this property if
239
   * unsupported. This may only be set before any messages are sent.
240
   *
241
   * @param numBytes The number of bytes that must be queued. Must be a
242
   *                 positive integer.
243
   */
244
  @ExperimentalApi("https://github.com/grpc/grpc-java/issues/11021")
245
  public void setOnReadyThreshold(int numBytes) {
246
    checkArgument(numBytes > 0, "numBytes must be positive: %s", numBytes);
1✔
247
  }
1✔
248

249
  /**
250
   * Returns the level of security guarantee in communications
251
   *
252
   * <p>Determining the level of security offered by the transport for RPCs on server-side.
253
   * This can be approximated by looking for the SSLSession, but that doesn't work for ALTS and
254
   * maybe some future TLS approaches. May return a lower security level when it cannot be
255
   * determined precisely.
256
   *
257
   * @return non-{@code null} SecurityLevel enum
258
   */
259
  @ExperimentalApi("https://github.com/grpc/grpc-java/issues/4692")
260
  public SecurityLevel getSecurityLevel() {
261
    return SecurityLevel.NONE;
1✔
262
  }
263

264
  /**
265
   * Returns properties of a single call.
266
   *
267
   * <p>Attributes originate from the transport and can be altered by {@link ServerTransportFilter}.
268
   *
269
   * @return non-{@code null} Attributes container
270
   */
271
  @ExperimentalApi("https://github.com/grpc/grpc-java/issues/1779")
272
  @Grpc.TransportAttr
273
  public Attributes getAttributes() {
274
    return Attributes.EMPTY;
1✔
275
  }
276

277
  /**
278
   * Gets the authority this call is addressed to.
279
   *
280
   * @return the authority string. {@code null} if not available.
281
   */
282
  @Nullable
283
  public String getAuthority() {
284
    return null;
1✔
285
  }
286

287
  /**
288
   * Triggers a custom event to be processed by the listener.
289
   * The event will be delivered to {@link Listener#onEvent(Object)} on the call's executor.
290
   *
291
   * <p>This method is safe to call from multiple threads without external synchronization. No
292
   * events will be delivered after the RPC is cancelled or completed.
293
   *
294
   * <p><strong>Deadlock avoidance:</strong> Callers should avoid holding application-level or
295
   * interceptor locks when calling this method. Depending on the transport and executor
296
   * configuration (such as {@code directExecutor()} or transports like Binder),
297
   * {@code triggerEvent} may acquire transport-level locks and may dispatch
298
   * {@link Listener#onEvent(Object)} synchronously on the calling thread.
299
   * If the caller holds an application lock while calling {@code triggerEvent}, and
300
   * {@code onEvent} or a concurrent transport operation (such as {@link #close} or
301
   * {@link #request}) attempts to acquire that same lock, a deadlock can occur from
302
   * lock-order inversion. Applications should mutate internal state under lock, release
303
   * the lock, and only then invoke {@code triggerEvent}.
304
   *
305
   * @param event the event to trigger.
306
   */
307
  @ExperimentalApi("https://github.com/grpc/grpc-java/issues/12979")
308
  public void triggerEvent(Object event) {
309
    // Default no-op
310
  }
×
311

312
  /**
313
   * The {@link MethodDescriptor} for the call.
314
   */
315
  public abstract MethodDescriptor<ReqT, RespT> getMethodDescriptor();
316
}
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