@nestjs/websockets
Version:
WebSockets for NestJS: gateways with message handlers, guards, pipes and interceptors, on Socket.IO or ws.
478 lines (477 loc) • 23.9 kB
JavaScript
import { from as fromPromise, isObservable, of, } from 'rxjs';
import { distinctUntilChanged, mergeAll } from 'rxjs/operators';
import { GATEWAY_OPTIONS, MESSAGE_METADATA, PORT_METADATA, } from './constants.js';
import { InvalidSocketPortException } from './errors/invalid-socket-port.exception.js';
import { GatewayMetadataExplorer, } from './gateway-metadata-explorer.js';
import { compareElementAt } from './utils/compare-element.util.js';
import { isFunction } from '@nestjs/common/internal';
import { Logger } from '@nestjs/common';
import { ContextIdFactory, MetadataScanner, } from '@nestjs/core';
import { ExecutionContextHost, REQUEST_CONTEXT_ID, STATIC_CONTEXT, } from '@nestjs/core/internal';
export class WebSocketsController {
socketServerProvider;
config;
contextCreator;
container;
injector;
exceptionFiltersContext;
graphInspector;
appOptions;
isAcceptingClients;
logger = new Logger(WebSocketsController.name, {
timestamp: true,
});
metadataExplorer = new GatewayMetadataExplorer(new MetadataScanner());
pendingDisconnects = new WeakMap();
// For each gateway resolved per connection, a promise per client that
// settles once its connection hook has been called
connectionHookCalls = new WeakMap();
constructor(socketServerProvider, config, contextCreator, container, injector, exceptionFiltersContext, graphInspector, appOptions = {}, isAcceptingClients = () => true) {
this.socketServerProvider = socketServerProvider;
this.config = config;
this.contextCreator = contextCreator;
this.container = container;
this.injector = injector;
this.exceptionFiltersContext = exceptionFiltersContext;
this.graphInspector = graphInspector;
this.appOptions = appOptions;
this.isAcceptingClients = isAcceptingClients;
}
connectGatewayToServer(instanceOrWrapper, metatypeOrModuleKey, moduleKey, instanceWrapperId) {
const isInstanceWrapper = typeof metatypeOrModuleKey === 'string' &&
'instance' in instanceOrWrapper;
const instance = isInstanceWrapper
? instanceOrWrapper.instance
: instanceOrWrapper;
const metatype = isInstanceWrapper
? instanceOrWrapper.metatype
: metatypeOrModuleKey;
const targetModuleKey = isInstanceWrapper
? metatypeOrModuleKey
: moduleKey;
const targetInstanceWrapperId = isInstanceWrapper
? instanceOrWrapper.id
: instanceWrapperId;
const instanceWrapper = isInstanceWrapper
? instanceOrWrapper
: {
instance,
metatype,
id: targetInstanceWrapperId,
isDependencyTreeStatic: () => true,
isDependencyTreeDurable: () => false,
getEnhancersMetadata: () => [],
};
const gatewayMetatype = metatype ?? instance.constructor;
const options = Reflect.getMetadata(GATEWAY_OPTIONS, gatewayMetatype) || {};
const port = Reflect.getMetadata(PORT_METADATA, gatewayMetatype) ?? 0;
if (!Number.isInteger(port)) {
throw new InvalidSocketPortException(port, gatewayMetatype);
}
this.subscribeToServerEvents(instanceWrapper, options, port, targetModuleKey, targetInstanceWrapperId);
}
subscribeToServerEvents(instanceOrWrapper, options, port, moduleKey, instanceWrapperId) {
const instanceWrapper = 'instance' in instanceOrWrapper
? instanceOrWrapper
: {
instance: instanceOrWrapper,
metatype: instanceOrWrapper.constructor,
id: instanceWrapperId,
isDependencyTreeStatic: () => true,
isDependencyTreeDurable: () => false,
getEnhancersMetadata: () => [],
};
const { instance } = instanceWrapper;
const nativeMessageHandlers = this.metadataExplorer.explore(instance);
const isStatic = instanceWrapper.isDependencyTreeStatic();
const hasGlobalScopedEnhancers = this.getGlobalScopedEnhancers().length > 0;
const moduleRef = this.container.getModuleByKey(moduleKey);
const messageHandlers = nativeMessageHandlers.map(({ callback, isAckHandledManually, message, methodName }) => ({
message,
methodName,
callback: isStatic && !hasGlobalScopedEnhancers
? this.contextCreator.create(instance, callback, moduleKey, methodName, STATIC_CONTEXT, instanceWrapper.id)
: this.createRequestScopedHandler(instanceWrapper, moduleRef, moduleKey, methodName),
isAckHandledManually,
}));
this.inspectEntrypointDefinitions(instance, port, messageHandlers, instanceWrapperId);
if (this.appOptions.preview) {
return;
}
const observableServer = this.socketServerProvider.scanForSocketServer(options, port, (instanceWrapper.metatype ?? instance.constructor)?.name);
this.assignServerToProperties(instance, observableServer.server);
this.subscribeEvents(instanceWrapper, messageHandlers, observableServer, isStatic
? this.createStaticEventHandler(instance, moduleKey, 'handleConnection', instanceWrapper.id)
: this.createRequestScopedEventHandler(instanceWrapper, moduleRef, moduleKey, 'handleConnection', observableServer.server), isStatic && !hasGlobalScopedEnhancers
? this.createStaticEventHandler(instance, moduleKey, 'handleDisconnect', instanceWrapper.id)
: this.createRequestScopedEventHandler(instanceWrapper, moduleRef, moduleKey, 'handleDisconnect', observableServer.server));
}
subscribeEvents(instanceWrapper, subscribersMap, observableServer, connectionHandler, disconnectHandler) {
const { instance } = instanceWrapper;
const { init, disconnect, connection, server } = observableServer;
const adapter = this.config.getIoAdapter();
this.subscribeInitEvent(instance, init);
this.subscribeConnectionEvent(connectionHandler, connection);
this.subscribeDisconnectEvent(disconnectHandler, disconnect);
const handler = this.getConnectionHandler(this, instance, subscribersMap, disconnect, connection);
adapter.bindClientConnect(server, handler);
this.printSubscriptionLogs(instance, subscribersMap);
}
getConnectionHandler(context, instance, subscribersMap, disconnect, connection) {
const adapter = this.config.getIoAdapter();
return (...args) => {
const [client] = args;
if (!this.isAcceptingClients()) {
// The lifecycle hooks of the application are still running, so the
// providers that the gateway, its enhancers and its handlers depend on
// may not be initialized yet. The client is dropped before any of
// them runs, as if the server was not listening yet.
adapter.closeClient?.(client);
return;
}
// Bound before the connection hooks run, since socket.io emits the
// disconnect synchronously when one of them calls client.disconnect().
// Such a disconnect is held back until every gateway sharing this
// server has handled the connection.
let isConnecting = true;
let heldDisconnect;
const disconnectHook = adapter.bindClientDisconnect;
disconnectHook &&
disconnectHook.call(adapter, client, (reason) => {
if (isConnecting) {
heldDisconnect = { reason };
return;
}
disconnect.next({ client, reason });
});
try {
connection.next(args);
context.subscribeMessages(subscribersMap, client, instance);
}
finally {
isConnecting = false;
heldDisconnect &&
disconnect.next({ client, reason: heldDisconnect.reason });
}
};
}
subscribeInitEvent(instance, event) {
if (instance.afterInit) {
event.subscribe(instance.afterInit.bind(instance));
}
}
subscribeConnectionEvent(handlerOrGateway, event) {
const handler = typeof handlerOrGateway === 'function'
? handlerOrGateway
: handlerOrGateway?.handleConnection?.bind(handlerOrGateway);
if (handler) {
event
.pipe(distinctUntilChanged((prev, curr) => compareElementAt(prev, curr, 0)))
.subscribe((args) => handler(...args));
}
}
subscribeDisconnectEvent(handlerOrGateway, event) {
const handler = typeof handlerOrGateway === 'function'
? handlerOrGateway
: handlerOrGateway?.handleDisconnect?.bind(handlerOrGateway);
if (handler) {
event
.pipe(distinctUntilChanged((prev, curr) => {
const prevClient = prev?.client || prev;
const currClient = curr?.client || curr;
return prevClient === currClient;
}))
.subscribe((data) => {
if (data && typeof data === 'object' && 'client' in data) {
handler(data.client, data.reason);
}
else {
// Backward compatibility: if it's just the client
handler(data);
}
});
}
}
subscribeMessages(subscribersMap, client, instance) {
const adapter = this.config.getIoAdapter();
const handlers = subscribersMap.map(({ callback, message, isAckHandledManually }) => ({
message,
callback: callback.bind(instance, client),
isAckHandledManually,
}));
adapter.bindMessageHandlers(client, handlers, data => fromPromise(this.pickResult(data)).pipe(mergeAll()));
}
async pickResult(deferredResult) {
const result = await deferredResult;
if (isObservable(result)) {
return result;
}
if (result instanceof Promise) {
return fromPromise(result);
}
return of(result);
}
inspectEntrypointDefinitions(instance, port, messageHandlers, instanceWrapperId) {
messageHandlers.forEach(handler => {
this.graphInspector.insertEntrypointDefinition({
type: 'websocket',
methodName: handler.methodName,
className: instance.constructor?.name,
classNodeId: instanceWrapperId,
metadata: {
port,
key: handler.message,
message: handler.message,
},
}, instanceWrapperId);
});
}
createRequestScopedHandler(instanceWrapper, moduleRef, moduleKey, methodName) {
const { instance } = instanceWrapper;
const collection = moduleRef.providers;
const isStatic = instanceWrapper.isDependencyTreeStatic();
const isTreeDurable = isStatic
? this.areGlobalScopedEnhancersDurable()
: instanceWrapper.isDependencyTreeDurable();
const scopedEnhancers = [
...(isStatic ? instanceWrapper.getEnhancersMetadata() || [] : []),
...this.getGlobalScopedEnhancers(),
];
const pattern = Reflect.getMetadata(MESSAGE_METADATA, instance[methodName]) ?? 'unknown';
// Kept per gateway, not per handler function: gateways that inherit the
// handler from a base class can declare different filters
let exceptionFilter;
return async (...args) => {
const [client] = args;
try {
const contextId = this.getContextId(client, isTreeDurable);
const contextInstance = isStatic
? instance
: await this.injector.loadPerContext(instance, moduleRef, collection, contextId);
// Resolve global enhancers without adding them to the gateway's dependency
// tree, so a singleton gateway keeps its state and lifecycle hooks.
await this.injector.loadEnhancersPerContext(instanceWrapper, contextId, instanceWrapper, scopedEnhancers);
await this.injector.waitForDeferredLoads(contextId);
return this.contextCreator.create(contextInstance, contextInstance[methodName], moduleKey, methodName, contextId, instanceWrapper.id)(...args);
}
catch (err) {
exceptionFilter ??= this.exceptionFiltersContext.create(instance, instance[methodName], moduleKey);
// The context failed to resolve before `WsProxy` could append the
// pattern, so add it here the same way.
const host = new ExecutionContextHost([...args, pattern]);
host.setType('ws');
// Waited for, as WsProxy does for a message that failed later on
const pending = exceptionFilter.handle(err, host);
if (pending) {
await pending;
}
}
};
}
createRequestScopedEventHandler(instanceWrapper, moduleRef, moduleKey, methodName, server) {
const { instance } = instanceWrapper;
const collection = moduleRef.providers;
const isStatic = instanceWrapper.isDependencyTreeStatic();
const isTreeDurable = isStatic
? this.areGlobalScopedEnhancersDurable()
: instanceWrapper.isDependencyTreeDurable();
const targetCallback = instance[methodName];
const connectionHookCalls = this.getConnectionHookCalls(instanceWrapper);
return async (...args) => {
const [client] = args;
let contextId;
let isResolved = false;
let markConnectionHookAsCalled;
try {
contextId = this.getContextId(client, isTreeDurable);
if (methodName === 'handleDisconnect') {
this.pendingDisconnects.set(contextId, (this.pendingDisconnects.get(contextId) ?? 0) + 1);
// The client can leave while the gateway is still being resolved
// for its connection hook. Nothing else orders the two handlers, and
// the injector could hand the pending instance to this one first.
const connectionHookCall = connectionHookCalls.get(client);
if (connectionHookCall) {
await connectionHookCall;
}
}
else {
connectionHookCalls.set(client, new Promise(resolve => {
markConnectionHookAsCalled = resolve;
}));
}
const contextInstance = isStatic
? instance
: await this.injector.loadPerContext(instance, moduleRef, collection, contextId);
isResolved = true;
if (!isStatic) {
this.assignServerToProperties(contextInstance, server);
}
const scopedMethod = contextInstance[methodName];
const result = scopedMethod?.apply(contextInstance, args);
// Not waited for, as a default-scoped gateway does not wait for its
// connection hook to finish before it handles the disconnect either
markConnectionHookAsCalled?.();
return await result;
}
catch (err) {
if (!targetCallback) {
// The gateway failed to resolve and has no hook whose exception
// filters could handle the error. Nothing awaits this handler, so
// rethrowing would end as an unhandled rejection.
this.logResolutionError(instance, methodName, err);
return;
}
if (!isResolved && contextId) {
// The gateway's enhancers are created in the context of the
// connection along with it, so when it failed to resolve, its
// filters have to be created here.
try {
await this.injector.loadEnhancersPerContext(instanceWrapper, contextId, instanceWrapper);
}
catch {
this.logResolutionError(instance, methodName, err);
return;
}
}
// Built for each connection: a request-scoped filter is only
// constructed in the context of the connection, and the static one
// holds an empty placeholder. The filters of a default-scoped gateway,
// resolved here for request-scoped global enhancers, are static, and a
// transient one is constructed for the gateway in the static context.
const exceptionFilter = this.exceptionFiltersContext.create(instance, targetCallback, moduleKey, isStatic ? STATIC_CONTEXT : contextId, instanceWrapper.id);
// A filter is not the hook: the disconnect hook does not wait for it
markConnectionHookAsCalled?.();
await this.handleLifecycleHookError(exceptionFilter, methodName, args, err);
}
finally {
// The hook threw, or is not going to be called at all
markConnectionHookAsCalled?.();
if (methodName === 'handleDisconnect' && contextId) {
this.cleanupRequestScopedContext(instanceWrapper, contextId, client);
}
}
};
}
getConnectionHookCalls(instanceWrapper) {
let connectionHookCalls = this.connectionHookCalls.get(instanceWrapper);
if (!connectionHookCalls) {
connectionHookCalls = new WeakMap();
this.connectionHookCalls.set(instanceWrapper, connectionHookCalls);
}
return connectionHookCalls;
}
logResolutionError(instance, methodName, err) {
this.logger.error(`Failed to resolve ${instance.constructor.name} on client ${methodName === 'handleConnection' ? 'connection' : 'disconnection'}`, err?.stack);
}
// A default-scoped gateway is resolved per connection only for its global
// scoped enhancers, so their trees decide whether the context is durable
// (mirrors InstanceWrapper#isDependencyTreeDurable).
areGlobalScopedEnhancersDurable() {
const scopedEnhancers = this.getGlobalScopedEnhancers().filter(wrapper => !wrapper.isDependencyTreeStatic());
return (scopedEnhancers.length > 0 &&
scopedEnhancers.every(wrapper => wrapper.isDependencyTreeDurable()));
}
/**
* Runs a lifecycle hook of a default-scoped gateway and passes the errors it
* throws or rejects with to the gateway's exception filters, as for message
* handlers. The hook still runs synchronously.
*/
createStaticEventHandler(instance, moduleKey, methodName, instanceWrapperId) {
const hook = instance[methodName];
if (!hook) {
return undefined;
}
// Kept per gateway, not per hook function: gateways that inherit the
// hook from a base class can declare different filters
let exceptionFilter;
return (...args) => {
const handleError = (err) => {
// With the gateway as the inquirer, as for its message handlers, so
// that a transient filter is the one constructed for the gateway
exceptionFilter ??= this.exceptionFiltersContext.create(instance, hook, moduleKey, STATIC_CONTEXT, instanceWrapperId);
return this.handleLifecycleHookError(exceptionFilter, methodName, args, err);
};
try {
const result = hook.apply(instance, args);
return isFunction(result?.then)
? result.catch(handleError)
: result;
}
catch (err) {
return handleError(err);
}
};
}
handleLifecycleHookError(exceptionFilter, methodName, args, err) {
const [client, disconnectReason] = args;
// Client first, data second and the pattern last, as for message handlers.
// With the raw hook arguments, the filter would send the last one (the
// socket itself with socket.io, the upgrade request with ws) back to the
// client as the pattern. The disconnect reason is safe to pass as data,
// as nothing is sent to a client that has already disconnected.
const data = methodName === 'handleDisconnect' ? disconnectReason : undefined;
const host = new ExecutionContextHost([client, data, methodName]);
host.setType('ws');
// Nothing awaits a lifecycle hook, so an error leaving the filter, e.g.
// when its reply cannot be serialized, would end the process as an
// uncaught exception or an unhandled rejection. It is logged instead, as
// the adapters do for message handlers.
try {
const pending = exceptionFilter.handle(err, host);
if (isFunction(pending?.then)) {
return Promise.resolve(pending).catch(filterError => this.logger.error(filterError));
}
}
catch (filterError) {
this.logger.error(filterError);
}
}
getGlobalScopedEnhancers() {
return [
...this.config.getGlobalRequestGuards(),
...this.config.getGlobalRequestPipes(),
...this.config.getGlobalRequestInterceptors(),
];
}
getContextId(request, isTreeDurable) {
const contextId = ContextIdFactory.getByRequest(request);
if (!request[REQUEST_CONTEXT_ID]) {
Object.defineProperty(request, REQUEST_CONTEXT_ID, {
value: contextId,
enumerable: false,
writable: false,
configurable: true,
});
const requestProviderValue = isTreeDurable
? contextId.payload
: Object.assign(request, contextId.payload);
this.container.registerRequestProvider(requestProviderValue, contextId);
}
return contextId;
}
cleanupRequestScopedContext(_instanceWrapper, contextId, request) {
const remaining = (this.pendingDisconnects.get(contextId) ?? 1) - 1;
if (remaining > 0) {
this.pendingDisconnects.set(contextId, remaining);
return;
}
this.pendingDisconnects.delete(contextId);
// Other gateways can still be executing their asynchronous disconnect hooks.
// A finished cycle must also never remove a newer context on the same client.
if (request[REQUEST_CONTEXT_ID] === contextId) {
Reflect.deleteProperty(request, REQUEST_CONTEXT_ID);
}
}
assignServerToProperties(instance, server) {
for (const propertyKey of this.metadataExplorer.scanForServerHooks(instance)) {
Reflect.set(instance, propertyKey, server);
}
}
printSubscriptionLogs(instance, subscribersMap) {
const gatewayClassName = instance?.constructor?.name;
if (!gatewayClassName) {
return;
}
subscribersMap.forEach(({ message }) => this.logger.log(`${gatewayClassName} subscribed to the "${message}" message`));
}
}