CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-io-grpc--grpc-core

Core gRPC library containing transport implementation, channel abstraction, load balancing, name resolution, and other fundamental gRPC functionalities for Java

Pending
Overview
Eval results
Files

core-utilities.mddocs/

Core Utilities

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.

Capabilities

GrpcUtil - Core Utility Functions

Central utility class providing common functionality used across gRPC modules.

/**
 * Core utility functions for gRPC
 * Located: io.grpc.internal.GrpcUtil
 */
class GrpcUtil {
    // Content encoding constants
    public static final String CONTENT_ACCEPT_ENCODING_KEY = "grpc-accept-encoding";
    public static final String CONTENT_ENCODING_KEY = "grpc-encoding";
    public static final String CONTENT_LENGTH_KEY = "content-length";
    public static final String CONTENT_TYPE_KEY = "content-type";
    
    // Default values
    public static final int DEFAULT_MAX_MESSAGE_SIZE = 4 * 1024 * 1024; // 4MB
    public static final int DEFAULT_MAX_HEADER_LIST_SIZE = 8192;
    public static final long DEFAULT_SERVER_KEEPALIVE_TIME_NANOS = Long.MAX_VALUE;
    public static final long DEFAULT_SERVER_KEEPALIVE_TIMEOUT_NANOS = 20L * 1000 * 1000 * 1000; // 20 seconds
    
    // Splitters for parsing headers
    public static final Splitter ACCEPT_ENCODING_SPLITTER = Splitter.on(',').trimResults();
    public static final Splitter AUTHORITY_SPLITTER = Splitter.on(':').limit(2);
    
    /**
     * Creates a metadata key for protocol buffer messages
     * @param name Header name (will be converted to lowercase)
     * @return Metadata key for string values
     */
    public static Metadata.Key<String> keyForProto(String name);
    
    /**
     * Creates a binary metadata key for protocol buffer messages
     * @param name Header name (must end with "-bin")
     * @return Metadata key for byte array values
     */
    public static Metadata.Key<byte[]> keyForProtoBin(String name);
    
    /**
     * Gets the gRPC build version
     * @return Version string for this gRPC build
     */
    public static String getGrpcBuildVersion();
    
    /**
     * Gets the user agent string for gRPC
     * @return User agent string including gRPC version
     */
    public static String getGrpcUserAgent(String transportName, @Nullable String applicationUserAgent);
    
    /**
     * Gets the current time provider
     * @return TimeProvider for getting current time
     */
    public static TimeProvider getTimeProvider();
    
    /**
     * Checks if the given throwable should be propagated
     * @param t Throwable to check
     * @return true if throwable should be propagated
     */
    public static boolean shouldPropagateCancel(Throwable t);
    
    /**
     * Gets the shared channel executor
     * @return Shared executor for channel operations
     */
    public static Executor getSharedChannelExecutor();
    
    /**
     * Splits host and port from authority string
     * @param authority Authority string (host:port)
     * @return HostAndPort object
     */
    public static HostAndPort splitHostAndPort(String authority);
    
    /**
     * Checks if transport supports keep alive
     * @param transport Transport to check
     * @return true if transport supports keep alive
     */
    public static boolean supportKeepAlive(ManagedClientTransport transport);
}

GrpcAttributes - Common Attribute Definitions

Defines common attributes used throughout gRPC for storing transport and connection metadata.

/**
 * Common attribute definitions for gRPC
 * Located: io.grpc.internal.GrpcAttributes
 */
class GrpcAttributes {
    /**
     * Attribute for the security level of a transport
     */
    public static final Attributes.Key<SecurityLevel> ATTR_SECURITY_LEVEL = 
        Attributes.Key.create("security-level");
    
    /**
     * Attribute for the client transport
     */
    public static final Attributes.Key<ClientTransport> ATTR_CLIENT_TRANSPORT = 
        Attributes.Key.create("client-transport");
    
    /**
     * Attribute for the server transport  
     */
    public static final Attributes.Key<ServerTransport> ATTR_SERVER_TRANSPORT = 
        Attributes.Key.create("server-transport");
    
    /**
     * Attribute for the remote address
     */
    public static final Attributes.Key<SocketAddress> ATTR_REMOTE_ADDR = 
        Attributes.Key.create("remote-addr");
    
    /**
     * Attribute for the local address
     */
    public static final Attributes.Key<SocketAddress> ATTR_LOCAL_ADDR = 
        Attributes.Key.create("local-addr");
    
    /**
     * Security levels for transport connections
     */
    public enum SecurityLevel {
        NONE,
        INTEGRITY,
        PRIVACY_AND_INTEGRITY
    }
}

ServiceConfigUtil - Service Configuration Utilities

Utilities for parsing and handling gRPC service configuration.

/**
 * Utilities for service configuration handling
 * Located: io.grpc.internal.ServiceConfigUtil
 */
