Skip to content

Commit 66d97cf

Browse files
committed
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.
1 parent 80631b2 commit 66d97cf

4 files changed

Lines changed: 305 additions & 16 deletions

File tree

‎packages/angular/ssr/src/app.ts‎

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -261,6 +261,10 @@ export class AngularServerApp {
261261
matchedRoute: RouteTreeNodeMetadata,
262262
requestContext?: unknown,
263263
): Promise<Response | null> {
264+
if (request.signal.aborted) {
265+
return null;
266+
}
267+
264268
const { renderMode, headers, status, preload } = matchedRoute;
265269

266270
if (!this.allowStaticRouteRender && renderMode === RenderMode.Prerender) {
@@ -304,6 +308,10 @@ export class AngularServerApp {
304308
} else if (renderMode === RenderMode.Client) {
305309
// Serve the client-side rendered version if the route is configured for CSR.
306310
let html = await this.assets.getServerAsset('index.csr.html').text();
311+
if (request.signal.aborted) {
312+
return null;
313+
}
314+
307315
html = await this.runTransformsOnHtml(html, url, preload);
308316

309317
return new Response(html, responseInit);
@@ -317,8 +325,19 @@ export class AngularServerApp {
317325
}
318326

319327
this.boostrap ??= await bootstrap();
328+
if (request.signal.aborted) {
329+
return null;
330+
}
331+
320332
let html = await assets.getIndexServerHtml().text();
333+
if (request.signal.aborted) {
334+
return null;
335+
}
336+
321337
html = await this.runTransformsOnHtml(html, url, preload);
338+
if (request.signal.aborted) {
339+
return null;
340+
}
322341

323342
const result = await renderAngular(
324343
html,
@@ -329,7 +348,7 @@ export class AngularServerApp {
329348
request.signal,
330349
);
331350

332-
if (result.hasNavigationError) {
351+
if (result.hasNavigationError || request.signal.aborted) {
333352
return null;
334353
}
335354

@@ -339,6 +358,10 @@ export class AngularServerApp {
339358

340359
if (renderMode === RenderMode.Prerender) {
341360
const renderedHtml = await result.content();
361+
if (request.signal.aborted) {
362+
return null;
363+
}
364+
342365
const finalHtml = this.inlineCriticalCss(renderedHtml);
343366

344367
return new Response(finalHtml, responseInit);
@@ -349,6 +372,13 @@ export class AngularServerApp {
349372
start: async (controller) => {
350373
try {
351374
let renderedHtml = await result.content();
375+
if (request.signal.aborted) {
376+
throw new DOMException(
377+
`Request for: ${request.url} was aborted.${request.signal.reason ? `\n${request.signal.reason}` : ''}`,
378+
'AbortError',
379+
);
380+
}
381+
352382
renderedHtml = this.inlineCriticalCss(renderedHtml);
353383
controller.enqueue(this.textEncoder.encode(renderedHtml));
354384
controller.close();

‎packages/angular/ssr/src/utils/ng.ts‎

Lines changed: 37 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,7 @@ export async function renderAngular(
106106
let rejectContent: ((reason?: unknown) => void) | undefined;
107107

108108
const destroy = (): Promise<void> => {
109+
clearTimeout(renderTimeoutId);
109110
rejectContent?.(
110111
new DOMException(
111112
`Request for: ${url} was aborted.${signal?.reason ? `\n${signal.reason}` : ''}`,
@@ -115,7 +116,6 @@ export async function renderAngular(
115116
rejectContent = undefined;
116117

117118
if (!destroyPromise) {
118-
clearTimeout(renderTimeoutId);
119119
signal?.removeEventListener('abort', abortHandler);
120120
destroyPromise = asyncDestroyPlatform(platformRef);
121121
}
@@ -131,14 +131,14 @@ export async function renderAngular(
131131
let applicationRef: ApplicationRef;
132132
if (isNgModule(bootstrap)) {
133133
const moduleRef = await platformRef.bootstrapModule(bootstrap);
134-
if (platformRef.destroyed || signal?.aborted) {
134+
if (platformRef.destroyed || moduleRef.injector.destroyed || signal?.aborted) {
135135
return { hasNavigationError: true };
136136
}
137137

138138
applicationRef = moduleRef.injector.get(ApplicationRef);
139139
} else {
140140
applicationRef = await bootstrap({ platformRef });
141-
if (platformRef.destroyed || signal?.aborted) {
141+
if (platformRef.destroyed || applicationRef.destroyed || signal?.aborted) {
142142
return { hasNavigationError: true };
143143
}
144144
}
@@ -149,7 +149,7 @@ export async function renderAngular(
149149
// This code protect against app destruction during bootstrapping which is a
150150
// valid case. We should not assume the `applicationRef` is not in destroyed state.
151151
// Calling `envInjector.get` would throw `NG0205: Injector has already been destroyed`.
152-
if (applicationRef.destroyed || signal?.aborted) {
152+
if (platformRef.destroyed || applicationRef.destroyed || signal?.aborted) {
153153
return { hasNavigationError: true };
154154
}
155155

@@ -187,21 +187,42 @@ export async function renderAngular(
187187
new Promise<string>((resolve, reject) => {
188188
rejectContent = reject;
189189

190+
if (
191+
destroyPromise ||
192+
platformRef.destroyed ||
193+
applicationRef.destroyed ||
194+
signal?.aborted
195+
) {
196+
void destroy();
197+
198+
return;
199+
}
200+
190201
// Defer rendering to the next event loop iteration to avoid blocking, as most operations in `renderInternal` are synchronous.
191202
renderTimeoutId = setTimeout(() => {
192-
if (platformRef.destroyed || applicationRef.destroyed || signal?.aborted) {
203+
if (
204+
destroyPromise ||
205+
platformRef.destroyed ||
206+
applicationRef.destroyed ||
207+
signal?.aborted
208+
) {
193209
void destroy();
194210

195211
return;
196212
}
197213

198-
renderInternal(platformRef, applicationRef)
199-
.then(resolve)
200-
.catch(reject)
201-
.finally(() => {
214+
renderInternal(platformRef, applicationRef).then(
215+
(renderedHtml) => {
202216
rejectContent = undefined;
203217
void destroy();
204-
});
218+
resolve(renderedHtml);
219+
},
220+
(error) => {
221+
rejectContent = undefined;
222+
void destroy();
223+
reject(error);
224+
},
225+
);
205226
}, 0);
206227
}),
207228
};
@@ -237,11 +258,13 @@ function asyncDestroyPlatform(platformRef: PlatformRef): Promise<void> {
237258

238259
return new Promise((resolve) => {
239260
setTimeout(() => {
240-
if (!platformRef.destroyed) {
241-
platformRef.destroy();
261+
try {
262+
if (!platformRef.destroyed) {
263+
platformRef.destroy();
264+
}
265+
} finally {
266+
resolve();
242267
}
243-
244-
resolve();
245268
}, 0);
246269
});
247270
}

‎packages/angular/ssr/test/app_spec.ts‎

Lines changed: 49 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ import {
2424
import { ActivatedRoute, CanActivateFn, Router } from '@angular/router';
2525
import { setTimeout } from 'node:timers/promises';
2626
import { AngularServerApp } from '../src/app';
27+
import { Hooks } from '../src/hooks';
2728
import { RenderMode } from '../src/routes/route-config';
2829
import { setAngularAppTestingManifest } from './testing-utils';
2930

@@ -399,6 +400,7 @@ describe('AngularServerApp', () => {
399400
it('should clean up the abort event listener on request.signal after rendering completes', async () => {
400401
const controller = new AbortController();
401402
const request = new Request('http://localhost/home', { signal: controller.signal });
403+
const addEventListenerSpy = spyOn(request.signal, 'addEventListener').and.callThrough();
402404
const removeEventListenerSpy = spyOn(
403405
request.signal,
404406
'removeEventListener',
@@ -408,7 +410,53 @@ describe('AngularServerApp', () => {
408410
expect(await response?.text()).toContain('Home works');
409411
await setTimeout(0);
410412

411-
expect(removeEventListenerSpy).toHaveBeenCalledWith('abort', jasmine.any(Function));
413+
const addedAbortListeners = addEventListenerSpy.calls
414+
.allArgs()
415+
.filter(([event]) => event === 'abort')
416+
.map(([, listener]) => listener);
417+
const removedAbortListeners = removeEventListenerSpy.calls
418+
.allArgs()
419+
.filter(([event]) => event === 'abort')
420+
.map(([, listener]) => listener);
421+
422+
expect(addedAbortListeners.length).toBeGreaterThan(0);
423+
expect(removedAbortListeners).toEqual(jasmine.arrayWithExactContents(addedAbortListeners));
424+
});
425+
426+
it('should skip html:transform:pre hooks when request signal is already aborted', async () => {
427+
try {
428+
setAngularAppTestingManifest(
429+
[{ path: 'home', component: HomeComponent }],
430+
[{ path: '**', renderMode: RenderMode.Server }],
431+
);
432+
433+
const hooks = new Hooks();
434+
const transformSpy = jasmine.createSpy('htmlTransform').and.callFake(({ html }) => html);
435+
hooks.on('html:transform:pre', transformSpy);
436+
437+
const customApp = new AngularServerApp({ hooks });
438+
// Warm up router.
439+
const warmup = await customApp.handle(new Request('http://localhost/home'));
440+
await warmup?.text();
441+
await setTimeout(0);
442+
expect(transformSpy).toHaveBeenCalledTimes(1);
443+
transformSpy.calls.reset();
444+
445+
const controller = new AbortController();
446+
controller.abort();
447+
448+
await expectAsync(
449+
customApp.handle(new Request('http://localhost/home', { signal: controller.signal })),
450+
).toBeRejectedWithError(
451+
DOMException,
452+
/Request for: http:\/\/localhost\/home was aborted/,
453+
);
454+
455+
await setTimeout(0);
456+
expect(transformSpy).not.toHaveBeenCalled();
457+
} finally {
458+
setupManifest();
459+
}
412460
});
413461

414462
it('should reject reading response body if request is aborted after handle() resolves but before rendering completes', async () => {

0 commit comments

Comments
 (0)