Skip to content

Commit 7afdd87

Browse files
committed
fix(@angular/ssr): destroy platform when request is aborted during rendering
Previously, aborting `request.signal` during server-side rendering caused `AngularServerApp.handle()` to reject via `promiseWithAbort`, while `renderAngular()` continued running in the background until `whenStable()` completed (or leaked the platform if a pending task never resolved). This commit forwards `request.signal` into `renderAngular()` so that aborting an in-flight request destroys the underlying `PlatformRef`, cancels any pending render timer, and exits cleanly. Additionally, `promiseWithAbort()` now attaches rejection handlers to the underlying promise even when the signal is already aborted to avoid unhandled promise rejections. Closes #34567
1 parent 7a7d184 commit 7afdd87

7 files changed

Lines changed: 171 additions & 17 deletions

File tree

‎packages/angular/ssr/node/src/app-engine.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,9 @@ export class AngularNodeAppEngine {
5959
* @param requestContext - Optional context for rendering, such as metadata associated with the request.
6060
* @returns A promise that resolves to the resulting HTTP response object, or `null` if no matching Angular route is found.
6161
*
62+
* @throws {DOMException} With name `'AbortError'` if the request is aborted before rendering completes.
63+
* When aborted, the underlying Angular platform is also destroyed to stop any in-progress rendering.
64+
*
6265
* @remarks A request to `https://www.example.com/page/index.html` will serve or render the Angular route
6366
* corresponding to `https://www.example.com/page`.
6467
*

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

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,9 @@ export class AngularAppEngine {
144144
* @param requestContext - Optional context for rendering, such as metadata associated with the request.
145145
* @returns A promise that resolves to the resulting HTTP response object, or `null` if no matching Angular route is found.
146146
*
147+
* @throws {DOMException} With name `'AbortError'` if `request.signal` is aborted before rendering completes.
148+
* When aborted, the underlying Angular platform is also destroyed to stop any in-progress rendering.
149+
*
147150
* @remarks A request to `https://www.example.com/page/index.html` will serve or render the Angular route
148151
* corresponding to `https://www.example.com/page`.
149152
*

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

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,9 @@ export class AngularServerApp {
147147
* @param requestContext - Optional context for rendering, such as metadata associated with the request.
148148
* @returns A promise that resolves to the resulting HTTP response object, or `null` if no matching Angular route is found.
149149
*
150+
* @throws {DOMException} With name `'AbortError'` if `request.signal` is aborted before rendering completes.
151+
* When aborted, the underlying Angular platform is also destroyed to stop any in-progress rendering.
152+
*
150153
* @remarks A request to `https://www.example.com/page/index.html` will serve or render the Angular route
151154
* corresponding to `https://www.example.com/page`.
152155
*/
@@ -323,6 +326,7 @@ export class AngularServerApp {
323326
url,
324327
platformProviders,
325328
SERVER_CONTEXT_VALUE[renderMode],
329+
request.signal,
326330
);
327331

328332
if (result.hasNavigationError) {

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

Lines changed: 41 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -47,17 +47,20 @@ export type AngularBootstrap =
4747
* @param url - The application URL, used for route-based rendering in SSR.
4848
* @param platformProviders - An array of platform providers for the rendering process.
4949
* @param serverContext - A string representing the server context, providing additional metadata for SSR.
50+
* @param signal - An optional `AbortSignal` to abort the rendering process and destroy the platform.
5051
* @returns A promise resolving to an object containing:
51-
* - `hasNavigationError`: Indicates if a navigation error occurred.
52+
* - `hasNavigationError`: Indicates if a navigation error occurred or if rendering was aborted/destroyed before stability.
5253
* - `redirectTo`: (Optional) The redirect URL if a navigation redirect occurred.
53-
* - `content`: A function returning a promise that resolves to the rendered HTML string.
54+
* - `content`: (Present when `hasNavigationError` is `false`) A function returning a promise that resolves to the rendered HTML string.
55+
* - `destroy`: (Present when `hasNavigationError` is `false`) A function to destroy the underlying Angular platform.
5456
*/
5557
export async function renderAngular(
5658
html: string,
5759
bootstrap: AngularBootstrap,
5860
url: URL,
5961
platformProviders: StaticProvider[],
6062
serverContext: string,
63+
signal?: AbortSignal,
6164
): Promise<
6265
| { hasNavigationError: true }
6366
| {
@@ -67,6 +70,10 @@ export async function renderAngular(
6770
destroy: () => void;
6871
}
6972
> {
73+
if (signal?.aborted) {
74+
return { hasNavigationError: true };
75+
}
76+
7077
// A request to `http://www.example.com/page/index.html` will render the Angular route corresponding to `http://www.example.com/page`.
7178
const urlToRender = stripIndexHtmlFromURL(url);
7279
const platformRef = platformServer([
@@ -94,14 +101,34 @@ export async function renderAngular(
94101

95102
let redirectTo: string | undefined;
96103
let hasNavigationError = true;
104+
let renderTimeoutId: ReturnType<typeof setTimeout> | undefined;
105+
106+
const destroy = () => {
107+
clearTimeout(renderTimeoutId);
108+
signal?.removeEventListener('abort', abortHandler);
109+
void asyncDestroyPlatform(platformRef);
110+
};
111+
112+
const abortHandler = () => {
113+
destroy();
114+
};
97115

98116
try {
117+
signal?.addEventListener('abort', abortHandler, { once: true });
118+
99119
let applicationRef: ApplicationRef;
100120
if (isNgModule(bootstrap)) {
101121
const moduleRef = await platformRef.bootstrapModule(bootstrap);
122+
if (platformRef.destroyed || signal?.aborted) {
123+
return { hasNavigationError: true };
124+
}
125+
102126
applicationRef = moduleRef.injector.get(ApplicationRef);
103127
} else {
104128
applicationRef = await bootstrap({ platformRef });
129+
if (platformRef.destroyed || signal?.aborted) {
130+
return { hasNavigationError: true };
131+
}
105132
}
106133

107134
// Block until application is stable.
@@ -110,7 +137,7 @@ export async function renderAngular(
110137
// This code protect against app destruction during bootstrapping which is a
111138
// valid case. We should not assume the `applicationRef` is not in destroyed state.
112139
// Calling `envInjector.get` would throw `NG0205: Injector has already been destroyed`.
113-
if (applicationRef.destroyed) {
140+
if (applicationRef.destroyed || signal?.aborted) {
114141
return { hasNavigationError: true };
115142
}
116143

@@ -141,27 +168,34 @@ export async function renderAngular(
141168
}
142169

143170
return {
144-
destroy: () => void asyncDestroyPlatform(platformRef),
171+
destroy,
145172
hasNavigationError,
146173
redirectTo,
147174
content: () =>
148175
new Promise<string>((resolve, reject) => {
149176
// Defer rendering to the next event loop iteration to avoid blocking, as most operations in `renderInternal` are synchronous.
150-
setTimeout(() => {
177+
renderTimeoutId = setTimeout(() => {
178+
if (platformRef.destroyed || applicationRef.destroyed || signal?.aborted) {
179+
destroy();
180+
181+
return;
182+
}
183+
151184
renderInternal(platformRef, applicationRef)
152185
.then(resolve)
153186
.catch(reject)
154-
.finally(() => void asyncDestroyPlatform(platformRef));
187+
.finally(destroy);
155188
}, 0);
156189
}),
157190
};
158191
} catch (error) {
192+
signal?.removeEventListener('abort', abortHandler);
159193
await asyncDestroyPlatform(platformRef);
160194

161195
throw error;
162196
} finally {
163197
if (hasNavigationError || redirectTo) {
164-
void asyncDestroyPlatform(platformRef);
198+
destroy();
165199
}
166200
}
167201
}

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

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
* @returns A promise that either resolves with the value of the provided `promise` or rejects with
1818
* an `AbortError` if the `AbortSignal` is triggered.
1919
*
20-
* @throws {AbortError} If the `AbortSignal` is triggered before the `promise` resolves.
20+
* @throws {DOMException} With name `'AbortError'` if the `AbortSignal` is triggered before the `promise` resolves.
2121
*/
2222
export function promiseWithAbort<T>(
2323
promise: Promise<T>,
@@ -34,12 +34,10 @@ export function promiseWithAbort<T>(
3434
// Check for abort signal
3535
if (signal.aborted) {
3636
abortHandler();
37-
38-
return;
37+
} else {
38+
signal.addEventListener('abort', abortHandler, { once: true });
3939
}
4040

41-
signal.addEventListener('abort', abortHandler, { once: true });
42-
4341
promise
4442
.then(resolve)
4543
.catch(reject)

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

Lines changed: 101 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,15 @@ import '@angular/compiler';
1212
/* eslint-enable import/no-unassigned-import */
1313

1414
import { APP_BASE_HREF } from '@angular/common';
15-
import { Component, PlatformRef, REQUEST, RESPONSE_INIT, inject } from '@angular/core';
15+
import {
16+
Component,
17+
DestroyRef,
18+
PendingTasks,
19+
PlatformRef,
20+
REQUEST,
21+
RESPONSE_INIT,
22+
inject,
23+
} from '@angular/core';
1624
import { ActivatedRoute, CanActivateFn, Router } from '@angular/router';
1725
import { setTimeout } from 'node:timers/promises';
1826
import { AngularServerApp } from '../src/app';
@@ -313,14 +321,102 @@ describe('AngularServerApp', () => {
313321
controller.abort();
314322
});
315323

324+
await expectAsync(app.handle(request)).toBeRejectedWithError(
325+
DOMException,
326+
/Request for: http:\/\/localhost\/home was aborted/,
327+
);
328+
});
329+
330+
it('should destroy the platform and stop rendering when an in-flight request is aborted', async () => {
331+
let resolveTaskReady!: () => void;
332+
const taskReady = new Promise<void>((resolve) => {
333+
resolveTaskReady = resolve;
334+
});
335+
let appDestroyed = false;
336+
let destroySpy: jasmine.Spy | undefined;
337+
338+
@Component({
339+
selector: 'app-slow',
340+
template: 'Slow page',
341+
})
342+
class SlowComponent {
343+
constructor() {
344+
destroySpy = spyOn(inject(PlatformRef), 'destroy').and.callThrough();
345+
const pendingTasks = inject(PendingTasks);
346+
const removeTask = pendingTasks.add();
347+
inject(DestroyRef).onDestroy(() => {
348+
appDestroyed = true;
349+
removeTask();
350+
});
351+
resolveTaskReady();
352+
}
353+
}
354+
316355
try {
317-
await app.handle(request);
318-
throw new Error('Should not be called.');
319-
} catch (e) {
320-
expect(e).toBeInstanceOf(DOMException);
356+
setAngularAppTestingManifest(
357+
[{ path: 'slow', component: SlowComponent }],
358+
[{ path: 'slow', renderMode: RenderMode.Server }],
359+
);
360+
361+
const customApp = new AngularServerApp();
362+
const controller = new AbortController();
363+
const request = new Request('http://localhost/slow', { signal: controller.signal });
364+
365+
const handlePromise = customApp.handle(request);
366+
367+
// Wait until the component is instantiated and holding a pending task
368+
await taskReady;
369+
expect(appDestroyed).toBeFalse();
370+
371+
// Abort the request while `applicationRef.whenStable()` is still pending
372+
controller.abort();
373+
374+
await expectAsync(handlePromise).toBeRejectedWithError(
375+
DOMException,
376+
/Request for: http:\/\/localhost\/slow was aborted/,
377+
);
378+
379+
// Wait for the macrotask queue to clear since platform destruction is scheduled via setTimeout(0)
380+
await setTimeout(0);
381+
expect(destroySpy).toHaveBeenCalledTimes(1);
382+
expect(appDestroyed).toBeTrue();
383+
} finally {
384+
setupManifest();
321385
}
322386
});
323387

388+
it('should not bootstrap the platform if the request signal is already aborted', async () => {
389+
// Warm up the router so route extraction does not create a PlatformRef during this test
390+
const warmupResponse = await app.handle(new Request('http://localhost/home'));
391+
await warmupResponse?.text();
392+
await setTimeout(0);
393+
394+
const destroySpy = spyOn(PlatformRef.prototype, 'destroy').and.callThrough();
395+
const controller = new AbortController();
396+
controller.abort();
397+
398+
const request = new Request('http://localhost/home', { signal: controller.signal });
399+
await expectAsync(app.handle(request)).toBeRejectedWithError(DOMException);
400+
401+
await setTimeout(0);
402+
expect(destroySpy).not.toHaveBeenCalled();
403+
});
404+
405+
it('should clean up the abort event listener on request.signal after rendering completes', async () => {
406+
const controller = new AbortController();
407+
const request = new Request('http://localhost/home', { signal: controller.signal });
408+
const removeEventListenerSpy = spyOn(
409+
request.signal,
410+
'removeEventListener',
411+
).and.callThrough();
412+
413+
const response = await app.handle(request);
414+
expect(await response?.text()).toContain('Home works');
415+
await setTimeout(0);
416+
417+
expect(removeEventListenerSpy).toHaveBeenCalledWith('abort', jasmine.any(Function));
418+
});
419+
324420
it('should return configured headers for pages with specific header settings', async () => {
325421
const response = await app.handle(new Request('http://localhost/page-with-headers'));
326422
const headers = response?.headers.entries() ?? [];

‎packages/angular/ssr/test/utils/promise_spec.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,4 +33,20 @@ describe('promiseWithAbort', () => {
3333

3434
await expectAsync(promise).toBeResolved();
3535
});
36+
37+
it('should reject with an AbortError and handle subsequent promise rejection when signal is already aborted', async () => {
38+
const abortController = new AbortController();
39+
abortController.abort('Already aborted');
40+
41+
let reject!: (reason?: unknown) => void;
42+
const underlyingPromise = new Promise<void>((_, r) => {
43+
reject = r;
44+
});
45+
const promise = promiseWithAbort(underlyingPromise, abortController.signal, 'Test operation');
46+
47+
await expectAsync(promise).toBeRejectedWithError(DOMException, /Test operation was aborted/);
48+
49+
// Rejecting the underlying promise after abort should not cause an unhandled rejection
50+
reject(new Error('Late failure'));
51+
});
3652
});

0 commit comments

Comments
 (0)