Core gRPC constants including status codes, connectivity states, compression algorithms, logging levels, and other enumerated values essential for gRPC communication and configuration.
Standard gRPC status codes for indicating call results and error conditions.
/**
* gRPC status codes indicating the result of RPC calls
*/
enum status {
/** The operation completed successfully */
OK = 0,
/** The operation was cancelled (typically by the caller) */
CANCELLED = 1,
/** Unknown error */
UNKNOWN = 2,
/** Client specified an invalid argument */
INVALID_ARGUMENT = 3,
/** Deadline expired before operation could complete */
DEADLINE_EXCEEDED = 4,
/** Some requested entity (file or directory) was not found */
NOT_FOUND = 5,
/** Some entity that we attempted to create already exists */
ALREADY_EXISTS = 6,
/** The caller does not have permission to execute the specified operation */
PERMISSION_DENIED = 7,
/** Some resource has been exhausted */
RESOURCE_EXHAUSTED = 8,
/** Operation was rejected because the system is not in required state */
FAILED_PRECONDITION = 9,
/** The operation was aborted, typically due to concurrency issue */
ABORTED = 10,
/** Operation was attempted past the valid range */
OUT_OF_RANGE = 11,
/** Operation is not implemented or not supported/enabled */
UNIMPLEMENTED = 12,
/** Internal errors (means some invariants expected by underlying system broken) */
INTERNAL = 13,
/** The service is currently unavailable */
UNAVAILABLE = 14,
/** Unrecoverable data loss or corruption */
DATA_LOSS = 15,
/** The request does not have valid authentication credentials */
UNAUTHENTICATED = 16
}Channel connectivity states indicating the current connection status.
/**
* Channel connectivity states
*/
enum connectivityState {
/** Channel is idle and not trying to connect */
IDLE = 0,
/** Channel is actively trying to connect */
CONNECTING = 1,
/** Channel is connected and ready to make calls */
READY = 2,
/** Channel has experienced a temporary failure and is trying to recover */
TRANSIENT_FAILURE = 3,
/** Channel has been shut down */
SHUTDOWN = 4
}Logging verbosity levels for controlling debug output.
/**
* Log verbosity levels for gRPC library logging
*/
enum logVerbosity {
/** Only log errors */
DEBUG = 0,
/** Log informational messages and errors */
INFO = 1,
/** Log errors only */
ERROR = 2,
/** No logging */
NONE = 3
}Flags controlling what information gets propagated from parent calls to child calls.
/**
* Call propagation flags for distributed tracing and context
*/
enum propagate {
/** Propagate deadline from parent call */
DEADLINE = 1,
/** Propagate census stats context */
CENSUS_STATS_CONTEXT = 2,
/** Propagate census tracing context */
CENSUS_TRACING_CONTEXT = 4,
/** Propagate cancellation */
CANCELLATION = 8,
/** Propagate all supported flags */
DEFAULTS = DEADLINE | CENSUS_STATS_CONTEXT | CENSUS_TRACING_CONTEXT | CANCELLATION
}Supported compression algorithms for message compression.
/**
* Compression algorithms supported by gRPC
*/
enum compressionAlgorithms {
/** No compression */
IDENTITY = 0,
/** GZIP compression */
GZIP = 1,
/** DEFLATE compression */
DEFLATE = 2
}import { status } from "@grpc/grpc-js";
// Client error handling
client.getData({ id: "123" }, (error, response) => {
if (error) {
switch (error.code) {
case status.NOT_FOUND:
console.error("Data not found");
break;
case status.PERMISSION_DENIED:
console.error("Access denied");
break;
case status.DEADLINE_EXCEEDED:
console.error("Request timed out");
break;
case status.UNAVAILABLE:
console.error("Service unavailable, retrying...");
// Implement retry logic
break;
case status.INVALID_ARGUMENT:
console.error("Invalid request:", error.details);
break;
default:
console.error("Unexpected error:", error.details);
}
return;
}
console.log("Success:", response);
});
// Server error responses
server.addService(serviceDefinition, {
getData: (call, callback) => {
const { id } = call.request;
if (!id) {
callback({
code: status.INVALID_ARGUMENT,
details: "ID is required"
});
return;
}
const data = findData(id);
if (!data) {
callback({
code: status.NOT_FOUND,
details: `Data with ID ${id} not found`
});
return;
}
// Check permission
const user = getUserFromMetadata(call.metadata);
if (!canAccess(user, data)) {
callback({
code: status.PERMISSION_DENIED,
details: "Insufficient permissions"
});
return;
}
callback(null, data);
}
});import { connectivityState } from "@grpc/grpc-js";
const channel = client.getChannel();
function watchConnectivity() {
const currentState = channel.getConnectivityState(true);
console.log("Current state:", getStateName(currentState));
// Watch for state changes
channel.watchConnectivityState(
currentState,
Date.now() + 30000, // 30 second timeout
(error) => {
if (error) {
console.error("State watch error:", error);
return;
}
const newState = channel.getConnectivityState(false);
console.log("State changed to:", getStateName(newState));
// Continue watching
watchConnectivity();
}
);
}
function getStateName(state: connectivityState): string {
switch (state) {
case connectivityState.IDLE:
return "IDLE";
case connectivityState.CONNECTING:
return "CONNECTING";
case connectivityState.READY:
return "READY";
case connectivityState.TRANSIENT_FAILURE:
return "TRANSIENT_FAILURE";
case connectivityState.SHUTDOWN:
return "SHUTDOWN";
default:
return "UNKNOWN";
}
}
// Start monitoring
watchConnectivity();import { setLogVerbosity, logVerbosity } from "@grpc/grpc-js";
// Set logging level
setLogVerbosity(logVerbosity.INFO);
// Custom logger
const customLogger = {
error: (message: string, ...args: any[]) => {
console.error(`[gRPC ERROR] ${message}`, ...args);
},
warn: (message: string, ...args: any[]) => {
console.warn(`[gRPC WARN] ${message}`, ...args);
},
info: (message: string, ...args: any[]) => {
console.info(`[gRPC INFO] ${message}`, ...args);
},
debug: (message: string, ...args: any[]) => {
console.debug(`[gRPC DEBUG] ${message}`, ...args);
}
};
setLogger(customLogger);
// Environment-based logging
const logLevel = process.env.GRPC_LOG_LEVEL || 'INFO';
switch (logLevel.toUpperCase()) {
case 'DEBUG':
setLogVerbosity(logVerbosity.DEBUG);
break;
case 'INFO':
setLogVerbosity(logVerbosity.INFO);
break;
case 'ERROR':
setLogVerbosity(logVerbosity.ERROR);
break;
case 'NONE':
setLogVerbosity(logVerbosity.NONE);
break;
default:
setLogVerbosity(logVerbosity.INFO);
}import { propagate } from "@grpc/grpc-js";
// Parent call with propagation
const parentCall = client.parentMethod({ data: "parent" });
// Child call that inherits context from parent
client.childMethod(
{ data: "child" },
{
parent: parentCall,
propagate_flags: propagate.DEFAULTS // Propagate all supported flags
},
(error, response) => {
console.log("Child response:", response);
}
);
// Selective propagation
client.anotherChildMethod(
{ data: "selective" },
{
parent: parentCall,
propagate_flags: propagate.DEADLINE | propagate.CANCELLATION
},
(error, response) => {
console.log("Selective propagation response:", response);
}
);
// Custom propagation logic
function makeChildCall(parentCall: any, data: any) {
let flags = 0;
// Always propagate deadlines
flags |= propagate.DEADLINE;
// Propagate tracing in production
if (process.env.NODE_ENV === 'production') {
flags |= propagate.CENSUS_TRACING_CONTEXT;
}
// Propagate cancellation for user-initiated requests
if (isUserInitiated(parentCall)) {
flags |= propagate.CANCELLATION;
}
return client.childMethod(data, {
parent: parentCall,
propagate_flags: flags
});
}import { compressionAlgorithms } from "@grpc/grpc-js";
// Client with compression
const client = new ServiceClient(address, credentials.createInsecure(), {
'grpc.default_compression_algorithm': compressionAlgorithms.GZIP,
'grpc.compression_enabled': 1
});
// Per-call compression
client.sendLargeData(
{ payload: largeDataBuffer },
{
// Override default compression for this call
compression: compressionAlgorithms.DEFLATE
},
(error, response) => {
console.log("Compressed call response:", response);
}
);
// Server with compression support
const server = new Server({
'grpc.default_compression_algorithm': compressionAlgorithms.GZIP
});
// Conditional compression based on message size
function getCompressionForMessage(message: any): compressionAlgorithms {
const messageSize = JSON.stringify(message).length;
if (messageSize > 1024) { // 1KB threshold
return compressionAlgorithms.GZIP;
} else if (messageSize > 512) { // 512B threshold
return compressionAlgorithms.DEFLATE;
} else {
return compressionAlgorithms.IDENTITY; // No compression
}
}import { status, Metadata } from "@grpc/grpc-js";
// Complete status object with metadata
interface StatusObject {
code: status;
details: string;
metadata: Metadata;
}
// Server sending detailed error status
server.addService(serviceDefinition, {
processData: (call, callback) => {
try {
const result = processData(call.request);
callback(null, result);
} catch (error) {
const errorMetadata = new Metadata();
errorMetadata.set('x-error-id', generateErrorId());
errorMetadata.set('x-retry-after', '300');
const statusObject: StatusObject = {
code: status.INTERNAL,
details: `Processing failed: ${error.message}`,
metadata: errorMetadata
};
callback(statusObject);
}
}
});
// Client handling detailed status
client.processData({ input: "data" }, (error, response) => {
if (error) {
const statusObj = error as StatusObject;
console.error(`Error ${statusObj.code}: ${statusObj.details}`);
// Extract error metadata
const errorId = statusObj.metadata?.get('x-error-id')[0];
const retryAfter = statusObj.metadata?.get('x-retry-after')[0];
console.error(`Error ID: ${errorId}`);
if (retryAfter) {
console.error(`Retry after ${retryAfter} seconds`);
}
return;
}
console.log("Success:", response);
});import {
status,
connectivityState,
logVerbosity,
compressionAlgorithms
} from "@grpc/grpc-js";
// Configuration object using constants
const grpcConfig = {
retryableStatuses: [
status.UNAVAILABLE,
status.DEADLINE_EXCEEDED,
status.RESOURCE_EXHAUSTED
],
readyStates: [
connectivityState.READY
],
connectingStates: [
connectivityState.IDLE,
connectivityState.CONNECTING
],
logLevel: process.env.NODE_ENV === 'development'
? logVerbosity.DEBUG
: logVerbosity.ERROR,
compressionEnabled: true,
defaultCompression: compressionAlgorithms.GZIP
};
// Use configuration
function shouldRetry(statusCode: status): boolean {
return grpcConfig.retryableStatuses.includes(statusCode);
}
function isChannelReady(state: connectivityState): boolean {
return grpcConfig.readyStates.includes(state);
}
function isChannelConnecting(state: connectivityState): boolean {
return grpcConfig.connectingStates.includes(state);
}