class ServiceConfigUtil {
    /**
     * Parses load balancing configuration from service config
     * @param serviceConfig Service configuration map
     * @return ConfigOrError with parsed load balancing config
     */
    public static ConfigOrError parseLoadBalancingConfig(Map<String, ?> serviceConfig);
    
    /**
     * Gets the timeout from method configuration
     * @param methodConfig Method configuration map
     * @return Timeout duration or null if not specified
     */
    @Nullable
    public static Long getTimeoutFromMethodConfig(Map<String, ?> methodConfig);
    
    /**
     * Gets the maximum request message size from method configuration
     * @param methodConfig Method configuration map
     * @return Maximum request size or null if not specified
     */
    @Nullable
    public static Integer getMaxRequestMessageBytesFromMethodConfig(Map<String, ?> methodConfig);
    
    /**
     * Gets the maximum response message size from method configuration  
     * @param methodConfig Method configuration map
     * @return Maximum response size or null if not specified
     */
    @Nullable
    public static Integer getMaxResponseMessageBytesFromMethodConfig(Map<String, ?> methodConfig);
    
    /**
     * Gets the wait for ready setting from method configuration
     * @param methodConfig Method configuration map
     * @return Wait for ready setting or null if not specified
     */
    @Nullable
    public static Boolean getWaitForReadyFromMethodConfig(Map<String, ?> methodConfig);
    
    /**
     * Checks if a method name matches the method configuration
     * @param methodConfig Method configuration map
     * @param serviceName Service name to check
     * @param methodName Method name to check  
     * @return true if the method matches the configuration
     */
    public static boolean selectMethod(
        Map<String, ?> methodConfig,
        String serviceName,
        String methodName
    );
}

Time Provider Interface

Interface for providing current time, allowing for testing and customization.

/**
 * Interface for providing current time
 * Located: io.grpc.internal.TimeProvider
 */
interface TimeProvider {
    /**
     * Gets the current time in nanoseconds
     * @return Current time in nanoseconds since epoch
     */
    long currentTimeNanos();
    
    /**
     * System time provider using System.nanoTime()
     */
    TimeProvider SYSTEM_TIME_PROVIDER = new TimeProvider() {
        @Override
        public long currentTimeNanos() {
            return System.nanoTime();
        }
    };
}

Channelz - Channel Monitoring

Provides monitoring and debugging support for gRPC channels and servers.

/**
 * gRPC channel monitoring and debugging support
 * Located: io.grpc.internal.Channelz
 */
class Channelz {
    /**
     * Gets the singleton Channelz instance
     * @return Channelz instance
     */
    public static Channelz instance();
    
    /**
     * Adds a top-level channel to monitoring
     * @param channel Channel to monitor  
     * @return InternalInstrumented wrapper for the channel
     */
    public InternalInstrumented addTopLevelChannel(InternalInstrumented channel);
    
    /**
     * Adds a subchannel to monitoring
     * @param subchannel Subchannel to monitor
     * @return InternalInstrumented wrapper for the subchannel
     */
    public InternalInstrumented addSubchannel(InternalInstrumented subchannel);
    
    /**
     * Adds a server to monitoring
     * @param server Server to monitor
     * @return InternalInstrumented wrapper for the server
     */
    public InternalInstrumented addServer(InternalInstrumented server);
    
    /**
     * Removes a channel from monitoring
     * @param channel Channel to remove
     */
    public void removeTopLevelChannel(InternalInstrumented channel);
    
    /**
     * Removes a subchannel from monitoring
     * @param subchannel Subchannel to remove
     */
    public void removeSubchannel(InternalInstrumented subchannel);
    
    /**
     * Removes a server from monitoring
     * @param server Server to remove
     */
    public void removeServer(InternalInstrumented server);
    
    /**
     * Gets statistics for all top-level channels
     * @return RootChannelList with channel statistics
     */
    public RootChannelList getRootChannels(long sinceTimestampNanos);
    
    /**
     * Gets statistics for all servers
     * @return ServerList with server statistics
     */
    public ServerList getServers(long sinceTimestampNanos);
}

Statistics and Tracing Context

Context for collecting statistics and tracing information.

/**
 * Context for stats and tracing instrumentation
 * Located: io.grpc.internal.StatsTraceContext
 */
class StatsTraceContext {
    /**
     * Creates a new client stats trace context
     * @param fullMethodName Full method name (service/method)
     * @param statsRecorder Stats recorder instance
     * @param tagger Tagger for adding tags
     * @return New StatsTraceContext for client
     */
    public static StatsTraceContext newClientContext(
        String fullMethodName,
        StatsRecorder statsRecorder,
        Tagger tagger
    );
    
    /**
     * Creates a new server stats trace context
     * @param fullMethodName Full method name (service/method)
     * @param statsRecorder Stats recorder instance
     * @param tagger Tagger for adding tags
     * @return New StatsTraceContext for server
     */
    public static StatsTraceContext newServerContext(
        String fullMethodName,
        StatsRecorder statsRecorder,
        Tagger tagger
    );
    
    /**
     * Records call started event
     */
    public void callStarted();
    
