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
32 changes: 31 additions & 1 deletion packages/angular/ssr/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -261,6 +261,10 @@ export class AngularServerApp {
matchedRoute: RouteTreeNodeMetadata,
requestContext?: unknown,
): Promise<Response | null> {
if (request.signal.aborted) {
return null;
}

const { renderMode, headers, status, preload } = matchedRoute;

if (!this.allowStaticRouteRender && renderMode === RenderMode.Prerender) {
Expand Down Expand Up @@ -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;
}
Comment thread
alan-agius4 marked this conversation as resolved.
Resolved

html = await this.runTransformsOnHtml(html, url, preload);

return new Response(html, responseInit);
Expand All @@ -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,
Expand All @@ -329,7 +348,7 @@ export class AngularServerApp {
request.signal,
);

if (result.hasNavigationError) {
if (result.hasNavigationError || request.signal.aborted) {
return null;
}

Expand All @@ -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);
Expand All @@ -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();
Expand Down
51 changes: 37 additions & 14 deletions packages/angular/ssr/src/utils/ng.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ export async function renderAngular(
let rejectContent: ((reason?: unknown) => void) | undefined;

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

if (!destroyPromise) {
clearTimeout(renderTimeoutId);
signal?.removeEventListener('abort', abortHandler);
destroyPromise = asyncDestroyPlatform(platformRef);
}
Expand All @@ -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 };
}
}
Expand All @@ -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 };
}

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

if (
destroyPromise ||
platformRef.destroyed ||
applicationRef.destroyed ||
signal?.aborted
) {
void destroy();

return;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Question: Do we need to call reject in these cases? Seems like we're not doing that now, but feels weird to leave a dangling promise.

}

// 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);
}),
};
Expand Down Expand Up @@ -237,11 +258,13 @@ function asyncDestroyPlatform(platformRef: PlatformRef): Promise<void> {

return new Promise((resolve) => {
setTimeout(() => {
if (!platformRef.destroyed) {
platformRef.destroy();
try {
if (!platformRef.destroyed) {
platformRef.destroy();
}
} finally {
resolve();
}

resolve();
}, 0);
});
}
Expand Down
50 changes: 49 additions & 1 deletion packages/angular/ssr/test/app_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down Expand Up @@ -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',
Expand All @@ -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 () => {
Expand Down
Loading