0
# Core Utilities
1
2
gRPC Core provides essential utility classes that offer common functionality used throughout the gRPC ecosystem. These utilities handle attributes, configuration, common operations, and provide shared constants and helper methods.
3
4
## Capabilities
5
6
### GrpcUtil - Core Utility Functions
7
8
Central utility class providing common functionality used across gRPC modules.
9
10
```java { .api }
11
/**
12
* Core utility functions for gRPC
13
* Located: io.grpc.internal.GrpcUtil
14
*/
15
class GrpcUtil {
16
// Content encoding constants
17
public static final String CONTENT_ACCEPT_ENCODING_KEY = "grpc-accept-encoding";
18
public static final String CONTENT_ENCODING_KEY = "grpc-encoding";
19
public static final String CONTENT_LENGTH_KEY = "content-length";
20
public static final String CONTENT_TYPE_KEY = "content-type";
21
22
// Default values
23
public static final int DEFAULT_MAX_MESSAGE_SIZE = 4 * 1024 * 1024; // 4MB
24
public static final int DEFAULT_MAX_HEADER_LIST_SIZE = 8192;
25
public static final long DEFAULT_SERVER_KEEPALIVE_TIME_NANOS = Long.MAX_VALUE;
26
public static final long DEFAULT_SERVER_KEEPALIVE_TIMEOUT_NANOS = 20L * 1000 * 1000 * 1000; // 20 seconds
27
28
// Splitters for parsing headers
29
public static final Splitter ACCEPT_ENCODING_SPLITTER = Splitter.on(',').trimResults();
30
public static final Splitter AUTHORITY_SPLITTER = Splitter.on(':').limit(2);
31
32
/**
33
* Creates a metadata key for protocol buffer messages
34
* @param name Header name (will be converted to lowercase)
35
* @return Metadata key for string values
36
*/
37
public static Metadata.Key<String> keyForProto(String name);
38
39
/**
40
* Creates a binary metadata key for protocol buffer messages
41
* @param name Header name (must end with "-bin")
42
* @return Metadata key for byte array values
43
*/
44
public static Metadata.Key<byte[]> keyForProtoBin(String name);
45
46
/**
47
* Gets the gRPC build version
48
* @return Version string for this gRPC build
49
*/
50
public static String getGrpcBuildVersion();
51
52
/**
53
* Gets the user agent string for gRPC
54
* @return User agent string including gRPC version
55
*/
56
public static String getGrpcUserAgent(String transportName, @Nullable String applicationUserAgent);
57
58
/**
59
* Gets the current time provider
60
* @return TimeProvider for getting current time
61
*/
62
public static TimeProvider getTimeProvider();
63
64
/**
65
* Checks if the given throwable should be propagated
66
* @param t Throwable to check
67
* @return true if throwable should be propagated
68
*/
69
public static boolean shouldPropagateCancel(Throwable t);
70
71
/**
72
* Gets the shared channel executor
73
* @return Shared executor for channel operations
74
*/
75
public static Executor getSharedChannelExecutor();
76
77
/**
78
* Splits host and port from authority string
79
* @param authority Authority string (host:port)
80
* @return HostAndPort object
81
*/
82
public static HostAndPort splitHostAndPort(String authority);
83
84
/**
85
* Checks if transport supports keep alive
86
* @param transport Transport to check
87
* @return true if transport supports keep alive
88
*/
89
public static boolean supportKeepAlive(ManagedClientTransport transport);
90
}
91
```
92
93
### GrpcAttributes - Common Attribute Definitions
94
95
Defines common attributes used throughout gRPC for storing transport and connection metadata.
96
97
```java { .api }
98
/**
99
* Common attribute definitions for gRPC
100
* Located: io.grpc.internal.GrpcAttributes
101
*/
102
class GrpcAttributes {
103
/**
104
* Attribute for the security level of a transport
105
*/
106
public static final Attributes.Key<SecurityLevel> ATTR_SECURITY_LEVEL =
107
Attributes.Key.create("security-level");
108
109
/**
110
* Attribute for the client transport
111
*/
112
public static final Attributes.Key<ClientTransport> ATTR_CLIENT_TRANSPORT =
113
Attributes.Key.create("client-transport");
114
115
/**
116
* Attribute for the server transport
117
*/
118
public static final Attributes.Key<ServerTransport> ATTR_SERVER_TRANSPORT =
119
Attributes.Key.create("server-transport");
120
121
/**
122
* Attribute for the remote address
123
*/
124
public static final Attributes.Key<SocketAddress> ATTR_REMOTE_ADDR =
125
Attributes.Key.create("remote-addr");
126
127
/**
128
* Attribute for the local address
129
*/
130
public static final Attributes.Key<SocketAddress> ATTR_LOCAL_ADDR =
131
Attributes.Key.create("local-addr");
132
133
/**
134
* Security levels for transport connections
135
*/
136
public enum SecurityLevel {
137
NONE,
138
INTEGRITY,
139
PRIVACY_AND_INTEGRITY
140
}
141
}
142
```
143
144
### ServiceConfigUtil - Service Configuration Utilities
145
146
Utilities for parsing and handling gRPC service configuration.
147
148
```java { .api }
149
/**
150
* Utilities for service configuration handling
151
* Located: io.grpc.internal.ServiceConfigUtil
152
*/
153
class ServiceConfigUtil {
154
/**
155
* Parses load balancing configuration from service config
156
* @param serviceConfig Service configuration map
157
* @return ConfigOrError with parsed load balancing config
158
*/
159
public static ConfigOrError parseLoadBalancingConfig(Map<String, ?> serviceConfig);
160
161
/**
162
* Gets the timeout from method configuration
163
* @param methodConfig Method configuration map
164
* @return Timeout duration or null if not specified
165
*/
166
@Nullable
167
public static Long getTimeoutFromMethodConfig(Map<String, ?> methodConfig);
168
169
/**
170
* Gets the maximum request message size from method configuration
171
* @param methodConfig Method configuration map
172
* @return Maximum request size or null if not specified
173
*/
174
@Nullable
175
public static Integer getMaxRequestMessageBytesFromMethodConfig(Map<String, ?> methodConfig);
176
177
/**
178
* Gets the maximum response message size from method configuration
179
* @param methodConfig Method configuration map
180
* @return Maximum response size or null if not specified
181
*/
182
@Nullable
183
public static Integer getMaxResponseMessageBytesFromMethodConfig(Map<String, ?> methodConfig);
184
185
/**
186
* Gets the wait for ready setting from method configuration
187
* @param methodConfig Method configuration map
188
* @return Wait for ready setting or null if not specified
189
*/
190
@Nullable
191
public static Boolean getWaitForReadyFromMethodConfig(Map<String, ?> methodConfig);
192
193
/**
194
* Checks if a method name matches the method configuration
195
* @param methodConfig Method configuration map
196
* @param serviceName Service name to check
197
* @param methodName Method name to check
198
* @return true if the method matches the configuration
199
*/
200
public static boolean selectMethod(
201
Map<String, ?> methodConfig,
202
String serviceName,
203
String methodName
204
);
205
}
206
```
207
208
### Time Provider Interface
209
210
Interface for providing current time, allowing for testing and customization.
211
212
```java { .api }
213
/**
214
* Interface for providing current time
215
* Located: io.grpc.internal.TimeProvider
216
*/
217
interface TimeProvider {
218
/**
219
* Gets the current time in nanoseconds
220
* @return Current time in nanoseconds since epoch
221
*/
222
long currentTimeNanos();
223
224
/**
225
* System time provider using System.nanoTime()
226
*/
227
TimeProvider SYSTEM_TIME_PROVIDER = new TimeProvider() {
228
@Override
229
public long currentTimeNanos() {
230
return System.nanoTime();
231
}
232
};
233
}
234
```
235
236
### Channelz - Channel Monitoring
237
238
Provides monitoring and debugging support for gRPC channels and servers.
239
240
```java { .api }
241
/**
242
* gRPC channel monitoring and debugging support
243
* Located: io.grpc.internal.Channelz
244
*/
245
class Channelz {
246
/**
247
* Gets the singleton Channelz instance
248
* @return Channelz instance
249
*/
250
public static Channelz instance();
251
252
/**
253
* Adds a top-level channel to monitoring
254
* @param channel Channel to monitor
255
* @return InternalInstrumented wrapper for the channel
256
*/
257
public InternalInstrumented addTopLevelChannel(InternalInstrumented channel);
258
259
/**
260
* Adds a subchannel to monitoring
261
* @param subchannel Subchannel to monitor
262
* @return InternalInstrumented wrapper for the subchannel
263
*/
264
public InternalInstrumented addSubchannel(InternalInstrumented subchannel);
265
266
/**
267
* Adds a server to monitoring
268
* @param server Server to monitor
269
* @return InternalInstrumented wrapper for the server
270
*/
271
public InternalInstrumented addServer(InternalInstrumented server);
272
273
/**
274
* Removes a channel from monitoring
275
* @param channel Channel to remove
276
*/
277
public void removeTopLevelChannel(InternalInstrumented channel);
278
279
/**
280
* Removes a subchannel from monitoring
281
* @param subchannel Subchannel to remove
282
*/
283
public void removeSubchannel(InternalInstrumented subchannel);
284
285
/**
286
* Removes a server from monitoring
287
* @param server Server to remove
288
*/
289
public void removeServer(InternalInstrumented server);
290
291
/**
292
* Gets statistics for all top-level channels
293
* @return RootChannelList with channel statistics
294
*/
295
public RootChannelList getRootChannels(long sinceTimestampNanos);
296
297
/**
298
* Gets statistics for all servers
299
* @return ServerList with server statistics
300
*/
301
public ServerList getServers(long sinceTimestampNanos);
302
}
303
```
304
305
### Statistics and Tracing Context
306
307
Context for collecting statistics and tracing information.
308
309
```java { .api }
310
/**
311
* Context for stats and tracing instrumentation
312
* Located: io.grpc.internal.StatsTraceContext
313
*/
314
class StatsTraceContext {
315
/**
316
* Creates a new client stats trace context
317
* @param fullMethodName Full method name (service/method)
318
* @param statsRecorder Stats recorder instance
319
* @param tagger Tagger for adding tags
320
* @return New StatsTraceContext for client
321
*/
322
public static StatsTraceContext newClientContext(
323
String fullMethodName,
324
StatsRecorder statsRecorder,
325
Tagger tagger
326
);
327
328
/**
329
* Creates a new server stats trace context
330
* @param fullMethodName Full method name (service/method)
331
* @param statsRecorder Stats recorder instance
332
* @param tagger Tagger for adding tags
333
* @return New StatsTraceContext for server
334
*/
335
public static StatsTraceContext newServerContext(
336
String fullMethodName,
337
StatsRecorder statsRecorder,
338
Tagger tagger
339
);
340
341
/**
342
* Records call started event
343
*/
344
public void callStarted();
345
346
/**
347
* Records call ended event
348
* @param status Final status of the call
349
*/
350
public void callEnded(Status status);
351
352
/**
353
* Records message sent event
354
* @param messageId Sequence number of the message
355
*/
356
public void outboundMessage(int messageId);
357
358
/**
359
* Records message received event
360
* @param messageId Sequence number of the message
361
*/
362
public void inboundMessage(int messageId);
363
364
/**
365
* Records wire size of outbound message
366
* @param bytes Number of bytes on wire
367
*/
368
public void outboundWireSize(long bytes);
369
370
/**
371
* Records wire size of inbound message
372
* @param bytes Number of bytes on wire
373
*/
374
public void inboundWireSize(long bytes);
375
}
376
```
377
378
## Utility Usage Patterns
379
380
### Using GrpcUtil
381
382
```java
383
import io.grpc.internal.GrpcUtil;
384
import io.grpc.Metadata;
385
386
// Create metadata keys
387
Metadata.Key<String> customKey = GrpcUtil.keyForProto("custom-header");
388
Metadata.Key<byte[]> binaryKey = GrpcUtil.keyForProtoBin("custom-data-bin");
389
390
// Get gRPC version info
391
String version = GrpcUtil.getGrpcBuildVersion();
392
String userAgent = GrpcUtil.getGrpcUserAgent("netty", "MyApp/1.0");
393
394
// Parse authority
395
HostAndPort hostPort = GrpcUtil.splitHostAndPort("example.com:443");
396
String host = hostPort.getHost();
397
int port = hostPort.getPort();
398
```
399
400
### Working with Service Configuration
401
402
```java
403
import io.grpc.internal.ServiceConfigUtil;
404
import java.util.Map;
405
406
// Parse service configuration
407
Map<String, ?> serviceConfig = loadServiceConfig();
408
ConfigOrError lbConfig = ServiceConfigUtil.parseLoadBalancingConfig(serviceConfig);
409
410
if (lbConfig.getError() != null) {
411
// Handle configuration error
412
handleConfigError(lbConfig.getError());
413
} else {
414
// Use parsed configuration
415
useLoadBalancingConfig(lbConfig.getConfig());
416
}
417
418
// Extract method-specific settings
419
Map<String, ?> methodConfig = getMethodConfig();
420
Long timeout = ServiceConfigUtil.getTimeoutFromMethodConfig(methodConfig);
421
Integer maxRequestSize = ServiceConfigUtil.getMaxRequestMessageBytesFromMethodConfig(methodConfig);
422
```
423
424
### Using Channelz for Monitoring
425
426
```java
427
import io.grpc.internal.Channelz;
428
429
// Get Channelz instance
430
Channelz channelz = Channelz.instance();
431
432
// Monitor a channel
433
InternalInstrumented channelWrapper = channelz.addTopLevelChannel(channel);
434
435
// Get channel statistics
436
RootChannelList channels = channelz.getRootChannels(0);
437
for (RootChannelList.RootChannel rootChannel : channels.channels) {
438
ChannelStats stats = rootChannel.getStats();
439
System.out.println("Channel " + rootChannel.getRef().getChannelId() +
440
" has " + stats.getCallsStarted() + " calls started");
441
}
442
```
443
444
### Custom Time Provider
445
446
```java
447
import io.grpc.internal.TimeProvider;
448
449
// Custom time provider for testing
450
public class FakeTimeProvider implements TimeProvider {
451
private long currentTime = 0;
452
453
@Override
454
public long currentTimeNanos() {
455
return currentTime;
456
}
457
458
public void advance(long nanos) {
459
currentTime += nanos;
460
}
461
}
462
463
// Use in tests
464
FakeTimeProvider fakeTime = new FakeTimeProvider();
465
// Configure gRPC to use fake time provider
466
```
467
468
## Constants and Configuration
469
470
### Default Values
471
472
```java
473
// Message size limits
474
int maxMessageSize = GrpcUtil.DEFAULT_MAX_MESSAGE_SIZE; // 4MB
475
int maxHeaderSize = GrpcUtil.DEFAULT_MAX_HEADER_LIST_SIZE; // 8KB
476
477
// Keep alive settings
478
long serverKeepAliveTime = GrpcUtil.DEFAULT_SERVER_KEEPALIVE_TIME_NANOS; // No limit
479
long serverKeepAliveTimeout = GrpcUtil.DEFAULT_SERVER_KEEPALIVE_TIMEOUT_NANOS; // 20s
480
```
481
482
### Header Constants
483
484
```java
485
// Content encoding headers
486
String acceptEncoding = GrpcUtil.CONTENT_ACCEPT_ENCODING_KEY; // "grpc-accept-encoding"
487
String contentEncoding = GrpcUtil.CONTENT_ENCODING_KEY; // "grpc-encoding"
488
String contentType = GrpcUtil.CONTENT_TYPE_KEY; // "content-type"
489
String contentLength = GrpcUtil.CONTENT_LENGTH_KEY; // "content-length"
490
```
491
492
## Error Handling and Debugging
493
494
Utilities provide comprehensive error handling and debugging support:
495
496
- **Configuration Validation**: ServiceConfigUtil validates service configurations
497
- **Error Propagation**: GrpcUtil provides utilities for proper error propagation
498
- **Monitoring Integration**: Channelz provides detailed monitoring and debugging
499
- **Stats Collection**: StatsTraceContext enables comprehensive statistics collection
500
- **Logging Support**: Utilities provide consistent logging across gRPC modules