    /**
     * Records call ended event
     * @param status Final status of the call
     */
    public void callEnded(Status status);
    
    /**
     * Records message sent event
     * @param messageId Sequence number of the message
     */
    public void outboundMessage(int messageId);
    
    /**
     * Records message received event
     * @param messageId Sequence number of the message
     */
    public void inboundMessage(int messageId);
    
    /**
     * Records wire size of outbound message
     * @param bytes Number of bytes on wire
     */
    public void outboundWireSize(long bytes);
    
    /**
     * Records wire size of inbound message
     * @param bytes Number of bytes on wire
     */
    public void inboundWireSize(long bytes);
}

Utility Usage Patterns

Using GrpcUtil

import io.grpc.internal.GrpcUtil;
import io.grpc.Metadata;

// Create metadata keys
Metadata.Key<String> customKey = GrpcUtil.keyForProto("custom-header");
Metadata.Key<byte[]> binaryKey = GrpcUtil.keyForProtoBin("custom-data-bin");

// Get gRPC version info
String version = GrpcUtil.getGrpcBuildVersion();
String userAgent = GrpcUtil.getGrpcUserAgent("netty", "MyApp/1.0");

// Parse authority
HostAndPort hostPort = GrpcUtil.splitHostAndPort("example.com:443");
String host = hostPort.getHost();
int port = hostPort.getPort();

Working with Service Configuration

import io.grpc.internal.ServiceConfigUtil;
import java.util.Map;

// Parse service configuration
Map<String, ?> serviceConfig = loadServiceConfig();
ConfigOrError lbConfig = ServiceConfigUtil.parseLoadBalancingConfig(serviceConfig);

if (lbConfig.getError() != null) {
    // Handle configuration error
    handleConfigError(lbConfig.getError());
} else {
    // Use parsed configuration
    useLoadBalancingConfig(lbConfig.getConfig());
}

// Extract method-specific settings
Map<String, ?> methodConfig = getMethodConfig();
Long timeout = ServiceConfigUtil.getTimeoutFromMethodConfig(methodConfig);
Integer maxRequestSize = ServiceConfigUtil.getMaxRequestMessageBytesFromMethodConfig(methodConfig);

Using Channelz for Monitoring

import io.grpc.internal.Channelz;

// Get Channelz instance
Channelz channelz = Channelz.instance();

// Monitor a channel
InternalInstrumented channelWrapper = channelz.addTopLevelChannel(channel);

// Get channel statistics
RootChannelList channels = channelz.getRootChannels(0);
for (RootChannelList.RootChannel rootChannel : channels.channels) {
    ChannelStats stats = rootChannel.getStats();
    System.out.println("Channel " + rootChannel.getRef().getChannelId() + 
                      " has " + stats.getCallsStarted() + " calls started");
}

Custom Time Provider

import io.grpc.internal.TimeProvider;

// Custom time provider for testing
public class FakeTimeProvider implements TimeProvider {
    private long currentTime = 0;
    
    @Override
    public long currentTimeNanos() {
        return currentTime;
    }
    
    public void advance(long nanos) {
        currentTime += nanos;
    }
}

// Use in tests
FakeTimeProvider fakeTime = new FakeTimeProvider();
// Configure gRPC to use fake time provider

Constants and Configuration

Default Values

// Message size limits
int maxMessageSize = GrpcUtil.DEFAULT_MAX_MESSAGE_SIZE; // 4MB
int maxHeaderSize = GrpcUtil.DEFAULT_MAX_HEADER_LIST_SIZE; // 8KB

// Keep alive settings  
long serverKeepAliveTime = GrpcUtil.DEFAULT_SERVER_KEEPALIVE_TIME_NANOS; // No limit
long serverKeepAliveTimeout = GrpcUtil.DEFAULT_SERVER_KEEPALIVE_TIMEOUT_NANOS; // 20s

Header Constants

// Content encoding headers
String acceptEncoding = GrpcUtil.CONTENT_ACCEPT_ENCODING_KEY; // "grpc-accept-encoding"  
String contentEncoding = GrpcUtil.CONTENT_ENCODING_KEY; // "grpc-encoding"
String contentType = GrpcUtil.CONTENT_TYPE_KEY; // "content-type"
String contentLength = GrpcUtil.CONTENT_LENGTH_KEY; // "content-length"

Error Handling and Debugging

Utilities provide comprehensive error handling and debugging support:

  • Configuration Validation: ServiceConfigUtil validates service configurations
  • Error Propagation: GrpcUtil provides utilities for proper error propagation
  • Monitoring Integration: Channelz provides detailed monitoring and debugging
  • Stats Collection: StatsTraceContext enables comprehensive statistics collection
  • Logging Support: Utilities provide consistent logging across gRPC modules

Install with Tessl CLI

npx tessl i tessl/maven-io-grpc--grpc-core

docs

buffer-management.md

builders-factories.md

core-utilities.md

index.md

load-balancing-name-resolution.md

service-providers.md

transport-layer.md

tile.json