@nestjs/microservices
Version:
Microservices for NestJS: message and event handlers over Kafka, RabbitMQ, NATS, Redis, MQTT, gRPC or TCP.
362 lines (361 loc) • 15.9 kB
JavaScript
import { createRequire } from 'module';
import { Observable } from 'rxjs';
import { GRPC_DEFAULT_PROTO_LOADER, GRPC_DEFAULT_URL } from '../constants.js';
import { GrpcStatus } from '../enums/index.js';
import { InvalidGrpcPackageException } from '../errors/invalid-grpc-package.exception.js';
import { InvalidGrpcServiceException } from '../errors/invalid-grpc-service.exception.js';
import { InvalidProtoDefinitionException } from '../errors/invalid-proto-definition.exception.js';
import { getGrpcPackageDefinition } from '../helpers/index.js';
import { hasPacketMetadata } from '../utils/packet-metadata.utils.js';
import { ClientProxy } from './client-proxy.js';
import { Logger } from '@nestjs/common';
import { loadPackageSync, isFunction, isNil, isObject, } from '@nestjs/common/internal';
const GRPC_CANCELLED = 'Cancelled';
/**
* Values `@grpc/grpc-js` reads after the request: metadata, then call
* options. It does not skip a nil value: one before a `CallOptions` object
* hides that object, and one in front of the unary-response callback is
* taken as the call options and then read as `options.interceptors`.
*/
function getArgumentsAfterRequest(hookedArgs) {
return hookedArgs.slice(1).filter(value => !isNil(value));
}
let grpcPackage = {};
let grpcProtoLoaderPackage = {};
/**
* @publicApi
*/
export class ClientGrpcProxy extends ClientProxy {
options;
logger = new Logger(ClientProxy.name);
clients = new Map();
url;
grpcClients = [];
get status() {
throw new Error('The "status" attribute is not supported by the gRPC transport');
}
constructor(options) {
super();
this.options = options;
this.url = this.getOptionsProp(options, 'url') || GRPC_DEFAULT_URL;
const protoLoader = this.getOptionsProp(options, 'protoLoader') || GRPC_DEFAULT_PROTO_LOADER;
// Loaded synchronously, unlike the packages of the other transports:
// getService() is synchronous and the clients are created right here.
// Bundlers such as esbuild cannot follow createRequire(), so applications
// bundling a gRPC client have to mark these packages as external.
grpcPackage = loadPackageSync('@grpc/grpc-js', ClientGrpcProxy.name, () => createRequire(import.meta.url)('@grpc/grpc-js'));
grpcProtoLoaderPackage = loadPackageSync(protoLoader, ClientGrpcProxy.name, () => createRequire(import.meta.url)(protoLoader));
this.grpcClients = this.createClients();
}
getService(name) {
const grpcClient = this.getClientByServiceName(name);
const clientRef = this.getClient(name);
if (!clientRef) {
throw new InvalidGrpcServiceException(name);
}
const protoMethods = Object.keys(clientRef[name].prototype);
const grpcService = {};
protoMethods.forEach(m => {
grpcService[m] = this.createServiceMethod(grpcClient, m);
});
return grpcService;
}
getClientByServiceName(name) {
return this.clients.get(name) || this.createClientByServiceName(name);
}
createClientByServiceName(name) {
const clientRef = this.getClient(name);
if (!clientRef) {
throw new InvalidGrpcServiceException(name);
}
// A copy, so the limits below never reach an object the caller may share
const channelOptions = {
...this.options?.channelOptions,
};
if (this.options && this.options.maxSendMessageLength) {
channelOptions['grpc.max_send_message_length'] =
this.options.maxSendMessageLength;
}
if (this.options && this.options.maxReceiveMessageLength) {
channelOptions['grpc.max_receive_message_length'] =
this.options.maxReceiveMessageLength;
}
if (this.options && this.options.maxMetadataSize) {
channelOptions['grpc.max_metadata_size'] = this.options.maxMetadataSize;
}
const keepaliveOptions = this.getKeepaliveOptions();
const options = {
...channelOptions,
...keepaliveOptions,
};
const credentials = this.options.credentials || grpcPackage.credentials.createInsecure();
const grpcClient = new clientRef[name](this.url, credentials, options);
this.clients.set(name, grpcClient);
return grpcClient;
}
getKeepaliveOptions() {
if (!isObject(this.options.keepalive)) {
return {};
}
const keepaliveKeys = {
keepaliveTimeMs: 'grpc.keepalive_time_ms',
keepaliveTimeoutMs: 'grpc.keepalive_timeout_ms',
keepalivePermitWithoutCalls: 'grpc.keepalive_permit_without_calls',
http2MaxPingsWithoutData: 'grpc.http2.max_pings_without_data',
http2MinTimeBetweenPingsMs: 'grpc.http2.min_time_between_pings_ms',
http2MinPingIntervalWithoutDataMs: 'grpc.http2.min_ping_interval_without_data_ms',
http2MaxPingStrikes: 'grpc.http2.max_ping_strikes',
};
const keepaliveOptions = {};
for (const [optionKey, optionValue] of Object.entries(this.options.keepalive)) {
const key = keepaliveKeys[optionKey];
if (key === undefined) {
continue;
}
keepaliveOptions[key] = optionValue;
}
return keepaliveOptions;
}
createServiceMethod(client, methodName) {
return client[methodName].responseStream
? this.createStreamServiceMethod(client, methodName)
: this.createUnaryServiceMethod(client, methodName);
}
createStreamServiceMethod(client, methodName) {
return (...args) => {
const isRequestStream = client[methodName].requestStream;
const stream = new Observable(observer => {
let isClientCanceled = false;
let upstreamSubscription = null;
const callArgs = this.applyDispatchHook(client, methodName, args);
const upstreamSubjectOrData = callArgs[0];
const isUpstreamSubject = upstreamSubjectOrData && isFunction(upstreamSubjectOrData.subscribe);
const call = isRequestStream && isUpstreamSubject
? client[methodName](...getArgumentsAfterRequest(callArgs))
: client[methodName](...callArgs.slice(0, 1), ...getArgumentsAfterRequest(callArgs));
if (isRequestStream && isUpstreamSubject) {
upstreamSubscription = this.writeRequestStream(call, upstreamSubjectOrData, observer);
}
call.on('data', (data) => observer.next(data));
call.on('error', (error) => {
if (error.details === GRPC_CANCELLED) {
call.destroy();
if (isClientCanceled) {
return;
}
}
observer.error(this.serializeError(error));
});
call.on('end', () => {
if (upstreamSubscription) {
upstreamSubscription.unsubscribe();
upstreamSubscription = null;
}
call.removeAllListeners();
observer.complete();
});
return () => {
if (upstreamSubscription) {
upstreamSubscription.unsubscribe();
upstreamSubscription = null;
}
if (call.finished) {
return undefined;
}
isClientCanceled = true;
call.cancel();
};
});
return stream;
};
}
createUnaryServiceMethod(client, methodName) {
return (...args) => {
const isRequestStream = client[methodName].requestStream;
const upstreamSubjectOrData = args[0];
const isUpstreamSubject = upstreamSubjectOrData && isFunction(upstreamSubjectOrData.subscribe);
if (isRequestStream && isUpstreamSubject) {
return new Observable(observer => {
let isClientCanceled = false;
const callArgs = [
(error, data) => {
if (error) {
if (error.details === GRPC_CANCELLED || error.code === 1) {
call.destroy();
if (isClientCanceled) {
return;
}
}
return observer.error(this.serializeError(error));
}
observer.next(data);
observer.complete();
},
];
callArgs.unshift(...getArgumentsAfterRequest(this.applyDispatchHook(client, methodName, args)));
const call = client[methodName](...callArgs);
const upstreamSubscription = this.writeRequestStream(call, upstreamSubjectOrData, observer);
return () => {
upstreamSubscription.unsubscribe();
if (!call.finished) {
isClientCanceled = true;
call.cancel();
}
};
});
}
return new Observable(observer => {
const callArgs = this.applyDispatchHook(client, methodName, args);
const call = client[methodName](...callArgs.slice(0, 1), ...getArgumentsAfterRequest(callArgs), (error, data) => {
if (error) {
return observer.error(this.serializeError(error));
}
observer.next(data);
observer.complete();
});
return () => {
if (!call.finished) {
call.cancel();
}
};
});
};
}
/**
* Writes the values of a request stream to the call, and ends the call once
* the stream completes.
*
* The call is an object mode stream, whose "write" throws on null where
* nothing catches it, so null fails the call instead, as a null response
* does on the server. What a request stream emits synchronously after the
* null, while it cannot be unsubscribed from yet, is not sent either, so
* the server cannot take the rest of the stream for all of it.
*/
writeRequestStream(call, upstream, observer) {
let isFailed = false;
return upstream.subscribe((val) => {
if (isFailed) {
return;
}
if (val === null) {
isFailed = true;
return observer.error(this.serializeError(this.createNullRequestError()));
}
call.write(val);
}, (err) => observer.error(this.serializeError(err)), () => !isFailed && call.end());
}
createNullRequestError() {
const details = 'The request stream emitted a null value';
return Object.assign(new Error(details), {
code: GrpcStatus.INTERNAL,
details,
});
}
/**
* Runs the dispatch hook for a call - gRPC calls do not go through `send()`
* or `emit()` - once per subscription, in the subscriber's context.
*
* Returns the arguments to make the call with: the caller's, with the
* metadata the hook attached added to the call's `Metadata` under every key
* the caller did not set. A `Metadata` the caller passed is cloned rather
* than changed, as it may be reused for other calls.
*/
applyDispatchHook(client, methodName, args) {
if (!this.onDispatchHook) {
return args;
}
// A gRPC method is known by its path, e.g. "/hero.HeroesService/FindOne"
const pattern = client[methodName]?.path ?? methodName;
const packet = this.createPacket(pattern, args[0]);
if (!hasPacketMetadata(packet.metadata)) {
return args;
}
const [data, maybeMetadata, ...rest] = args;
const isMetadata = maybeMetadata instanceof grpcPackage.Metadata;
const metadata = isMetadata
? maybeMetadata.clone()
: new grpcPackage.Metadata();
for (const [key, value] of Object.entries(packet.metadata)) {
if (metadata.get(key).length === 0) {
metadata.set(key, value);
}
}
// Call options passed in place of the metadata move one place along
return isMetadata || isNil(maybeMetadata)
? [data, metadata, ...rest]
: [data, metadata, maybeMetadata, ...rest];
}
createClients() {
const grpcContext = this.loadProto();
const packageOption = this.getOptionsProp(this.options, 'package');
const grpcPackages = [];
const packageNames = Array.isArray(packageOption)
? packageOption
: [packageOption];
for (const packageName of packageNames) {
const grpcPkg = this.lookupPackage(grpcContext, packageName);
if (!grpcPkg) {
const invalidPackageError = new InvalidGrpcPackageException(packageName);
this.logger.error(invalidPackageError.message, invalidPackageError.stack);
throw invalidPackageError;
}
grpcPackages.push(grpcPkg);
}
return grpcPackages;
}
loadProto() {
try {
const packageDefinition = getGrpcPackageDefinition(this.options, grpcProtoLoaderPackage);
return grpcPackage.loadPackageDefinition(packageDefinition);
}
catch (err) {
const invalidProtoError = new InvalidProtoDefinitionException(err.path);
const message = err && err.message ? err.message : invalidProtoError.message;
this.logger.error(message, invalidProtoError.stack);
throw invalidProtoError;
}
}
lookupPackage(root, packageName) {
/** Reference: https://github.com/kondi/rxjs-grpc */
let pkg = root;
if (packageName) {
for (const name of packageName.split('.')) {
if (!pkg) {
break;
}
pkg = pkg[name];
}
}
return pkg;
}
close() {
this.clients.forEach(client => {
if (client && isFunction(client.close)) {
client.close();
}
});
this.clients.clear();
this.grpcClients = [];
}
async connect() {
throw new Error('The "connect()" method is not supported in gRPC mode.');
}
send(pattern, data) {
throw new Error('Method is not supported in gRPC mode. Use ClientGrpc instead (learn more in the documentation).');
}
getClient(name) {
return this.grpcClients.find(client => Object.hasOwn(client, name));
}
publish(packet, callback) {
throw new Error('Method is not supported in gRPC mode. Use ClientGrpc instead (learn more in the documentation).');
}
async dispatchEvent(packet) {
throw new Error('Method is not supported in gRPC mode. Use ClientGrpc instead (learn more in the documentation).');
}
on(event, callback) {
throw new Error('Method is not supported in gRPC mode.');
}
unwrap() {
throw new Error('Method is not supported in gRPC mode.');
}
}