@adeshsuryan/grpc-client-core
v0.1.1
Published
Typed, production-safe gRPC client factory for Node.js: shared channel lifecycle, credentials, deadlines, metadata, bounded retries, error mapping, and correlation. Framework-agnostic; pairs with a server-only adapter for Next.js.
Maintainers
Readme
grpc-client-core

Typed, production-safe gRPC client factory for Node.js: ownership-safe
client pooling, TLS credentials, total deadlines, AbortSignal
cancellation, explicit bounded retries, normalized errors, safe structured
events, and request correlation — over @grpc/grpc-js.
Node-only, unary-only. A server-only Next.js adapter lives in a separate
package (grpc-next-toolkit).
Install
npm install @adeshsuryan/grpc-client-coreRequires Node.js >= 20. Runtime dependency: @grpc/grpc-js only.
Quickstart
import { createGrpcClient } from "@adeshsuryan/grpc-client-core";
import { EchoServiceClient } from "./gen/echo"; // ts-proto / grpc-tools output
const client = createGrpcClient(EchoServiceClient, {
address: process.env.ECHO_GRPC_URL!, // e.g. "dns:///echo:443"
credentials: "tls", // default; "insecure" is local dev only
timeoutMs: 5000, // total per-call deadline
metadata: { "x-tenant": "acme" },
});
// request/response types are inferred from the generated client
const res = await client.invoke("echo", { msg: "hi" }, { deadlineMs: 3000 });
await client.close(); // graceful shutdownCore behavior
- Pooled client resources. Handles with the same constructor, address,
credential identity, and channel options share one underlying
client/channel — never a channel per request. Distinct custom
ChannelCredentialsobjects always isolate. Registry capacity: 256 live resources by default (createClientRegistry({ capacity })to change or isolate for tests). - Ownership.
close(graceMs?)stops new calls on this handle, drains its in-flight calls (default grace 10s, then cancels stragglers), and releases its ownership — other handles sharing the resource are unaffected.destroy()cancels this handle's calls immediately. The resource closes when its last owner releases. - Total deadline.
timeoutMs/deadlineMsproduce one absolute deadline shared across all retries and backoff — never per-attempt. - Cancellation.
AbortSignalcancels the in-flight call server-observably; an already-aborted signal dispatches nothing. Cancellation origin is exposed (caller|shutdown|deadline|remote). - Metadata. Static + per-call merge; per-call keys replace all base
values for that key; repeated and binary
-binvalues fromMetadatainstances are preserved.withCorrelationId(id, meta)sets a validatedx-request-id. - Bounded retries — opt-in only. Config requires an
idempotent: truedeclaration at the call or per-method level:
createGrpcClient(Svc, {
address, credentials: "tls",
methodPolicies: {
getUser: {
idempotent: true,
retry: { maxAttempts: 3, backoff: "exponential", baseDelayMs: 100, maxDelayMs: 2000, jitter: true },
},
},
});Defaults: maxAttempts 1–10 including first attempt; default allowlist
{UNAVAILABLE}; explicit retryableStatusCodes replaces it;
CANCELLED/DEADLINE_EXCEEDED are forbidden; caller cancellation is
always terminal; transport-level grpc.enable_retries is disabled and
conflicts are rejected. Only retry idempotent operations.
- Errors. Every failure is a
GrpcError—{ code, grpcStatus, retryable, details, metadata, cancelOrigin }. Local codes:INVALID_CONFIG,INVALID_METHOD,CLIENT_CLOSED,RESOURCE_LIMIT,MIDDLEWARE_ERROR.toJSON()is sanitized for logging. - Events. Silent by default. Optional
loggerreceives safe structured events (call.start,attempt.start,attempt.end,call.retry,call.end,call.error,channel.state,channel.close) — no payloads, errors, or credential material. - Middleware.
middleware: [async (ctx, next) => next()]wraps the logical call once (not per attempt);nextis single-use; middleware errors map toMIDDLEWARE_ERROR. - Health boundary.
waitForReady/getConnectivityStatereport channel connectivity only — not service health.
API
const client = createGrpcClient(ServiceCtor, config, registry?);
await client.invoke(method, req, { deadlineMs, metadata, signal, retry, idempotent });
await client.waitForReady(5000);
client.getConnectivityState(false); // "READY" | "IDLE" | ... ; false = observe only
await client.close(graceMs?);
client.destroy();
createClientRegistry({ capacity? }); // isolated registry for testsLimitations
Unary calls only — streaming methods are rejected (INVALID_METHOD).
Node.js server runtimes only. Channel connectivity is not application
health. Retries never make a non-idempotent operation safe.
Development
npm install
npm run build # dual CJS+ESM emit into dist/
npm test # build + typecheck + node --test (real local servers)
npm run gen:proto # regenerate test fixture (test/proto/echo.proto)Licence
MIT — see LICENSE.
