Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 35 additions & 5 deletions packages/angular/ssr/src/utils/ng.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand Down Expand Up @@ -104,6 +110,8 @@ export async function renderAngular(
let renderTimeoutId: ReturnType<typeof setTimeout> | undefined;
let destroyPromise: Promise<void> | undefined;
let rejectContent: ((reason?: unknown) => void) | undefined;
let abortTimeoutSignal: AbortSignal | undefined;
let isStable = false;
Comment on lines +113 to +114

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

Instead of using AbortSignal.timeout, which creates a timer that cannot be cleared manually and can keep the Node.js event loop active (potentially causing serverless functions to hang or delay termination), we can use a standard setTimeout and clearTimeout approach. This is simpler, more compatible, and avoids event loop retention issues.

Suggested change
let abortTimeoutSignal: AbortSignal | undefined;
let isStable = false;
let abortTimeoutId: ReturnType<typeof setTimeout> | undefined;
let isStable = false;

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AbortSignal.timeout() doesn't keep the event loop alive, in Node its timer is unref'd. I tested it with the built server: aborting a request whose render never becomes stable and then closing the server, the process exits right away (0.00 s), while with a setTimeout it waits for the timer (9.83 s).

It's also what the route extraction and render workers already use for their 30 s deadlines, and the listener is removed when the platform is destroyed, so the timer firing later does nothing. Keeping it as is.


const destroy = (): Promise<void> => {
rejectContent?.(
Expand All @@ -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 });
};
Comment thread
SkyZeroZx marked this conversation as resolved.
Resolved

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.
Expand Down
108 changes: 108 additions & 0 deletions packages/angular/ssr/test/app_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -30,6 +32,7 @@ import { setAngularAppTestingManifest } from './testing-utils';
describe('AngularServerApp', () => {
let app: AngularServerApp;
let slowRouteHook: (() => void) | undefined;
let appInitializerHook: (() => Promise<void>) | undefined;

@Component({
selector: 'app-home',
Expand Down Expand Up @@ -198,6 +201,7 @@ describe('AngularServerApp', () => {
provide: APP_BASE_HREF,
useFactory: () => inject(REQUEST)?.headers.get('X-Forwarded-Prefix'),
},
provideAppInitializer(() => appInitializerHook?.()),
],
);

Expand Down Expand Up @@ -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);
Comment thread
SkyZeroZx marked this conversation as resolved.
Resolved

slowRouteHook = () => {
destroySpy = spyOn(inject(PlatformRef), 'destroy').and.callThrough();
Expand Down Expand Up @@ -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();
Comment thread
SkyZeroZx marked this conversation as resolved.
Resolved

// Wait for the macrotask queue to clear since platform destruction is scheduled via setTimeout(0)
await setTimeout(0);
Expand All @@ -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<void>();
const { promise: workDone, resolve: resolveWork } = Promise.withResolvers<void>();
const { promise: platformDestroyed, resolve: resolvePlatformDestroyed } =
Promise.withResolvers<void>();
let pendingWork: Promise<unknown> | 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<void>();
const { promise: initializerDone, resolve: resolveInitializer } =
Promise.withResolvers<void>();
const { promise: platformDestroyed, resolve: resolvePlatformDestroyed } =
Promise.withResolvers<void>();
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'));
Expand Down