From 66d97cfc6f4a03b45062e670e8e496e155a7e088 Mon Sep 17 00:00:00 2001 From: Alan Agius <17563226+alan-agius4@users.noreply.github.com> Date: Fri, 20 Nov 2026 07:41:24 +0000 Subject: [PATCH] fix(@angular/ssr): guard aborted requests across rendering and serialization Short-circuit `AngularServerApp.handleRendering()` on `request.signal.aborted` before asset reads, `html:transform:pre` hooks, `renderAngular()`, and critical CSS inlining so aborted requests avoid unnecessary work. In `renderAngular()`, check `moduleRef.injector.destroyed`, `applicationRef.destroyed`, `platformRef.destroyed`, and `destroyPromise` consistently across bootstrap, `whenStable()`, and `content()`, clear `renderTimeoutId` on every `destroy()` call, detach abort listeners before settling `content()`, and ensure `asyncDestroyPlatform()` always resolves. --- packages/angular/ssr/src/app.ts | 32 +++- packages/angular/ssr/src/utils/ng.ts | 51 ++++-- packages/angular/ssr/test/app_spec.ts | 50 +++++- packages/angular/ssr/test/utils/ng_spec.ts | 188 +++++++++++++++++++++ 4 files changed, 305 insertions(+), 16 deletions(-) create mode 100644 packages/angular/ssr/test/utils/ng_spec.ts diff --git a/packages/angular/ssr/src/app.ts b/packages/angular/ssr/src/app.ts index b2dd91af1bba..fdf13108e95b 100644 --- a/packages/angular/ssr/src/app.ts +++ b/packages/angular/ssr/src/app.ts @@ -261,6 +261,10 @@ export class AngularServerApp { matchedRoute: RouteTreeNodeMetadata, requestContext?: unknown, ): Promise { + if (request.signal.aborted) { + return null; + } + const { renderMode, headers, status, preload } = matchedRoute; if (!this.allowStaticRouteRender && renderMode === RenderMode.Prerender) { @@ -304,6 +308,10 @@ export class AngularServerApp { } else if (renderMode === RenderMode.Client) { // Serve the client-side rendered version if the route is configured for CSR. let html = await this.assets.getServerAsset('index.csr.html').text(); + if (request.signal.aborted) { + return null; + } + html = await this.runTransformsOnHtml(html, url, preload); return new Response(html, responseInit); @@ -317,8 +325,19 @@ export class AngularServerApp { } this.boostrap ??= await bootstrap(); + if (request.signal.aborted) { + return null; + } + let html = await assets.getIndexServerHtml().text(); + if (request.signal.aborted) { + return null; + } + html = await this.runTransformsOnHtml(html, url, preload); + if (request.signal.aborted) { + return null; + } const result = await renderAngular( html, @@ -329,7 +348,7 @@ export class AngularServerApp { request.signal, ); - if (result.hasNavigationError) { + if (result.hasNavigationError || request.signal.aborted) { return null; } @@ -339,6 +358,10 @@ export class AngularServerApp { if (renderMode === RenderMode.Prerender) { const renderedHtml = await result.content(); + if (request.signal.aborted) { + return null; + } + const finalHtml = this.inlineCriticalCss(renderedHtml); return new Response(finalHtml, responseInit); @@ -349,6 +372,13 @@ export class AngularServerApp { start: async (controller) => { try { let renderedHtml = await result.content(); + if (request.signal.aborted) { + throw new DOMException( + `Request for: ${request.url} was aborted.${request.signal.reason ? `\n${request.signal.reason}` : ''}`, + 'AbortError', + ); + } + renderedHtml = this.inlineCriticalCss(renderedHtml); controller.enqueue(this.textEncoder.encode(renderedHtml)); controller.close(); diff --git a/packages/angular/ssr/src/utils/ng.ts b/packages/angular/ssr/src/utils/ng.ts index fe1879a17930..6057b61d2730 100644 --- a/packages/angular/ssr/src/utils/ng.ts +++ b/packages/angular/ssr/src/utils/ng.ts @@ -106,6 +106,7 @@ export async function renderAngular( let rejectContent: ((reason?: unknown) => void) | undefined; const destroy = (): Promise => { + clearTimeout(renderTimeoutId); rejectContent?.( new DOMException( `Request for: ${url} was aborted.${signal?.reason ? `\n${signal.reason}` : ''}`, @@ -115,7 +116,6 @@ export async function renderAngular( rejectContent = undefined; if (!destroyPromise) { - clearTimeout(renderTimeoutId); signal?.removeEventListener('abort', abortHandler); destroyPromise = asyncDestroyPlatform(platformRef); } @@ -131,14 +131,14 @@ export async function renderAngular( let applicationRef: ApplicationRef; if (isNgModule(bootstrap)) { const moduleRef = await platformRef.bootstrapModule(bootstrap); - if (platformRef.destroyed || signal?.aborted) { + if (platformRef.destroyed || moduleRef.injector.destroyed || signal?.aborted) { return { hasNavigationError: true }; } applicationRef = moduleRef.injector.get(ApplicationRef); } else { applicationRef = await bootstrap({ platformRef }); - if (platformRef.destroyed || signal?.aborted) { + if (platformRef.destroyed || applicationRef.destroyed || signal?.aborted) { return { hasNavigationError: true }; } } @@ -149,7 +149,7 @@ export async function renderAngular( // This code protect against app destruction during bootstrapping which is a // valid case. We should not assume the `applicationRef` is not in destroyed state. // Calling `envInjector.get` would throw `NG0205: Injector has already been destroyed`. - if (applicationRef.destroyed || signal?.aborted) { + if (platformRef.destroyed || applicationRef.destroyed || signal?.aborted) { return { hasNavigationError: true }; } @@ -187,21 +187,42 @@ export async function renderAngular( new Promise((resolve, reject) => { rejectContent = reject; + if ( + destroyPromise || + platformRef.destroyed || + applicationRef.destroyed || + signal?.aborted + ) { + void destroy(); + + return; + } + // Defer rendering to the next event loop iteration to avoid blocking, as most operations in `renderInternal` are synchronous. renderTimeoutId = setTimeout(() => { - if (platformRef.destroyed || applicationRef.destroyed || signal?.aborted) { + if ( + destroyPromise || + platformRef.destroyed || + applicationRef.destroyed || + signal?.aborted + ) { void destroy(); return; } - renderInternal(platformRef, applicationRef) - .then(resolve) - .catch(reject) - .finally(() => { + renderInternal(platformRef, applicationRef).then( + (renderedHtml) => { rejectContent = undefined; void destroy(); - }); + resolve(renderedHtml); + }, + (error) => { + rejectContent = undefined; + void destroy(); + reject(error); + }, + ); }, 0); }), }; @@ -237,11 +258,13 @@ function asyncDestroyPlatform(platformRef: PlatformRef): Promise { return new Promise((resolve) => { setTimeout(() => { - if (!platformRef.destroyed) { - platformRef.destroy(); + try { + if (!platformRef.destroyed) { + platformRef.destroy(); + } + } finally { + resolve(); } - - resolve(); }, 0); }); } diff --git a/packages/angular/ssr/test/app_spec.ts b/packages/angular/ssr/test/app_spec.ts index b50557f1b031..45e501af4e84 100644 --- a/packages/angular/ssr/test/app_spec.ts +++ b/packages/angular/ssr/test/app_spec.ts @@ -24,6 +24,7 @@ import { import { ActivatedRoute, CanActivateFn, Router } from '@angular/router'; import { setTimeout } from 'node:timers/promises'; import { AngularServerApp } from '../src/app'; +import { Hooks } from '../src/hooks'; import { RenderMode } from '../src/routes/route-config'; import { setAngularAppTestingManifest } from './testing-utils'; @@ -399,6 +400,7 @@ describe('AngularServerApp', () => { it('should clean up the abort event listener on request.signal after rendering completes', async () => { const controller = new AbortController(); const request = new Request('http://localhost/home', { signal: controller.signal }); + const addEventListenerSpy = spyOn(request.signal, 'addEventListener').and.callThrough(); const removeEventListenerSpy = spyOn( request.signal, 'removeEventListener', @@ -408,7 +410,53 @@ describe('AngularServerApp', () => { expect(await response?.text()).toContain('Home works'); await setTimeout(0); - expect(removeEventListenerSpy).toHaveBeenCalledWith('abort', jasmine.any(Function)); + const addedAbortListeners = addEventListenerSpy.calls + .allArgs() + .filter(([event]) => event === 'abort') + .map(([, listener]) => listener); + const removedAbortListeners = removeEventListenerSpy.calls + .allArgs() + .filter(([event]) => event === 'abort') + .map(([, listener]) => listener); + + expect(addedAbortListeners.length).toBeGreaterThan(0); + expect(removedAbortListeners).toEqual(jasmine.arrayWithExactContents(addedAbortListeners)); + }); + + it('should skip html:transform:pre hooks when request signal is already aborted', async () => { + try { + setAngularAppTestingManifest( + [{ path: 'home', component: HomeComponent }], + [{ path: '**', renderMode: RenderMode.Server }], + ); + + const hooks = new Hooks(); + const transformSpy = jasmine.createSpy('htmlTransform').and.callFake(({ html }) => html); + hooks.on('html:transform:pre', transformSpy); + + const customApp = new AngularServerApp({ hooks }); + // Warm up router. + const warmup = await customApp.handle(new Request('http://localhost/home')); + await warmup?.text(); + await setTimeout(0); + expect(transformSpy).toHaveBeenCalledTimes(1); + transformSpy.calls.reset(); + + const controller = new AbortController(); + controller.abort(); + + await expectAsync( + customApp.handle(new Request('http://localhost/home', { signal: controller.signal })), + ).toBeRejectedWithError( + DOMException, + /Request for: http:\/\/localhost\/home was aborted/, + ); + + await setTimeout(0); + expect(transformSpy).not.toHaveBeenCalled(); + } finally { + setupManifest(); + } }); it('should reject reading response body if request is aborted after handle() resolves but before rendering completes', async () => { diff --git a/packages/angular/ssr/test/utils/ng_spec.ts b/packages/angular/ssr/test/utils/ng_spec.ts new file mode 100644 index 000000000000..4f10a73c2d12 --- /dev/null +++ b/packages/angular/ssr/test/utils/ng_spec.ts @@ -0,0 +1,188 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +// The compiler is needed as tests are in JIT. +/* eslint-disable import/no-unassigned-import */ +import '@angular/compiler'; +/* eslint-enable import/no-unassigned-import */ + +import { Component, PlatformRef, inject, provideZonelessChangeDetection } from '@angular/core'; +import { bootstrapApplication } from '@angular/platform-browser'; +import { setTimeout } from 'node:timers/promises'; +import { renderAngular } from '../../src/utils/ng'; + +const BASE_HTML = ''; + +describe('renderAngular', () => { + beforeEach(async () => { + // Drain any asyncDestroyPlatform macrotask scheduled by a previous spec. + await setTimeout(0); + }); + + afterEach(async () => { + await setTimeout(0); + }); + + it('should return { hasNavigationError: true } without bootstrapping when signal is already aborted', async () => { + const bootstrapSpy = jasmine.createSpy('bootstrap'); + const destroySpy = spyOn(PlatformRef.prototype, 'destroy').and.callThrough(); + const controller = new AbortController(); + controller.abort(); + + const result = await renderAngular( + BASE_HTML, + bootstrapSpy, + new URL('http://localhost/'), + [], + 'ssr', + controller.signal, + ); + + expect(result).toEqual({ hasNavigationError: true }); + expect(bootstrapSpy).not.toHaveBeenCalled(); + await setTimeout(0); + expect(destroySpy).not.toHaveBeenCalled(); + }); + + it('should reject content() with AbortError and destroy platform once when aborted before content() runs', async () => { + let destroySpy: jasmine.Spy | undefined; + + @Component({ + selector: 'app-root', + template: 'Standalone works', + }) + class AppComponent { + constructor() { + destroySpy = spyOn(inject(PlatformRef), 'destroy').and.callThrough(); + } + } + + const controller = new AbortController(); + const result = await renderAngular( + BASE_HTML, + (context) => + bootstrapApplication( + AppComponent, + { providers: [provideZonelessChangeDetection()] }, + context, + ), + new URL('http://localhost/'), + [], + 'ssr', + controller.signal, + ); + + expect(result.hasNavigationError).toBeFalse(); + if (!('content' in result)) { + fail('Expected renderAngular result to expose content()'); + + return; + } + + controller.abort('client disconnected'); + + let caughtError: unknown; + try { + await result.content(); + fail('Expected content() to reject with AbortError'); + } catch (error) { + caughtError = error; + } + + expect(caughtError).toBeInstanceOf(DOMException); + expect((caughtError as DOMException).name).toBe('AbortError'); + expect((caughtError as DOMException).message).toContain( + 'Request for: http://localhost/ was aborted.\nclient disconnected', + ); + + await setTimeout(0); + expect(destroySpy).toHaveBeenCalledTimes(1); + }); + + it('should reject content() with AbortError if destroy() was already called', async () => { + let destroySpy: jasmine.Spy | undefined; + + @Component({ + selector: 'app-root', + template: 'Destroy before content works', + }) + class AppComponent { + constructor() { + destroySpy = spyOn(inject(PlatformRef), 'destroy').and.callThrough(); + } + } + + const result = await renderAngular( + BASE_HTML, + (context) => + bootstrapApplication( + AppComponent, + { providers: [provideZonelessChangeDetection()] }, + context, + ), + new URL('http://localhost/'), + [], + 'ssr', + ); + + if (!('content' in result)) { + fail('Expected renderAngular result to expose content()'); + + return; + } + + const destroyPromise = result.destroy(); + await expectAsync(result.content()).toBeRejectedWithError( + DOMException, + /Request for: http:\/\/localhost\/ was aborted/, + ); + await destroyPromise; + expect(destroySpy).toHaveBeenCalledTimes(1); + }); + + it('should make destroy() idempotent and return the same promise when called multiple times', async () => { + let destroySpy: jasmine.Spy | undefined; + + @Component({ + selector: 'app-root', + template: 'Idempotent works', + }) + class AppComponent { + constructor() { + destroySpy = spyOn(inject(PlatformRef), 'destroy').and.callThrough(); + } + } + + const result = await renderAngular( + BASE_HTML, + (context) => + bootstrapApplication( + AppComponent, + { providers: [provideZonelessChangeDetection()] }, + context, + ), + new URL('http://localhost/'), + [], + 'ssr', + ); + + if (!('destroy' in result)) { + fail('Expected renderAngular result to expose destroy()'); + + return; + } + + const p1 = result.destroy(); + const p2 = result.destroy(); + expect(p1).toBe(p2); + + await Promise.all([p1, p2, result.destroy()]); + await result.destroy(); + expect(destroySpy).toHaveBeenCalledTimes(1); + }); +});