@nestjs/microservices
Version:
Microservices for NestJS: message and event handlers over Kafka, RabbitMQ, NATS, Redis, MQTT, gRPC or TCP.
445 lines (444 loc) • 18 kB
JavaScript
import { connectable, EMPTY, from as fromPromise, isObservable, of, ReplaySubject, Subject, throwError, } from 'rxjs';
import { catchError, distinctUntilChanged, finalize, mergeMap, } from 'rxjs/operators';
import { DEFAULT_GRACE_PERIOD, EVENT_HANDLER_REPLY_DEPRECATED, MAX_TIMEOUT, NO_EVENT_HANDLER, UNSERIALIZABLE_PATTERN, } from '../constants.js';
import { IncomingRequestDeserializer } from '../deserializers/incoming-request.deserializer.js';
import { InvalidPacketIdException } from '../errors/invalid-packet-id.exception.js';
import { IdentitySerializer } from '../serializers/identity.serializer.js';
import { exceedsPatternLimits, transformPatternToRoute, } from '../utils/index.js';
import { Logger } from '@nestjs/common';
import { isNil, isNumber, isString, loadPackage, loadPackageSync, } from '@nestjs/common/internal';
import { MESSAGES } from '@nestjs/core/internal';
const MAX_PACKET_ID_LENGTH = 256;
// Matches every text JSON.parse() accepts. A string pattern it does not match
// (e.g. "user.created") is used as it is, as parsing it would only throw.
const JSON_TEXT = /^\s*(?:[{["\-\d]|(?:true|false|null)\s*$)/;
// Far longer than the route of any pattern within the limits of a route, and
// short enough for parsing it to stay cheap
const MAX_JSON_PATTERN_LENGTH = 1024 * 1024;
/**
* @publicApi
*/
export class Server {
/**
* Unique transport identifier.
*/
transportId;
messageHandlers = new Map();
logger = new Logger(Server.name);
/**
* Event handlers that have replied to a request, so that the deprecation
* is logged once per pattern.
*/
eventHandlersThatReplied = new WeakSet();
/**
* Whether this transport hands an event handler failure to its client
* library, which then reports it. The base `handleEvent` connects the
* stream without subscribing, so nothing observes the failure and Nest logs
* it instead. `ServerKafka` awaits the stream and sets this to `true`.
*/
propagatesEventHandlerErrors = false;
serializer;
deserializer;
onProcessingStartHook = (transportId, context, done) => done();
onProcessingEndHook;
_status$ = new ReplaySubject(1);
/**
* Requests and events being handled. A request stays counted until its last
* reply has been published.
*/
handlersInFlight = 0;
handlersInFlightListeners = new Set();
/**
* Returns an observable that emits status changes.
*/
get status() {
return this._status$.asObservable().pipe(distinctUntilChanged());
}
/**
* Sets the transport identifier.
* @param transportId Unique transport identifier.
*/
setTransportId(transportId) {
this.transportId = transportId;
}
/**
* Sets a hook that will be called when processing starts.
*/
setOnProcessingStartHook(hook) {
this.onProcessingStartHook = hook;
}
/**
* Sets a hook that will be called when processing ends.
*/
setOnProcessingEndHook(hook) {
this.onProcessingEndHook = hook;
}
addHandler(pattern, callback, isEventHandler = false, extras = {}) {
const normalizedPattern = this.normalizePattern(pattern);
callback.isEventHandler = isEventHandler;
callback.extras = extras;
if (this.messageHandlers.has(normalizedPattern) && isEventHandler) {
const headRef = this.messageHandlers.get(normalizedPattern);
const getTail = (handler) => handler?.next ? getTail(handler.next) : handler;
const tailRef = getTail(headRef);
tailRef.next = callback;
}
else {
this.messageHandlers.set(normalizedPattern, callback);
}
}
getHandlers() {
return this.messageHandlers;
}
getHandlerByPattern(pattern) {
// A string pattern such as '1.0' or 'true' is stored as it is, but parsing
// it as json would turn it into another route, so it is tried first.
if (this.messageHandlers.has(pattern)) {
return this.messageHandlers.get(pattern);
}
const route = this.getRouteFromPattern(pattern);
return this.messageHandlers.has(route)
? this.messageHandlers.get(route)
: null;
}
send(stream$, respond) {
const dataQueue = [];
// The queue is read through an index and emptied once drained, as each
// shift() would move all the packets queued behind the one it removes
let nextIndex = 0;
let isProcessing = false;
// The requester is answered with an error in place of a final reply that
// cannot be published only once, as that error may fail to publish too
let isFallbackQueued = false;
// The response stream has settled, so the queue holds its last reply
let isStreamSettled = false;
const settleHandlerInFlight = this.trackHandlerInFlight();
const scheduleOnNextTick = (data) => {
if (data.isDisposed && dataQueue.length > nextIndex) {
dataQueue[dataQueue.length - 1].isDisposed = true;
}
else {
dataQueue.push(data);
}
if (!isProcessing) {
isProcessing = true;
process.nextTick(async () => {
while (nextIndex < dataQueue.length) {
const packet = dataQueue[nextIndex++];
try {
await respond(packet);
}
catch (err) {
// A reply that cannot be published must neither surface as an
// unhandled rejection nor stop the replies queued behind it.
// When it was the last one, the requester still gets an error.
this.logger.error(err);
if (packet.isDisposed && !isFallbackQueued) {
isFallbackQueued = true;
dataQueue.push({
err: {
status: 'error',
message: MESSAGES.UNKNOWN_EXCEPTION_MESSAGE,
},
isDisposed: true,
});
}
}
}
dataQueue.length = 0;
nextIndex = 0;
isProcessing = false;
if (isStreamSettled) {
settleHandlerInFlight();
}
});
}
};
return stream$
.pipe(catchError((err) => {
scheduleOnNextTick({ err });
return EMPTY;
}), finalize(() => {
isStreamSettled = true;
scheduleOnNextTick({ isDisposed: true });
}))
.subscribe((response) => scheduleOnNextTick({ response }));
}
/**
* @param handler - the handler of `pattern`, if it was looked up already
*/
async handleEvent(pattern, packet, context, handler = this.getHandlerByPattern(pattern)) {
if (!handler) {
return this.logger.error(NO_EVENT_HANDLER `${pattern}`);
}
return this.runWithProcessingHooks(context, async (runEndHook) => {
const resultOrStream = await handler(packet.data, context);
if (isObservable(resultOrStream)) {
const connectableSource = connectable(resultOrStream.pipe(finalize(runEndHook)), {
connector: () => new Subject(),
resetOnDisconnect: false,
});
connectableSource.connect();
}
else {
runEndHook();
}
});
}
/**
* Handles a request-response message. `produce` returns the response
* stream, whose values are replied through `respond`, and the processing
* end hook runs once that stream settles (or once `produce` rejects).
*/
handleRequest(context, produce, respond) {
return this.runWithProcessingHooks(context, async (runEndHook) => {
let response$;
try {
response$ = await produce();
}
catch (err) {
// The handler promise rejected. An inherited HTTP filter does this
// when it replies through host.switchToHttp().getResponse(): on RPC
// that object is the context, so the reply throws. gRPC fails the
// call with INTERNAL. Answer here too, then rethrow so the transport
// still logs the rejection.
if (this.shouldAnswerRejectedRequest(err)) {
this.send(throwError(() => ({
status: 'error',
message: MESSAGES.UNKNOWN_EXCEPTION_MESSAGE,
})).pipe(finalize(runEndHook)), respond);
}
throw err;
}
this.send(response$.pipe(finalize(runEndHook)), respond);
});
}
/**
* Whether a request is answered with an error when `produce` rejects with
* `err`, rather than only passing the rejection on to the transport.
*/
shouldAnswerRejectedRequest(err) {
return true;
}
/**
* Logs a deprecation warning the first time an event handler is about to
* reply to a request (a packet with an id, sent with `ClientProxy#send`).
* Event handlers still reply to requests, except on Kafka, but will not in
* the next major version.
*/
warnIfEventHandlerReplies(handler, pattern) {
if (!handler.isEventHandler || this.eventHandlersThatReplied.has(handler)) {
return;
}
this.eventHandlersThatReplied.add(handler);
this.logger.warn(EVENT_HANDLER_REPLY_DEPRECATED `${pattern}`);
}
/**
* Runs `fn` between the processing start and end hooks.
*
* `fn` receives a runner that closes the span exactly once and attaches it
* to the teardown of whatever stream it produces. If `fn` rejects before
* that teardown can run, the span is closed here and the rejection travels
* on to the transport's client library.
*
* `endHookContext` is for transports that report a different context to
* the end hook than to the start hook (gRPC passes the request).
*/
runWithProcessingHooks(context, fn, endHookContext = context) {
return this.onProcessingStartHook(this.transportId, context, async () => {
const settleHandlerInFlight = this.trackHandlerInFlight();
const runEndHook = this.createProcessingEndHookRunner(endHookContext);
const end = () => {
runEndHook();
settleHandlerInFlight();
};
try {
await fn(end);
}
catch (err) {
end();
throw err;
}
});
}
/**
* Resolves once no request or event is being handled, or after
* `gracePeriod` milliseconds, whichever comes first. The period is 10
* seconds unless a number is given.
*
* A transport calls it from `close()`, after it has stopped receiving
* messages and before it closes its connection, so that the handlers in
* flight can finish and publish their replies. A handler whose stream never
* completes stays in flight, so the wait then lasts the whole period.
*
* A message counts from the moment its handling starts, once it has been
* deserialized. With an asynchronous deserializer, a message received right
* before `close()` may not be counted yet, so its handler can still run
* after the connection has been closed.
*/
waitForHandlersInFlight(gracePeriod) {
if (this.handlersInFlight === 0) {
return Promise.resolve();
}
const timeout = this.normalizeGracePeriod(gracePeriod);
return new Promise(resolve => {
const stopWaiting = () => {
clearTimeout(timer);
this.handlersInFlightListeners.delete(stopWaiting);
resolve();
};
const timer = setTimeout(stopWaiting, timeout);
this.handlersInFlightListeners.add(stopWaiting);
});
}
/**
* Reads `gracePeriod` the same way for every transport: a value that is not
* a number (NaN, "10s") gets the default period rather than none, a string
* such as "5000" (e.g. from an environment variable) is a number, and a
* longer one than a timer supports (e.g. Infinity, to wait until the
* handlers are done) is capped.
*/
normalizeGracePeriod(gracePeriod) {
return Math.min(isNil(gracePeriod) || isNaN(gracePeriod)
? DEFAULT_GRACE_PERIOD
: Number(gracePeriod), MAX_TIMEOUT);
}
/**
* Counts a handler as in flight until the returned function is called.
* Calling it again does nothing.
*/
trackHandlerInFlight() {
this.handlersInFlight++;
let isSettled = false;
return () => {
if (isSettled) {
return;
}
isSettled = true;
this.handlersInFlight--;
if (this.handlersInFlight === 0) {
this.handlersInFlightListeners.forEach(listener => listener());
}
};
}
/**
* Returns a function that runs the processing end hook exactly once.
*
* An event handler can fail either by rejecting or by returning a stream
* that errors, and `ServerKafka#handleEvent` awaits that stream, so both the
* `finalize` teardown and the `catch` block can be reached for a single
* event. The hook closes a span, so it must not run twice.
*/
createProcessingEndHookRunner(context) {
let isEndHookCalled = false;
return () => {
if (isEndHookCalled) {
return;
}
isEndHookCalled = true;
this.onProcessingEndHook?.(this.transportId, context);
};
}
transformToObservable(resultOrDeferred) {
if (resultOrDeferred instanceof Promise) {
return fromPromise(resultOrDeferred).pipe(mergeMap(val => (isObservable(val) ? val : of(val))));
}
if (isObservable(resultOrDeferred)) {
return resultOrDeferred;
}
return of(resultOrDeferred);
}
getOptionsProp(obj, prop, defaultValue = undefined) {
return obj && prop in obj ? obj[prop] : defaultValue;
}
handleError(error) {
this.logger.error(error);
}
loadPackage(name, ctx, loader) {
return loadPackage(name, ctx, loader);
}
loadPackageSynchronously(name, ctx, loader) {
return loadPackageSync(name, ctx, loader);
}
initializeSerializer(options) {
this.serializer =
(options &&
options.serializer) ||
new IdentitySerializer();
}
initializeDeserializer(options) {
this.deserializer =
(options &&
options.deserializer) ||
new IncomingRequestDeserializer();
}
/**
* Transforms the server Pattern to valid type and returns a route for him.
*
* @param {string} pattern - server pattern
* @returns string
*/
getRouteFromPattern(pattern) {
let validPattern;
try {
// Parsing a longer one would cost many times its size, only for its
// route to say that it exceeds the limits of a route
validPattern =
pattern.length <= MAX_JSON_PATTERN_LENGTH && JSON_TEXT.test(pattern)
? JSON.parse(pattern)
: pattern;
}
catch (error) {
// Uses a fundamental object (`pattern` variable without any conversion)
validPattern = pattern;
}
return this.normalizePattern(validPattern);
}
normalizePattern(pattern) {
return transformPatternToRoute(pattern);
}
/**
* Returns the string representation of an incoming message pattern.
*
* Patterns are client-controlled: serializing a deeply nested one makes
* `JSON.stringify` throw a `RangeError`, which must not escape the message
* handler (as an unhandled promise rejection that terminates the process).
*
* A pattern that exceeds the limits of a route is not serialized at all:
* its handler would be looked up by parsing the text again, at several
* times its size in memory, only for its route to say which limit it
* exceeds. That route is returned instead.
*
* @param {unknown} pattern - client pattern
* @returns string
*/
getPatternAsString(pattern) {
if (isString(pattern)) {
return pattern;
}
if (exceedsPatternLimits(pattern)) {
return this.normalizePattern(pattern);
}
try {
return JSON.stringify(pattern);
}
catch {
return UNSERIALIZABLE_PATTERN;
}
}
/**
* Throws unless the id of an incoming request is a number or a short string.
*
* Ids are client-controlled and every reply to the request carries a copy,
* so a long string or a nested value would be copied and serialized once
* per reply, which a handler that streams its response multiplies.
*
* @param {unknown} id - request id
*/
assertValidPacketId(id) {
if (isNumber(id) || (isString(id) && id.length <= MAX_PACKET_ID_LENGTH)) {
return;
}
throw new InvalidPacketIdException(MAX_PACKET_ID_LENGTH);
}
}