UNPKG

@nestjs/core

Version:

The core of NestJS, a TypeScript framework for Node.js backends: modules, dependency injection and the request pipeline, on Express, Fastify or node:http.

499 lines (498 loc) • 24.4 kB
import { ForbiddenException, SSE_ABORT_CONTROLLER, StreamableFile, } from '@nestjs/common'; import { CUSTOM_ROUTE_ARGS_METADATA, HEADERS_METADATA, HTTP_CODE_METADATA, isEmptyArray, isPlainObject, isString, REDIRECT_METADATA, RENDER_METADATA, ROUTE_ARGS_METADATA, RouteParamtypes, SSE_METADATA, } from '@nestjs/common/internal'; import * as commonInternal from '@nestjs/common/internal'; import { EmptyError, isObservable, Observable } from 'rxjs'; import { takeUntil, tap } from 'rxjs/operators'; import { finished, Stream } from 'stream'; import { FORBIDDEN_MESSAGE, } from '../guards/index.js'; import { ContextUtils } from '../helpers/context-utils.js'; import { destroyUnsentBody } from '../helpers/destroy-unsent-body.js'; import { HandlerMetadataStorage, } from '../helpers/handler-metadata-storage.js'; import { STATIC_CONTEXT } from '../injector/constants.js'; import { markRejectedByPipes } from './rejected-by-pipes.js'; import { onceClosed, pickCloseSource, RouterResponseController, } from './router-response-controller.js'; import { isStreamingBody, isStreamingBodyConsumed, listenForStreamError, } from './streaming-body.js'; /** Signals the request's response handler each time the route returns an Observable. */ class RouteHandlerObservableNotifier { emitted = false; listener; next() { this.emitted = true; this.listener?.(); } subscribe(listener) { this.listener = listener; if (this.emitted) { listener(); } return this; } unsubscribe() { this.listener = undefined; } } const isThenable = (value) => value !== null && (typeof value === 'object' || typeof value === 'function') && typeof value.then === 'function'; export class RouterExecutionContext { paramsFactory; pipesContextCreator; pipesConsumer; guardsContextCreator; guardsConsumer; interceptorsContextCreator; interceptorsConsumer; applicationRef; handlerMetadataStorage = new HandlerMetadataStorage(); contextUtils = new ContextUtils(); responseController; constructor(paramsFactory, pipesContextCreator, pipesConsumer, guardsContextCreator, guardsConsumer, interceptorsContextCreator, interceptorsConsumer, applicationRef) { this.paramsFactory = paramsFactory; this.pipesContextCreator = pipesContextCreator; this.pipesConsumer = pipesConsumer; this.guardsContextCreator = guardsContextCreator; this.guardsConsumer = guardsConsumer; this.interceptorsContextCreator = interceptorsContextCreator; this.interceptorsConsumer = interceptorsConsumer; this.applicationRef = applicationRef; this.responseController = new RouterResponseController(applicationRef); } create(instance, callback, methodName, moduleKey, requestMethod, contextId = STATIC_CONTEXT, inquirerId) { const contextType = 'http'; const { argsLength, fnHandleResponse, isSseHandler, paramtypes, getParamsMetadata, httpStatusCode, responseHeaders, hasCustomHeaders, } = this.getMetadata(instance, callback, methodName, moduleKey, requestMethod, contextType); const paramsOptions = this.contextUtils.mergeParamsMetatypes(getParamsMetadata(moduleKey, contextId, inquirerId), paramtypes); const pipes = this.pipesContextCreator.create(instance, callback, moduleKey, contextId, inquirerId); this.contextUtils.warnOnMissingParamtypes(instance, methodName, paramtypes, pipes, paramsOptions.filter(({ type }) => this.isPipeable(type))); const guards = this.guardsContextCreator.create(instance, callback, moduleKey, contextId, inquirerId); const interceptors = this.interceptorsContextCreator.create(instance, callback, moduleKey, contextId, inquirerId); const fnCanActivate = this.createGuardsFn(guards, instance, callback, contextType); const fnApplyPipes = this.createPipesFn(pipes, paramsOptions); const handler = (args, req, res, next, handlerObservable$, handlerStreams = []) => async () => { try { const pendingPipes = fnApplyPipes && fnApplyPipes(args, req, res, next); pendingPipes && (await pendingPipes); } catch (err) { // e.g. for upload interceptors to remove the files they stored markRejectedByPipes(req); throw err; } const result = callback.apply(instance, args); if (!handlerObservable$) { return result; } // Settled here, so that an Observable a promise resolves to is tapped // like one the handler returns as it is. The `then()` of a thenable // (e.g. a lazy query builder) is still called once, as its value is // returned in its place. const value = isThenable(result) ? await result : result; this.observeHandlerResult(value, handlerObservable$, handlerStreams); return isObservable(value) ? value.pipe(tap(emitted => this.trackHandlerStream(emitted, handlerStreams))) : value; }; return async (req, res, next) => { const args = this.contextUtils.createNullArray(argsLength); fnCanActivate && (await fnCanActivate([req, res, next])); this.responseController.setStatus(res, httpStatusCode); hasCustomHeaders && this.responseController.setHeaders(res, responseHeaders); if (isSseHandler) { // Attach a per-request AbortController before the handler runs so async // @Sse() handlers can observe client disconnects via @SseSignal() during // their setup. The controller is aborted in RouterResponseController.sse() // when the underlying connection closes. this.attachSseAbortSignal(req); } // Interceptors always hand back an Observable, so whether the route // handler itself returned one can only be observed where it runs. const handlerObservable$ = isSseHandler || isEmptyArray(interceptors) ? undefined : new RouteHandlerObservableNotifier(); // The streams the handler produced: an interceptor may still hold one // when the client goes away, wrap one in a value it cannot be sent as, // or replace one with something else. const handlerStreams = []; const resultOrDeferred = this.interceptorsConsumer.intercept(interceptors, [req, res, next], instance, callback, handler(args, req, res, next, handlerObservable$, handlerStreams), contextType); const result = isSseHandler ? resultOrDeferred : await resultOrDeferred; await fnHandleResponse(result, res, req, handlerObservable$, handlerStreams); }; } getMetadata(instance, callback, methodName, moduleKey, requestMethod, contextType) { const cacheMetadata = this.handlerMetadataStorage.get(instance, methodName); if (cacheMetadata) { return cacheMetadata; } const metadata = this.contextUtils.reflectCallbackMetadata(instance, methodName, ROUTE_ARGS_METADATA) || {}; const keys = Object.keys(metadata); const argsLength = this.contextUtils.getArgumentsLength(keys, metadata); const paramtypes = this.contextUtils.reflectCallbackParamtypes(instance, methodName); const contextFactory = this.contextUtils.getContextFactory(contextType, instance, callback); const getParamsMetadata = (moduleKey, contextId = STATIC_CONTEXT, inquirerId) => this.exchangeKeysForValues(keys, metadata, moduleKey, contextId, inquirerId, contextFactory); const paramsMetadata = getParamsMetadata(moduleKey); const isResponseHandled = this.isResponseHandled(instance, methodName, paramsMetadata); const httpRedirectResponse = this.reflectRedirect(callback); const fnHandleResponse = this.createHandleResponseFn(callback, isResponseHandled, httpRedirectResponse); const isSseHandler = !!this.reflectSse(callback); const httpCode = this.reflectHttpStatusCode(callback); const httpStatusCode = httpCode ?? this.responseController.getStatusByMethod(requestMethod); const responseHeaders = this.reflectResponseHeaders(callback); const hasCustomHeaders = !isEmptyArray(responseHeaders); const handlerMetadata = { argsLength, fnHandleResponse, isSseHandler, paramtypes, getParamsMetadata, httpStatusCode, hasCustomHeaders, responseHeaders, }; this.handlerMetadataStorage.set(instance, methodName, handlerMetadata); return handlerMetadata; } reflectRedirect(callback) { return Reflect.getMetadata(REDIRECT_METADATA, callback); } reflectHttpStatusCode(callback) { return Reflect.getMetadata(HTTP_CODE_METADATA, callback); } reflectRenderTemplate(callback) { return Reflect.getMetadata(RENDER_METADATA, callback); } reflectResponseHeaders(callback) { return Reflect.getMetadata(HEADERS_METADATA, callback) || []; } reflectSse(callback) { return Reflect.getMetadata(SSE_METADATA, callback); } reflectSseOptions(callback) { // Check the namespace, since a named import fails with an older common. return 'SSE_OPTIONS_METADATA' in commonInternal ? Reflect.getMetadata(commonInternal.SSE_OPTIONS_METADATA, callback) : undefined; } exchangeKeysForValues(keys, metadata, moduleContext, contextId = STATIC_CONTEXT, inquirerId, contextFactory) { this.pipesContextCreator.setModuleContext(moduleContext); return keys.map(key => { const { index, data, pipes: pipesCollection, schema } = metadata[key]; const pipes = this.pipesContextCreator.createConcreteContext(pipesCollection, contextId, inquirerId); const type = this.contextUtils.mapParamType(key); if (key.includes(CUSTOM_ROUTE_ARGS_METADATA)) { const { factory } = metadata[key]; const customExtractValue = this.contextUtils.getCustomFactory(factory, data, contextFactory); return { index, extractValue: customExtractValue, type, data, pipes, schema, }; } const numericType = Number(type); const extractValue = (req, res, next) => this.paramsFactory.exchangeKeyForValue(numericType, data, { req: req, res, next, }); return { index, extractValue, type: numericType, data, pipes, schema }; }); } async getParamValue(value, metadata, pipes) { if (!isEmptyArray(pipes)) { return this.pipesConsumer.apply(value, metadata, pipes); } return value; } isPipeable(type) { return (type === RouteParamtypes.BODY || type === RouteParamtypes.RAW_BODY || type === RouteParamtypes.QUERY || type === RouteParamtypes.PARAM || type === RouteParamtypes.FILE || type === RouteParamtypes.FILES || type === RouteParamtypes.COOKIES || type === RouteParamtypes.SIGNED_COOKIES || isString(type)); } createGuardsFn(guards, instance, callback, contextType) { const canActivateFn = async (args) => { const canActivate = await this.guardsConsumer.tryActivate(guards, args, instance, callback, contextType); if (!canActivate) { throw new ForbiddenException(FORBIDDEN_MESSAGE); } }; return guards.length ? canActivateFn : null; } createPipesFn(pipes, paramsOptions) { if (!paramsOptions.length) { return null; } // Which pipes a param runs through is fixed for the route, so it is // worked out once here rather than on every request. const params = paramsOptions.map(({ index, extractValue, type, data, metatype, pipes: paramPipes, schema, }) => { const isPipeable = this.isPipeable(type); return { index, extractValue, isPipeable, metadata: { metatype, type, data, schema }, pipes: isPipeable ? pipes.concat(paramPipes) : [], }; }); const applyPipes = async (args, param, value) => { args[param.index] = await this.getParamValue(value, param.metadata, param.pipes); }; return (args, req, res, next) => { // A value no pipe runs on is final once extracted and needs no promise, // unless it is a thenable on a pipeable param, which getParamValue() has // always settled. The response, which a custom decorator can give the // handler as @Res() does, is passed on unchanged, with no pipe run on // it, whatever the adapter: the then() of a Fastify reply waits for the // response to be sent, so settling it, or any pipe that returns it, // would wait for an answer the handler has yet to give. The rest, and // any extractor that throws, go through one Promise.all() in param // order, as before: pipes start in the same order and the first error // is the same one. let pending; for (let i = 0; i < params.length; i++) { const param = params[i]; try { const value = param.extractValue(req, res, next); if (param.isPipeable && (param.pipes.length > 0 || isThenable(value)) && value !== res) { (pending ??= []).push(applyPipes(args, param, value)); } else { args[param.index] = value; } } catch (err) { (pending ??= []).push(Promise.reject(err)); } } return pending && Promise.all(pending); }; } createHandleResponseFn(callback, isResponseHandled, redirectResponse, httpStatusCode) { const renderTemplate = this.reflectRenderTemplate(callback); if (renderTemplate) { return async (result, res) => { return await this.responseController.render(result, res, renderTemplate); }; } if (redirectResponse && isString(redirectResponse.url)) { return async (result, res) => { await this.responseController.redirect(result, res, redirectResponse); }; } const isSseHandler = !!this.reflectSse(callback); if (isSseHandler) { const maxPendingDataLength = this.reflectSseOptions(callback)?.maxPendingDataLength; return async (result, res, req) => { const rawResponse = res.raw ?? res; await this.responseController.sse(result, rawResponse, req.raw || req, { additionalHeaders: () => res.getHeaders?.(), statusCode: () => res.statusCode ?? rawResponse.statusCode, maxPendingDataLength, }); }; } return async (result, res, req, handlerObservable$, handlerStreams = []) => { let disconnected = false; try { if (isObservable(result)) { // Only an Observable returned by the route handler itself is torn // down when the client goes away. Without interceptors, `result` is // that Observable; otherwise `handlerObservable$` reports it. const disconnect$ = this.fromClientDisconnect(req, res, () => { disconnected = true; }, handlerObservable$); result = result.pipe( // What it emits waits for it to complete. Without interceptors, it // is the handler's own Observable, whose streams are tracked here. tap(value => handlerObservable$ ? listenForStreamError(value) : this.trackHandlerStream(value, handlerStreams)), takeUntil(disconnect$)); } result = await this.responseController.transformToResult(result); } catch (err) { // `takeUntil` completes the stream on disconnect, so `lastValueFrom` // rejects with an `EmptyError` if nothing was emitted yet. Any other // error still goes to the exception filters. if (!disconnected || !(err instanceof EmptyError)) { // An interceptor failed with a stream of the handler still in hand handlerStreams.forEach(destroyUnsentBody); throw err; } } if (disconnected) { // Nothing is sent to a client that is gone. The stream of a // StreamableFile would otherwise hold what it reads from (e.g. an // open file) for good, also one the handler emitted that an // interceptor held when the chain was torn down. [result, ...handlerStreams].forEach(destroyUnsentBody); return res; } if (!isResponseHandled) { const streamingBody = this.pickStreamingBody(result, handlerStreams); // A stream of the handler that an interceptor replaced (e.g. with an // empty 304, or a stream of its own) is not sent either. What is sent // in its place may still read from it, so it is released once the // response is over. this.releaseOnceResponseIsOver(handlerStreams.filter(stream => stream !== result && stream !== streamingBody), req, res); try { await (streamingBody ? this.responseController.stream(streamingBody, res, req, { statusCode: httpStatusCode, }) : this.responseController.apply(result, res, httpStatusCode)); } catch (err) { // Not sent either, e.g. for a header value Node.js rejects [result, streamingBody, ...handlerStreams].forEach(destroyUnsentBody); throw err; } } return res; }; } /** * The stream to send, if any: the one the interceptors handed back, or the * one in the plain object they wrapped it in (`{ data: stream }`), which * cannot go out that way, unless they read it to build their own result. It * is never the handler's own in place of what they returned: they may have * replaced it with a stream that leaves something out, or with something * that is not a stream (a notice, nothing at all), which is sent as it is. */ pickStreamingBody(result, handlerStreams) { if (isStreamingBody(result)) { return result; } // Only for a handler that streams: other routes serialize such an object if (!isPlainObject(result) || !handlerStreams.some(isStreamingBody)) { return undefined; } const wrappedBody = Object.values(result).find(isStreamingBody); return wrappedBody && !isStreamingBodyConsumed(wrappedBody) ? wrappedBody : undefined; } /** * Releases streams that are not sent once the response is over: sent, or * its connection closed. The connection is watched as well, since a * pipelined response that still waits for its turn never learns that it is * gone. */ releaseOnceResponseIsOver(streams, req, res) { if (isEmptyArray(streams)) { return; } const response = res?.raw ?? res; const connection = pickCloseSource((req?.raw ?? req)?.socket, response); let isReleased = false; let stopWaitingForClose; const release = () => { if (isReleased) { return; } isReleased = true; stopWaitingForClose?.(); streams.forEach(destroyUnsentBody); }; if (connection?.destroyed) { return release(); } stopWaitingForClose = connection && onceClosed(connection, release); // `finished()` throws for anything but a stream if (response instanceof Stream) { finished(response, release); } } trackHandlerStream(value, handlerStreams) { if (value instanceof StreamableFile) { handlerStreams.push(value); } else if (isStreamingBody(value)) { handlerStreams.push(value); // An 'error' emitted while an interceptor awaits, before anything // listens, would bring the process down. listenForStreamError(value); } } observeHandlerResult(result, handlerObservable$, handlerStreams) { if (isObservable(result)) { handlerObservable$.next(); } else { this.trackHandlerStream(result, handlerStreams); } } /** * Emits once the client connection closes, or right away if it already has. * With interceptors, watching starts only once the route handler itself * produces an Observable, and starts over each time it does (e.g. on a * retry). Picks the close source the same way `RouterResponseController#sse()` * does, so the two disconnect watchers cannot drift apart. */ fromClientDisconnect(req, res, onDisconnect, handlerObservable$) { const watch = (subscriber) => { const source = pickCloseSource((req?.raw ?? req)?.socket, res?.raw ?? res); if (!source) { return; } const disconnect = () => { onDisconnect(); subscriber.next(); }; if (source.destroyed) { disconnect(); return; } return onceClosed(source, disconnect); }; if (!handlerObservable$) { return new Observable(watch); } return new Observable(subscriber => { let stopWatching; return handlerObservable$.subscribe(() => { if (subscriber.closed) { return; } try { if (stopWatching) { subscriber.remove(stopWatching); stopWatching(); } stopWatching = watch(subscriber); subscriber.add(stopWatching); } catch (err) { subscriber.error(err); } }); }); } isResponseHandled(instance, methodName, paramsMetadata) { const hasResponseOrNextDecorator = paramsMetadata.some(({ type }) => type === RouteParamtypes.RESPONSE || type === RouteParamtypes.NEXT); const isPassthroughEnabled = this.contextUtils.reflectPassthrough(instance, methodName); return hasResponseOrNextDecorator && !isPassthroughEnabled; } attachSseAbortSignal(req) { const carrier = req; // Attach to both the framework request and its raw form (when present), since // @SseSignal() reads from the execution-context request while // RouterResponseController.sse() operates on the raw request. if (!carrier[SSE_ABORT_CONTROLLER]) { carrier[SSE_ABORT_CONTROLLER] = new AbortController(); } if (carrier.raw && !carrier.raw[SSE_ABORT_CONTROLLER]) { carrier.raw[SSE_ABORT_CONTROLLER] = carrier[SSE_ABORT_CONTROLLER]; } } }