UNPKG

@nestjs/websockets

Version:

WebSockets for NestJS: gateways with message handlers, guards, pipes and interceptors, on Socket.IO or ws.

136 lines (135 loc) • 6.91 kB
import { AbstractWsAdapter } from './adapters/ws-adapter.js'; import { ServerAndEventStreamsFactory } from './factories/server-and-event-streams-factory.js'; import { Logger } from '@nestjs/common'; import { addLeadingSlash, isFunction, isNil, isString, } from '@nestjs/common/internal'; import { isDeepStrictEqual } from 'util'; // The options that decide whether a client may connect at all. They are // options of the server, which gateways on the same port and path share. const CONNECTION_CHECKS = ['verifyClient', 'allowRequest']; // The options of a gateway that are not options of its server const GATEWAY_KEYS = ['namespace', 'path', 'server']; export class SocketServerProvider { socketsContainer; applicationConfig; hasHttpServer; logger = new Logger(SocketServerProvider.name); // The options of the gateway each server was created for serverOptions = new WeakMap(); constructor(socketsContainer, applicationConfig, hasHttpServer = true) { this.socketsContainer = socketsContainer; this.applicationConfig = applicationConfig; this.hasHttpServer = hasHttpServer; } scanForSocketServer(options, port, gatewayName) { const serverAndStreamsHost = this.socketsContainer.getOneByConfig({ port, path: options.path, }); if (serverAndStreamsHost) { this.ensureOptionsApply(options, port, serverAndStreamsHost, gatewayName); } if (serverAndStreamsHost && options.namespace) { return this.decorateWithNamespace(options, port, serverAndStreamsHost.server); } return serverAndStreamsHost ? serverAndStreamsHost : this.createSocketServer(options, port, gatewayName); } createSocketServer(options, port, gatewayName) { const adapter = this.applicationConfig.getIoAdapter(); const { namespace, server, ...partialOptions } = options; let ioServer; if (this.isServedWithoutListener(port, adapter)) { // An adapter would otherwise listen on a port of the kernel's choosing, // on every interface this.logger.log(`${gatewayName ?? 'A gateway'} has no port, and there is no HTTP server to serve it on, so its server does not listen for clients. Give it a port of its own to serve clients from this process.`); ioServer = adapter.createWithoutListener(partialOptions); } else { ioServer = adapter.create(port, partialOptions); } const serverAndEventStreamsHost = ServerAndEventStreamsFactory.create(ioServer); this.socketsContainer.addOne({ port, path: options.path }, serverAndEventStreamsHost); this.serverOptions.set(serverAndEventStreamsHost, options); if (!namespace) { return serverAndEventStreamsHost; } return this.decorateWithNamespace(options, port, ioServer); } isServedWithoutListener(port, adapter) { return (port === 0 && !this.hasHttpServer && adapter instanceof AbstractWsAdapter && !adapter['httpServer'] && isFunction(adapter.createWithoutListener)); } /** * A gateway that joins a server created for another gateway is served with * the options of that gateway. A connection check of its own would never * run, and every client would reach its handlers, so the application does * not start. Other options it would lose are reported. */ ensureOptionsApply(options, port, host, gatewayName) { const serverOptions = this.serverOptions.get(host); if (!serverOptions) { return; } const gateway = gatewayName ? `The gateway ${gatewayName}` : 'A gateway'; const server = `the server on port ${port}${options.path ? ` and the path "${options.path}"` : ''}`; for (const key of CONNECTION_CHECKS) { if (!isNil(options[key]) && options[key] !== serverOptions[key]) { const error = new Error(`${gateway} sets "${key}", but shares ${server} with a gateway declared before it, and the server runs ${isNil(serverOptions[key]) ? 'no' : 'the'} "${key}" of that gateway. Set the same "${key}" on the gateway declared first, or give the gateway a port or path of its own.`); this.logger.error(error); throw error; } } const droppedOptions = Object.keys(options).filter(key => !GATEWAY_KEYS.includes(key) && !CONNECTION_CHECKS.includes(key) && !isDeepStrictEqual(options[key], serverOptions[key])); if (droppedOptions.length > 0) { this.logger.warn(`${gateway} shares ${server} with a gateway declared before it, and the server was created with the options of that gateway, so these options of its own are not applied: ${droppedOptions.map(key => `"${key}"`).join(', ')}.`); } } decorateWithNamespace(options, port, targetServer) { // Gateways on the same namespace share one host, and with it the streams // of connections and disconnections, as gateways sharing a server do. // socket.io also serves a RegExp namespace from the first parent namespace // created for it, so a second one would never get a connection. const namespaceConfig = { port, path: options.path, namespace: this.validateNamespace(options.namespace || ''), }; const namespaceHost = this.socketsContainer.getOneByConfig(namespaceConfig); if (namespaceHost) { return namespaceHost; } const namespaceServer = this.getServerOfNamespace(options, port, targetServer); const serverAndEventStreamsHost = ServerAndEventStreamsFactory.create(namespaceServer); // "/" is the namespace of the gateways without one, so a gateway on it // shares their streams too, while it keeps the namespace as its server const rootHost = namespaceConfig.namespace === '/' ? this.socketsContainer.getOneByConfig({ port, path: options.path }) : undefined; if (rootHost) { serverAndEventStreamsHost.connection = rootHost.connection; serverAndEventStreamsHost.disconnect = rootHost.disconnect; } this.socketsContainer.addOne(namespaceConfig, serverAndEventStreamsHost); return serverAndEventStreamsHost; } getServerOfNamespace(options, port, server) { const adapter = this.applicationConfig.getIoAdapter(); return adapter.create(port, { ...options, namespace: this.validateNamespace(options.namespace || ''), server, }); } validateNamespace(namespace) { if (!isString(namespace)) { return namespace; } return addLeadingSlash(namespace); } }