Skip to content

Commit 106adcc

Browse files
committed
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
1 parent 80631b2 commit 106adcc

2 files changed

Lines changed: 143 additions & 5 deletions

File tree

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

Lines changed: 35 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,12 @@ import { Console } from '../console';
2727
import { addTrailingSlash, joinUrlParts, stripIndexHtmlFromURL, stripTrailingSlash } from './url';
2828
import { getFirstHeaderValue } from './validation';
2929

30+
/**
31+
* The maximum time, in milliseconds, that an aborted render can take to become stable before its platform is destroyed.
32+
* This matches the time in which Angular expects an application to become stable (see NG0506).
33+
*/
34+
const ABORTED_RENDER_TIMEOUT = 10_000;
35+
3036
/**
3137
* Represents the bootstrap mechanism for an Angular application.
3238
*
@@ -104,6 +110,8 @@ export async function renderAngular(
104110
let renderTimeoutId: ReturnType<typeof setTimeout> | undefined;
105111
let destroyPromise: Promise<void> | undefined;
106112
let rejectContent: ((reason?: unknown) => void) | undefined;
113+
let abortTimeoutSignal: AbortSignal | undefined;
114+
let isStable = false;
107115

108116
const destroy = (): Promise<void> => {
109117
rejectContent?.(
@@ -117,34 +125,56 @@ export async function renderAngular(
117125
if (!destroyPromise) {
118126
clearTimeout(renderTimeoutId);
119127
signal?.removeEventListener('abort', abortHandler);
128+
abortTimeoutSignal?.removeEventListener('abort', abortTimeoutHandler);
120129
destroyPromise = asyncDestroyPlatform(platformRef);
121130
}
122131

123132
return destroyPromise;
124133
};
125134

126-
const abortHandler = () => void destroy();
135+
const abortTimeoutHandler = () => void destroy();
127136

128-
try {
129-
signal?.addEventListener('abort', abortHandler, { once: true });
137+
// Destroying the platform while the application has pending work, such as an app initializer or an
138+
// `HttpClient` request, makes that work fail outside of the request where it cannot be caught.
139+
// When the request is aborted before the application is stable, the platform is destroyed once it
140+
// becomes stable, or when `ABORTED_RENDER_TIMEOUT` elapses if it never does.
141+
const abortHandler = () => {
142+
if (isStable) {
143+
void destroy();
144+
145+
return;
146+
}
130147

148+
abortTimeoutSignal = AbortSignal.timeout(ABORTED_RENDER_TIMEOUT);
149+
abortTimeoutSignal.addEventListener('abort', abortTimeoutHandler, { once: true });
150+
};
151+
152+
try {
131153
let applicationRef: ApplicationRef;
132154
if (isNgModule(bootstrap)) {
133155
const moduleRef = await platformRef.bootstrapModule(bootstrap);
134-
if (platformRef.destroyed || signal?.aborted) {
156+
if (platformRef.destroyed) {
135157
return { hasNavigationError: true };
136158
}
137159

138160
applicationRef = moduleRef.injector.get(ApplicationRef);
139161
} else {
140162
applicationRef = await bootstrap({ platformRef });
141-
if (platformRef.destroyed || signal?.aborted) {
163+
if (platformRef.destroyed) {
142164
return { hasNavigationError: true };
143165
}
144166
}
145167

168+
// Aborts are handled after bootstrapping, as app initializers cannot be stopped and use the platform once they settle.
169+
if (signal?.aborted) {
170+
abortHandler();
171+
} else {
172+
signal?.addEventListener('abort', abortHandler, { once: true });
173+
}
174+
146175
// Block until application is stable.
147176
await applicationRef.whenStable();
177+
isStable = true;
148178

149179
// This code protect against app destruction during bootstrapping which is a
150180
// valid case. We should not assume the `applicationRef` is not in destroyed state.

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

Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,11 +15,13 @@ import { APP_BASE_HREF } from '@angular/common';
1515
import {
1616
Component,
1717
DestroyRef,
18+
EnvironmentInjector,
1819
PendingTasks,
1920
PlatformRef,
2021
REQUEST,
2122
RESPONSE_INIT,
2223
inject,
24+
provideAppInitializer,
2325
} from '@angular/core';
2426
import { ActivatedRoute, CanActivateFn, Router } from '@angular/router';
2527
import { setTimeout } from 'node:timers/promises';
@@ -30,6 +32,7 @@ import { setAngularAppTestingManifest } from './testing-utils';
3032
describe('AngularServerApp', () => {
3133
let app: AngularServerApp;
3234
let slowRouteHook: (() => void) | undefined;
35+
let appInitializerHook: (() => Promise<void>) | undefined;
3336

3437
@Component({
3538
selector: 'app-home',
@@ -198,6 +201,7 @@ describe('AngularServerApp', () => {
198201
provide: APP_BASE_HREF,
199202
useFactory: () => inject(REQUEST)?.headers.get('X-Forwarded-Prefix'),
200203
},
204+
provideAppInitializer(() => appInitializerHook?.()),
201205
],
202206
);
203207

@@ -340,6 +344,8 @@ describe('AngularServerApp', () => {
340344
});
341345
let appDestroyed = false;
342346
let destroySpy: jasmine.Spy | undefined;
347+
const abortTimeout = new AbortController();
348+
spyOn(AbortSignal, 'timeout').and.returnValue(abortTimeout.signal);
343349

344350
slowRouteHook = () => {
345351
destroySpy = spyOn(inject(PlatformRef), 'destroy').and.callThrough();
@@ -369,6 +375,11 @@ describe('AngularServerApp', () => {
369375
DOMException,
370376
/Request for: http:\/\/localhost\/page-slow was aborted/,
371377
);
378+
await setTimeout(0);
379+
expect(destroySpy).not.toHaveBeenCalled();
380+
381+
// Simulate the abort timeout elapsing as the pending task never resolves
382+
abortTimeout.abort();
372383

373384
// Wait for the macrotask queue to clear since platform destruction is scheduled via setTimeout(0)
374385
await setTimeout(0);
@@ -379,6 +390,103 @@ describe('AngularServerApp', () => {
379390
}
380391
});
381392

393+
it('should destroy the platform once pending work settles when an in-flight request is aborted', async () => {
394+
const { promise: taskReady, resolve: resolveTaskReady } = Promise.withResolvers<void>();
395+
const { promise: workDone, resolve: resolveWork } = Promise.withResolvers<void>();
396+
const { promise: platformDestroyed, resolve: resolvePlatformDestroyed } =
397+
Promise.withResolvers<void>();
398+
let pendingWork: Promise<unknown> | undefined;
399+
let destroySpy: jasmine.Spy | undefined;
400+
401+
slowRouteHook = () => {
402+
const platformRef = inject(PlatformRef);
403+
destroySpy = spyOn(platformRef, 'destroy').and.callThrough();
404+
platformRef.onDestroy(resolvePlatformDestroyed);
405+
406+
// Like an `HttpClient` request, this work holds a pending task and uses the application once it settles
407+
const injector = inject(EnvironmentInjector);
408+
const removeTask = inject(PendingTasks).add();
409+
pendingWork = workDone.then(() => injector.get(Router)).finally(removeTask);
410+
resolveTaskReady();
411+
};
412+
413+
try {
414+
const controller = new AbortController();
415+
const request = new Request('http://localhost/page-slow', { signal: controller.signal });
416+
417+
const handlePromise = app.handle(request);
418+
419+
// Abort the request while the work is still pending
420+
await taskReady;
421+
controller.abort();
422+
423+
await expectAsync(handlePromise).toBeRejectedWithError(
424+
DOMException,
425+
/Request for: http:\/\/localhost\/page-slow was aborted/,
426+
);
427+
await setTimeout(0);
428+
expect(destroySpy).not.toHaveBeenCalled();
429+
430+
resolveWork();
431+
await expectAsync(pendingWork).toBeResolved();
432+
433+
await platformDestroyed;
434+
expect(destroySpy).toHaveBeenCalledTimes(1);
435+
} finally {
436+
slowRouteHook = undefined;
437+
}
438+
});
439+
440+
it('should wait for a pending app initializer before destroying the platform when the request is aborted', async () => {
441+
// Warm up the router so route extraction does not run the app initializer during this test
442+
const warmupResponse = await app.handle(new Request('http://localhost/home'));
443+
await warmupResponse?.text();
444+
await setTimeout(0);
445+
446+
const { promise: initializerStarted, resolve: resolveInitializerStarted } =
447+
Promise.withResolvers<void>();
448+
const { promise: initializerDone, resolve: resolveInitializer } =
449+
Promise.withResolvers<void>();
450+
const { promise: platformDestroyed, resolve: resolvePlatformDestroyed } =
451+
Promise.withResolvers<void>();
452+
let destroySpy: jasmine.Spy | undefined;
453+
454+
appInitializerHook = () => {
455+
const platformRef = inject(PlatformRef);
456+
destroySpy = spyOn(platformRef, 'destroy').and.callThrough();
457+
platformRef.onDestroy(resolvePlatformDestroyed);
458+
resolveInitializerStarted();
459+
460+
return initializerDone;
461+
};
462+
463+
try {
464+
const controller = new AbortController();
465+
const request = new Request('http://localhost/home', { signal: controller.signal });
466+
467+
const handlePromise = app.handle(request);
468+
469+
// Abort the request while the app initializer is still pending
470+
await initializerStarted;
471+
controller.abort();
472+
473+
await expectAsync(handlePromise).toBeRejectedWithError(
474+
DOMException,
475+
/Request for: http:\/\/localhost\/home was aborted/,
476+
);
477+
await setTimeout(0);
478+
expect(destroySpy).not.toHaveBeenCalled();
479+
480+
// Bootstrapping reads from the application injector once the initializer settles
481+
resolveInitializer();
482+
483+
await platformDestroyed;
484+
expect(destroySpy).toHaveBeenCalledTimes(1);
485+
} finally {
486+
appInitializerHook = undefined;
487+
}
488+
});
489+
382490
it('should not bootstrap the platform if the request signal is already aborted', async () => {
383491
// Warm up the router so route extraction does not create a PlatformRef during this test
384492
const warmupResponse = await app.handle(new Request('http://localhost/home'));

0 commit comments

Comments
 (0)