From 106adcc217ddab1fba15be5eaf0e9f4a575d09ae Mon Sep 17 00:00:00 2001 From: SkyZeroZx <73321943+SkyZeroZx@users.noreply.github.com> Date: Wed, 18 Nov 2026 21:34:15 -0500 Subject: [PATCH] fix(@angular/ssr): destroy the platform of an aborted request once it is stable Aborting a request destroyed the platform while an app initializer or an `HttpClient` request was still pending, which could end the server process. The platform is now destroyed once the application is stable, or after 10 seconds. Fixes #34754 --- packages/angular/ssr/src/utils/ng.ts | 40 ++++++++-- packages/angular/ssr/test/app_spec.ts | 108 ++++++++++++++++++++++++++ 2 files changed, 143 insertions(+), 5 deletions(-) diff --git a/packages/angular/ssr/src/utils/ng.ts b/packages/angular/ssr/src/utils/ng.ts index fe1879a17930..b8ebb945bfd0 100644 --- a/packages/angular/ssr/src/utils/ng.ts +++ b/packages/angular/ssr/src/utils/ng.ts @@ -27,6 +27,12 @@ import { Console } from '../console'; import { addTrailingSlash, joinUrlParts, stripIndexHtmlFromURL, stripTrailingSlash } from './url'; import { getFirstHeaderValue } from './validation'; +/** + * The maximum time, in milliseconds, that an aborted render can take to become stable before its platform is destroyed. + * This matches the time in which Angular expects an application to become stable (see NG0506). + */ +const ABORTED_RENDER_TIMEOUT = 10_000; + /** * Represents the bootstrap mechanism for an Angular application. * @@ -104,6 +110,8 @@ export async function renderAngular( let renderTimeoutId: ReturnType | undefined; let destroyPromise: Promise | undefined; let rejectContent: ((reason?: unknown) => void) | undefined; + let abortTimeoutSignal: AbortSignal | undefined; + let isStable = false; const destroy = (): Promise => { rejectContent?.( @@ -117,34 +125,56 @@ export async function renderAngular( if (!destroyPromise) { clearTimeout(renderTimeoutId); signal?.removeEventListener('abort', abortHandler); + abortTimeoutSignal?.removeEventListener('abort', abortTimeoutHandler); destroyPromise = asyncDestroyPlatform(platformRef); } return destroyPromise; }; - const abortHandler = () => void destroy(); + const abortTimeoutHandler = () => void destroy(); - try { - signal?.addEventListener('abort', abortHandler, { once: true }); + // Destroying the platform while the application has pending work, such as an app initializer or an + // `HttpClient` request, makes that work fail outside of the request where it cannot be caught. + // When the request is aborted before the application is stable, the platform is destroyed once it + // becomes stable, or when `ABORTED_RENDER_TIMEOUT` elapses if it never does. + const abortHandler = () => { + if (isStable) { + void destroy(); + + return; + } + abortTimeoutSignal = AbortSignal.timeout(ABORTED_RENDER_TIMEOUT); + abortTimeoutSignal.addEventListener('abort', abortTimeoutHandler, { once: true }); + }; + + try { let applicationRef: ApplicationRef; if (isNgModule(bootstrap)) { const moduleRef = await platformRef.bootstrapModule(bootstrap); - if (platformRef.destroyed || signal?.aborted) { + if (platformRef.destroyed) { return { hasNavigationError: true }; } applicationRef = moduleRef.injector.get(ApplicationRef); } else { applicationRef = await bootstrap({ platformRef }); - if (platformRef.destroyed || signal?.aborted) { + if (platformRef.destroyed) { return { hasNavigationError: true }; } } + // Aborts are handled after bootstrapping, as app initializers cannot be stopped and use the platform once they settle. + if (signal?.aborted) { + abortHandler(); + } else { + signal?.addEventListener('abort', abortHandler, { once: true }); + } + // Block until application is stable. await applicationRef.whenStable(); + isStable = true; // This code protect against app destruction during bootstrapping which is a // valid case. We should not assume the `applicationRef` is not in destroyed state. diff --git a/packages/angular/ssr/test/app_spec.ts b/packages/angular/ssr/test/app_spec.ts index b50557f1b031..c38edc917047 100644 --- a/packages/angular/ssr/test/app_spec.ts +++ b/packages/angular/ssr/test/app_spec.ts @@ -15,11 +15,13 @@ import { APP_BASE_HREF } from '@angular/common'; import { Component, DestroyRef, + EnvironmentInjector, PendingTasks, PlatformRef, REQUEST, RESPONSE_INIT, inject, + provideAppInitializer, } from '@angular/core'; import { ActivatedRoute, CanActivateFn, Router } from '@angular/router'; import { setTimeout } from 'node:timers/promises'; @@ -30,6 +32,7 @@ import { setAngularAppTestingManifest } from './testing-utils'; describe('AngularServerApp', () => { let app: AngularServerApp; let slowRouteHook: (() => void) | undefined; + let appInitializerHook: (() => Promise) | undefined; @Component({ selector: 'app-home', @@ -198,6 +201,7 @@ describe('AngularServerApp', () => { provide: APP_BASE_HREF, useFactory: () => inject(REQUEST)?.headers.get('X-Forwarded-Prefix'), }, + provideAppInitializer(() => appInitializerHook?.()), ], ); @@ -340,6 +344,8 @@ describe('AngularServerApp', () => { }); let appDestroyed = false; let destroySpy: jasmine.Spy | undefined; + const abortTimeout = new AbortController(); + spyOn(AbortSignal, 'timeout').and.returnValue(abortTimeout.signal); slowRouteHook = () => { destroySpy = spyOn(inject(PlatformRef), 'destroy').and.callThrough(); @@ -369,6 +375,11 @@ describe('AngularServerApp', () => { DOMException, /Request for: http:\/\/localhost\/page-slow was aborted/, ); + await setTimeout(0); + expect(destroySpy).not.toHaveBeenCalled(); + + // Simulate the abort timeout elapsing as the pending task never resolves + abortTimeout.abort(); // Wait for the macrotask queue to clear since platform destruction is scheduled via setTimeout(0) await setTimeout(0); @@ -379,6 +390,103 @@ describe('AngularServerApp', () => { } }); + it('should destroy the platform once pending work settles when an in-flight request is aborted', async () => { + const { promise: taskReady, resolve: resolveTaskReady } = Promise.withResolvers(); + const { promise: workDone, resolve: resolveWork } = Promise.withResolvers(); + const { promise: platformDestroyed, resolve: resolvePlatformDestroyed } = + Promise.withResolvers(); + let pendingWork: Promise | undefined; + let destroySpy: jasmine.Spy | undefined; + + slowRouteHook = () => { + const platformRef = inject(PlatformRef); + destroySpy = spyOn(platformRef, 'destroy').and.callThrough(); + platformRef.onDestroy(resolvePlatformDestroyed); + + // Like an `HttpClient` request, this work holds a pending task and uses the application once it settles + const injector = inject(EnvironmentInjector); + const removeTask = inject(PendingTasks).add(); + pendingWork = workDone.then(() => injector.get(Router)).finally(removeTask); + resolveTaskReady(); + }; + + try { + const controller = new AbortController(); + const request = new Request('http://localhost/page-slow', { signal: controller.signal }); + + const handlePromise = app.handle(request); + + // Abort the request while the work is still pending + await taskReady; + controller.abort(); + + await expectAsync(handlePromise).toBeRejectedWithError( + DOMException, + /Request for: http:\/\/localhost\/page-slow was aborted/, + ); + await setTimeout(0); + expect(destroySpy).not.toHaveBeenCalled(); + + resolveWork(); + await expectAsync(pendingWork).toBeResolved(); + + await platformDestroyed; + expect(destroySpy).toHaveBeenCalledTimes(1); + } finally { + slowRouteHook = undefined; + } + }); + + it('should wait for a pending app initializer before destroying the platform when the request is aborted', async () => { + // Warm up the router so route extraction does not run the app initializer during this test + const warmupResponse = await app.handle(new Request('http://localhost/home')); + await warmupResponse?.text(); + await setTimeout(0); + + const { promise: initializerStarted, resolve: resolveInitializerStarted } = + Promise.withResolvers(); + const { promise: initializerDone, resolve: resolveInitializer } = + Promise.withResolvers(); + const { promise: platformDestroyed, resolve: resolvePlatformDestroyed } = + Promise.withResolvers(); + let destroySpy: jasmine.Spy | undefined; + + appInitializerHook = () => { + const platformRef = inject(PlatformRef); + destroySpy = spyOn(platformRef, 'destroy').and.callThrough(); + platformRef.onDestroy(resolvePlatformDestroyed); + resolveInitializerStarted(); + + return initializerDone; + }; + + try { + const controller = new AbortController(); + const request = new Request('http://localhost/home', { signal: controller.signal }); + + const handlePromise = app.handle(request); + + // Abort the request while the app initializer is still pending + await initializerStarted; + controller.abort(); + + await expectAsync(handlePromise).toBeRejectedWithError( + DOMException, + /Request for: http:\/\/localhost\/home was aborted/, + ); + await setTimeout(0); + expect(destroySpy).not.toHaveBeenCalled(); + + // Bootstrapping reads from the application injector once the initializer settles + resolveInitializer(); + + await platformDestroyed; + expect(destroySpy).toHaveBeenCalledTimes(1); + } finally { + appInitializerHook = undefined; + } + }); + it('should not bootstrap the platform if the request signal is already aborted', async () => { // Warm up the router so route extraction does not create a PlatformRef during this test const warmupResponse = await app.handle(new Request('http://localhost/home'));