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

grpc / grpc-java / #19282

13 Jun 2024 08:06PM UTC coverage: 88.322% (+0.02%) from 88.303%
#19282

push

github

web-flow
api: Stabilize ServerBuilder.AddServices() (#11285)

32069 of 36309 relevant lines covered (88.32%)

0.88 hits per line

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

7.41
/../api/src/main/java/io/grpc/ServerBuilder.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;
18

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

21
import com.google.common.base.Preconditions;
22
import java.io.File;
23
import java.io.InputStream;
24
import java.util.List;
25
import java.util.concurrent.Executor;
26
import java.util.concurrent.TimeUnit;
27
import javax.annotation.Nullable;
28

29
/**
30
 * A builder for {@link Server} instances.
31
 *
32
 * @param <T> The concrete type of this builder.
33
 * @since 1.0.0
34
 */
35
public abstract class ServerBuilder<T extends ServerBuilder<T>> {
1✔
36

37
  /**
38
   * Static factory for creating a new ServerBuilder.
39
   *
40
   * @param port the port to listen on
41
   * @since 1.0.0
42
   */
43
  public static ServerBuilder<?> forPort(int port) {
44
    return ServerProvider.provider().builderForPort(port);
1✔
45
  }
46

47
  /**
48
   * Execute application code directly in the transport thread.
49
   *
50
   * <p>Depending on the underlying transport, using a direct executor may lead to substantial
51
   * performance improvements. However, it also requires the application to not block under
52
   * any circumstances.
53
   *
54
   * <p>Calling this method is semantically equivalent to calling {@link #executor(Executor)} and
55
   * passing in a direct executor. However, this is the preferred way as it may allow the transport
56
   * to perform special optimizations.
57
   *
58
   * @return this
59
   * @since 1.0.0
60
   */
61
  public abstract T directExecutor();
62

63
  /**
64
   * Provides a custom executor.
65
   *
66
   * <p>It's an optional parameter. If the user has not provided an executor when the server is
67
   * built, the builder will use a static cached thread pool.
68
   *
69
   * <p>The server won't take ownership of the given executor. It's caller's responsibility to
70
   * shut down the executor when it's desired.
71
   *
72
   * @return this
73
   * @since 1.0.0
74
   */
75
  public abstract T executor(@Nullable Executor executor);
76

77

78
  /**
79
   * Allows for defining a way to provide a custom executor to handle the server call.
80
   * This executor is the result of calling
81
   * {@link ServerCallExecutorSupplier#getExecutor(ServerCall, Metadata)} per RPC.
82
   *
83
   * <p>It's an optional parameter. If it is provided, the {@link #executor(Executor)} would still
84
   * run necessary tasks before the {@link ServerCallExecutorSupplier} is ready to be called, then
85
   * it switches over. But if calling {@link ServerCallExecutorSupplier} returns null, the server
86
   * call is still handled by the default {@link #executor(Executor)} as a fallback.
87
   *
88
   * @param executorSupplier the server call executor provider
89
   * @return this
90
   * @since 1.39.0
91
   *
92
   * */
93
  @ExperimentalApi("https://github.com/grpc/grpc-java/issues/8274")
94
  public T callExecutor(ServerCallExecutorSupplier executorSupplier) {
95
    return thisT();
×
96
  }
97

98
  /**
99
   * Adds a service implementation to the handler registry.
100
   *
101
   * @param service ServerServiceDefinition object
102
   * @return this
103
   * @since 1.0.0
104
   */
105
  public abstract T addService(ServerServiceDefinition service);
106

107
  /**
108
   * Adds a service implementation to the handler registry.
109
   *
110
   * @param bindableService BindableService object
111
   * @return this
112
   * @since 1.0.0
113
   */
114
  public abstract T addService(BindableService bindableService);
115

116
  /**
117
   * Adds a list of service implementations to the handler registry together. This exists for
118
   * convenience - equivalent to repeatedly calling addService() with different services.
119
   * If multiple services on the list use the same name, only the last one on the list will
120
   * be added.
121
   *
122
   * @param services the list of ServerServiceDefinition objects
123
   * @return this
124
   * @since 1.37.0
125
   */
126
  public final T addServices(List<ServerServiceDefinition> services) {
127
    checkNotNull(services, "services");
×
128
    for (ServerServiceDefinition service : services) {
×
129
      addService(service);
×
130
    }
×
131
    return thisT();
×
132
  }
133

134
  /**
135
   * Adds a {@link ServerInterceptor} that is run for all services on the server.  Interceptors
136
   * added through this method always run before per-service interceptors added through {@link
137
   * ServerInterceptors}.  Interceptors run in the reverse order in which they are added, just as
138
   * with consecutive calls to {@code ServerInterceptors.intercept()}.
139
   *
140
   * @param interceptor the all-service interceptor
141
   * @return this
142
   * @since 1.5.0
143
   */
144
  public T intercept(ServerInterceptor interceptor) {
145
    throw new UnsupportedOperationException();
×
146
  }
147

148
  /**
149
   * Adds a {@link ServerTransportFilter}. The order of filters being added is the order they will
150
   * be executed.
151
   *
152
   * @return this
153
   * @since 1.2.0
154
   */
155
  @ExperimentalApi("https://github.com/grpc/grpc-java/issues/2132")
156
  public T addTransportFilter(ServerTransportFilter filter) {
157
    throw new UnsupportedOperationException();
×
158
  }
159

160
  /**
161
   * Adds a {@link ServerStreamTracer.Factory} to measure server-side traffic.  The order of
162
   * factories being added is the order they will be executed.
163
   *
164
   * @return this
165
   * @since 1.3.0
166
   */
167
  @ExperimentalApi("https://github.com/grpc/grpc-java/issues/2861")
168
  public T addStreamTracerFactory(ServerStreamTracer.Factory factory) {
169
    throw new UnsupportedOperationException();
×
170
  }
171

172
  /**
173
   * Sets a fallback handler registry that will be looked up in if a method is not found in the
174
   * primary registry. The primary registry (configured via {@code addService()}) is faster but
175
   * immutable. The fallback registry is more flexible and allows implementations to mutate over
176
   * time and load services on-demand.
177
   *
178
   * @return this
179
   * @since 1.0.0
180
   */
181
  public abstract T fallbackHandlerRegistry(@Nullable HandlerRegistry fallbackRegistry);
182

183
  /**
184
   * Makes the server use TLS.
185
   *
186
   * @param certChain file containing the full certificate chain
187
   * @param privateKey file containing the private key
188
   *
189
   * @return this
190
   * @throws UnsupportedOperationException if the server does not support TLS.
191
   * @since 1.0.0
192
   */
193
  public abstract T useTransportSecurity(File certChain, File privateKey);
194

195
  /**
196
   * Makes the server use TLS.
197
   *
198
   * @param certChain InputStream containing the full certificate chain
199
   * @param privateKey InputStream containing the private key
200
   *
201
   * @return this
202
   * @throws UnsupportedOperationException if the server does not support TLS, or does not support
203
   *         reading these files from an InputStream.
204
   * @since 1.12.0
205
   */
206
  public T useTransportSecurity(InputStream certChain, InputStream privateKey) {
207
    throw new UnsupportedOperationException();
×
208
  }
209

210

211
  /**
212
   * Set the decompression registry for use in the channel.  This is an advanced API call and
213
   * shouldn't be used unless you are using custom message encoding.   The default supported
214
   * decompressors are in {@code DecompressorRegistry.getDefaultInstance}.
215
   *
216
   * @return this
217
   * @since 1.0.0
218
   */
219
  @ExperimentalApi("https://github.com/grpc/grpc-java/issues/1704")
220
  public abstract T decompressorRegistry(@Nullable DecompressorRegistry registry);
221

222
  /**
223
   * Set the compression registry for use in the channel.  This is an advanced API call and
224
   * shouldn't be used unless you are using custom message encoding.   The default supported
225
   * compressors are in {@code CompressorRegistry.getDefaultInstance}.
226
   *
227
   * @return this
228
   * @since 1.0.0
229
   */
230
  @ExperimentalApi("https://github.com/grpc/grpc-java/issues/1704")
231
  public abstract T compressorRegistry(@Nullable CompressorRegistry registry);
232

233
  /**
234
   * Sets the permitted time for new connections to complete negotiation handshakes before being
235
   * killed. The default value is 2 minutes.
236
   *
237
   * @return this
238
   * @throws IllegalArgumentException if timeout is negative
239
   * @throws UnsupportedOperationException if unsupported
240
   * @since 1.8.0
241
   */
242
  public T handshakeTimeout(long timeout, TimeUnit unit) {
243
    throw new UnsupportedOperationException();
×
244
  }
245

246
  /**
247
   * Sets the time without read activity before sending a keepalive ping. An unreasonably small
248
   * value might be increased, and {@code Long.MAX_VALUE} nano seconds or an unreasonably large
249
   * value will disable keepalive. The typical default is two hours when supported.
250
   *
251
   * @throws IllegalArgumentException if time is not positive
252
   * @throws UnsupportedOperationException if unsupported
253
   * @see <a href="https://github.com/grpc/proposal/blob/master/A9-server-side-conn-mgt.md">gRFC A9
254
   *     Server-side Connection Management</a>
255
   * @since 1.47.0
256
   */
257
  @ExperimentalApi("https://github.com/grpc/grpc-java/issues/9009")
258
  public T keepAliveTime(long keepAliveTime, TimeUnit timeUnit) {
259
    throw new UnsupportedOperationException();
×
260
  }
261

262
  /**
263
   * Sets a time waiting for read activity after sending a keepalive ping. If the time expires
264
   * without any read activity on the connection, the connection is considered dead. An unreasonably
265
   * small value might be increased. Defaults to 20 seconds when supported.
266
   *
267
   * <p>This value should be at least multiple times the RTT to allow for lost packets.
268
   *
269
   * @throws IllegalArgumentException if timeout is not positive
270
   * @throws UnsupportedOperationException if unsupported
271
   * @see <a href="https://github.com/grpc/proposal/blob/master/A9-server-side-conn-mgt.md">gRFC A9
272
   *     Server-side Connection Management</a>
273
   * @since 1.47.0
274
   */
275
  @ExperimentalApi("https://github.com/grpc/grpc-java/issues/9009")
276
  public T keepAliveTimeout(long keepAliveTimeout, TimeUnit timeUnit) {
277
    throw new UnsupportedOperationException();
×
278
  }
279

280
  /**
281
   * Sets the maximum connection idle time, connections being idle for longer than which will be
282
   * gracefully terminated. Idleness duration is defined since the most recent time the number of
283
   * outstanding RPCs became zero or the connection establishment. An unreasonably small value might
284
   * be increased. {@code Long.MAX_VALUE} nano seconds or an unreasonably large value will disable
285
   * max connection idle.
286
   *
287
   * @throws IllegalArgumentException if idle is not positive
288
   * @throws UnsupportedOperationException if unsupported
289
   * @see <a href="https://github.com/grpc/proposal/blob/master/A9-server-side-conn-mgt.md">gRFC A9
290
   *     Server-side Connection Management</a>
291
   * @since 1.47.0
292
   */
293
  @ExperimentalApi("https://github.com/grpc/grpc-java/issues/9009")
294
  public T maxConnectionIdle(long maxConnectionIdle, TimeUnit timeUnit) {
295
    throw new UnsupportedOperationException();
×
296
  }
297

298
  /**
299
   * Sets the maximum connection age, connections lasting longer than which will be gracefully
300
   * terminated. An unreasonably small value might be increased. A random jitter of +/-10% will be
301
   * added to it. {@code Long.MAX_VALUE} nano seconds or an unreasonably large value will disable
302
   * max connection age.
303
   *
304
   * @throws IllegalArgumentException if age is not positive
305
   * @throws UnsupportedOperationException if unsupported
306
   * @see <a href="https://github.com/grpc/proposal/blob/master/A9-server-side-conn-mgt.md">gRFC A9
307
   *     Server-side Connection Management</a>
308
   * @since 1.47.0
309
   */
310
  @ExperimentalApi("https://github.com/grpc/grpc-java/issues/9009")
311
  public T maxConnectionAge(long maxConnectionAge, TimeUnit timeUnit) {
312
    throw new UnsupportedOperationException();
×
313
  }
314

315
  /**
316
   * Sets the grace time for the graceful connection termination. Once the max connection age
317
   * is reached, RPCs have the grace time to complete. RPCs that do not complete in time will be
318
   * cancelled, allowing the connection to terminate. {@code Long.MAX_VALUE} nano seconds or an
319
   * unreasonably large value are considered infinite.
320
   *
321
   * @throws IllegalArgumentException if grace is negative
322
   * @throws UnsupportedOperationException if unsupported
323
   * @see #maxConnectionAge(long, TimeUnit)
324
   * @see <a href="https://github.com/grpc/proposal/blob/master/A9-server-side-conn-mgt.md">gRFC A9
325
   *     Server-side Connection Management</a>
326
   * @since 1.47.0
327
   */
328
  @ExperimentalApi("https://github.com/grpc/grpc-java/issues/9009")
329
  public T maxConnectionAgeGrace(long maxConnectionAgeGrace, TimeUnit timeUnit) {
330
    throw new UnsupportedOperationException();
×
331
  }
332

333
  /**
334
   * Specify the most aggressive keep-alive time clients are permitted to configure. The server will
335
   * try to detect clients exceeding this rate and when detected will forcefully close the
336
   * connection. The typical default is 5 minutes when supported.
337
   *
338
   * <p>Even though a default is defined that allows some keep-alives, clients must not use
339
   * keep-alive without approval from the service owner. Otherwise, they may experience failures in
340
   * the future if the service becomes more restrictive. When unthrottled, keep-alives can cause a
341
   * significant amount of traffic and CPU usage, so clients and servers should be conservative in
342
   * what they use and accept.
343
   *
344
   * @throws IllegalArgumentException if time is negative
345
   * @throws UnsupportedOperationException if unsupported
346
   * @see #permitKeepAliveWithoutCalls(boolean)
347
   * @see <a href="https://github.com/grpc/proposal/blob/master/A8-client-side-keepalive.md">gRFC A8
348
   *     Client-side Keepalive</a>
349
   * @since 1.47.0
350
   */
351
  @ExperimentalApi("https://github.com/grpc/grpc-java/issues/9009")
352
  public T permitKeepAliveTime(long keepAliveTime, TimeUnit timeUnit) {
353
    throw new UnsupportedOperationException();
×
354
  }
355

356
  /**
357
   * Sets whether to allow clients to send keep-alive HTTP/2 PINGs even if there are no outstanding
358
   * RPCs on the connection. Defaults to {@code false} when supported.
359
   *
360
   * @throws UnsupportedOperationException if unsupported
361
   * @see #permitKeepAliveTime(long, TimeUnit)
362
   * @see <a href="https://github.com/grpc/proposal/blob/master/A8-client-side-keepalive.md">gRFC A8
363
   *     Client-side Keepalive</a>
364
   * @since 1.47.0
365
   */
366
  @ExperimentalApi("https://github.com/grpc/grpc-java/issues/9009")
367
  public T permitKeepAliveWithoutCalls(boolean permit) {
368
    throw new UnsupportedOperationException();
×
369
  }
370

371
  /**
372
   * Sets the maximum message size allowed to be received on the server. If not called,
373
   * defaults to 4 MiB. The default provides protection to servers who haven't considered the
374
   * possibility of receiving large messages while trying to be large enough to not be hit in normal
375
   * usage.
376
   *
377
   * <p>This method is advisory, and implementations may decide to not enforce this.  Currently,
378
   * the only known transport to not enforce this is {@code InProcessServer}.
379
   *
380
   * @param bytes the maximum number of bytes a single message can be.
381
   * @return this
382
   * @throws IllegalArgumentException if bytes is negative.
383
   * @throws UnsupportedOperationException if unsupported.
384
   * @since 1.13.0
385
   */
386
  public T maxInboundMessageSize(int bytes) {
387
    // intentional noop rather than throw, this method is only advisory.
388
    Preconditions.checkArgument(bytes >= 0, "bytes must be >= 0");
×
389
    return thisT();
×
390
  }
391

392
  /**
393
   * Sets the maximum size of metadata allowed to be received. {@code Integer.MAX_VALUE} disables
394
   * the enforcement. The default is implementation-dependent, but is not generally less than 8 KiB
395
   * and may be unlimited.
396
   *
397
   * <p>This is cumulative size of the metadata. The precise calculation is
398
   * implementation-dependent, but implementations are encouraged to follow the calculation used for
399
   * <a href="http://httpwg.org/specs/rfc7540.html#rfc.section.6.5.2">
400
   * HTTP/2's SETTINGS_MAX_HEADER_LIST_SIZE</a>. It sums the bytes from each entry's key and value,
401
   * plus 32 bytes of overhead per entry.
402
   *
403
   * @param bytes the maximum size of received metadata
404
   * @return this
405
   * @throws IllegalArgumentException if bytes is non-positive
406
   * @since 1.17.0
407
   */
408
  public T maxInboundMetadataSize(int bytes) {
409
    Preconditions.checkArgument(bytes > 0, "maxInboundMetadataSize must be > 0");
×
410
    // intentional noop rather than throw, this method is only advisory.
411
    return thisT();
×
412
  }
413

414
  /**
415
   * Sets the BinaryLog object that this server should log to. The server does not take
416
   * ownership of the object, and users are responsible for calling {@link BinaryLog#close()}.
417
   *
418
   * @param binaryLog the object to provide logging.
419
   * @return this
420
   * @since 1.13.0
421
   */
422
  @ExperimentalApi("https://github.com/grpc/grpc-java/issues/4017")
423
  public T setBinaryLog(BinaryLog binaryLog) {
424
    throw new UnsupportedOperationException();
×
425
  }
426

427
  /**
428
   * Builds a server using the given parameters.
429
   *
430
   * <p>The returned service will not been started or be bound a port. You will need to start it
431
   * with {@link Server#start()}.
432
   *
433
   * @return a new Server
434
   * @since 1.0.0
435
   */
436
  public abstract Server build();
437

438
  /**
439
   * Returns the correctly typed version of the builder.
440
   */
441
  private T thisT() {
442
    @SuppressWarnings("unchecked")
443
    T thisT = (T) this;
×
444
    return thisT;
×
445
  }
446
}
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