Skip to content
Merged
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
4 changes: 2 additions & 2 deletions .talismanrc
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,7 @@ fileignoreconfig:
- "a project name passed on argv to the project resolver"
- "expect\\(Object.keys\\(DEPENDENCIES\\)\\).toEqual\\(\\['project', 'env'\\]\\)"
- filename: AGENTS.md
checksum: 5e00b7347fb405145f6b1059ef533ff5b58ef5b4e4f2af5fab3b5dd9424529c4
checksum: e7f2d908061e4b982b2e866c17e716467835cb5e7fd08bfc97b77331cb91d554
allowed_patterns:
- "Do not add an exemption to a guard to make a new file pass"
- "passes its own error wording to `client.request\\(req, MESSAGES\\)`"
Expand Down Expand Up @@ -286,7 +286,7 @@ fileignoreconfig:
- filename: test/integration/projects-list-command.test.ts
checksum: 6709766943430b80aad2d7200102d936a92321e86c41f66d6a60a5baf82a81bf
- filename: src/functions/cloud-functions.test.ts
checksum: ae6261584e816fb4839b8ae52b3d6b80db2ab26b12b6f0c3cc3f9f555a6cc521
checksum: 2e62e1c79b12f7c140a2a4088ebde787196380370142aee165b4834a0856bf4c
- filename: src/functions/function.errors.ts
checksum: cad477cf24c97bf3395427235ca1de0f305369d05d61c21a83435654df2269e3
- filename: src/transport/proxy.test.ts
Expand Down
11 changes: 7 additions & 4 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -593,10 +593,13 @@ The approved differences from V1 are these, and only these:
response with 504 CF005 after the timeout.
- **A function that reaches a file outside `functions/` is warned about, not refused**, naming
the function file that crosses the boundary.
- **Errors name the user's file.** A function that fails to bundle or load stops serve with
`Could not load functions/<file>.js: <cause>` (`FunctionLoadError`). A package that is not
installed is `MissingPackageError`, naming the importing file and the package and saying to
run `npm install`. Each function is bundled with a source map into a temporary `.mjs` file
- **Errors name the user's file.** A function that fails to bundle or load is logged as
`Could not load functions/<file>.js: <cause>` (`FunctionLoadError`), when serve starts and on
each request to its route. That route answers a bare 502 and every other function keeps
serving, as on AWS, where each deployed function is its own Lambda (CL-8970). Azure and GCP
(V1) run every function in one server, which fails to start, so every route answers 500 CF001.
A package that is not installed still stops serve: it is `MissingPackageError`, naming the
importing file and the package and saying to run `npm install`. Each function is bundled with a source map into a temporary `.mjs` file
and imported by file URL, not from a `data:` URL, and serve enables Node's source-map support,
so a handler's stack trace points at `functions/<file>.js:<line>`.
- **A busy port** raises `PortInUseError` and exits 2 with a clean message (V1 crashed on an
Expand Down
109 changes: 81 additions & 28 deletions src/functions/cloud-functions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1989,6 +1989,17 @@ describe('isOutsideDirectory', () => {
});

describe('CloudFunctions serve failures', () => {
const serveWithLoadFailure = async (file: string, source: string, route: string): Promise<{ status: number; logged: string }> => {
const errorSpy = jest.spyOn(console, 'error').mockImplementation(() => undefined);
writeFunctionFile(file, source);
const port = await freePort();

await new CloudFunctions(workspace).serve(port);
const { status } = await sendRequest(port, route);

return { status, logged: errorSpy.mock.calls.map(([message]) => String(message)).join('\n') };
};

it('rejects with the validation error the validator raised', async () => {
writeFunctionFile('[id].js', 'export default function top(request, response) { response.send("top"); }');

Expand All @@ -1998,20 +2009,63 @@ describe('CloudFunctions serve failures', () => {
expect(startedServers).toHaveLength(0);
});

it('gives the file, line and column of a syntax error', async () => {
writeFunctionFile('syn.js', ['export default function syn() {', ' const = 1;', '}'].join('\n'));
it('serves the other functions when one throws while loading, and answers its route with a bare 502, as each deployed function is its own Lambda', async () => {
const errorSpy = jest.spyOn(console, 'error').mockImplementation(() => undefined);
writeFunctionFile('ok.js', 'export default function ok(request, response) { response.send("ok"); }');
writeFunctionFile('broken.js', 'throw new Error("not configured"); export default function broken(request, response) { response.send("never"); }');
const port = await freePort();

await expect(new CloudFunctions(workspace).serve(await freePort())).rejects.toThrow(
`(${join('functions', 'syn.js')}:2:`,
);
await new CloudFunctions(workspace).serve(port);
const ok = await sendRequest(port, '/ok');
const broken = await sendRequest(port, '/broken');

expect([ok.status, ok.body]).toEqual([200, 'ok']);
expect([broken.status, broken.body]).toEqual([502, '']);
expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining(`Could not load ${join('functions', 'broken.js')}: not configured`));
});

it('logs why a route answers 502 when serve starts and again on each request to it', async () => {
const errorSpy = jest.spyOn(console, 'error').mockImplementation(() => undefined);
const reason = `Could not load ${join('functions', 'broken.js')}: not configured`;
writeFunctionFile('broken.js', 'throw new Error("not configured"); export default function broken() {}');
const port = await freePort();

await new CloudFunctions(workspace).serve(port);
const atStart = errorSpy.mock.calls.filter(([message]) => String(message).startsWith(reason)).length;
await sendRequest(port, '/broken');
await sendRequest(port, '/broken');
const afterTwoRequests = errorSpy.mock.calls.filter(([message]) => String(message).startsWith(reason)).length;

expect([atStart, afterTwoRequests]).toEqual([1, 3]);
});

it('answers a 502 on a dynamic route whose function fails to load, keeping its path parameter', async () => {
jest.spyOn(console, 'error').mockImplementation(() => undefined);
writeFunctionFile(join('items', '[id].js'), 'throw new Error("not configured"); export default function item() {}');
writeFunctionFile(join('items', 'list.js'), 'export default function list(request, response) { response.send("list"); }');
const port = await freePort();

await new CloudFunctions(workspace).serve(port);

expect((await sendRequest(port, '/items/abc')).status).toBe(502);
expect((await sendRequest(port, '/items/list')).body).toBe('list');
});

it('gives the file, line and column where a function throws while loading', async () => {
writeFunctionFile('te.js', ['const cfg = undefined;', 'const value = cfg.value;', 'export default function te() {}'].join('\n'));
it('logs the file, line and column of a syntax error and answers that route with a 502', async () => {
const failure = await serveWithLoadFailure('syn.js', ['export default function syn() {', ' const = 1;', '}'].join('\n'), '/syn');

await expect(new CloudFunctions(workspace).serve(await freePort())).rejects.toThrow(
`(${join('functions', 'te.js')}:2:`,
expect(failure.status).toBe(502);
expect(failure.logged).toContain(`(${join('functions', 'syn.js')}:2:`);
});

it('logs the file, line and column where a function throws while loading', async () => {
const failure = await serveWithLoadFailure(
'te.js',
['const cfg = undefined;', 'const value = cfg.value;', 'export default function te() {}'].join('\n'),
'/te',
);

expect(failure.logged).toContain(`(${join('functions', 'te.js')}:2:`);
});

it('gives no location rather than a realpath error when the bundler reports a virtual module', () => {
Expand All @@ -2021,29 +2075,23 @@ describe('CloudFunctions serve failures', () => {
});

it('keeps a thrown non-error value in the load failure message', async () => {
writeFunctionFile('str.js', 'throw "plain string"; export default function str() {}');
const failure = await serveWithLoadFailure('str.js', 'throw "plain string"; export default function str() {}', '/str');

await expect(new CloudFunctions(workspace).serve(await freePort())).rejects.toThrow(
`Could not load ${join('functions', 'str.js')}: plain string`,
);
expect(failure.logged).toContain(`Could not load ${join('functions', 'str.js')}: plain string`);
});

it('names the function file when it cannot be bundled', async () => {
writeFunctionFile('syntax-error.js', 'export default function ( {');
it('names the function file when it cannot be bundled and answers its route with a 502', async () => {
const failure = await serveWithLoadFailure('syntax-error.js', 'export default function ( {', '/syntax-error');

await expect(new CloudFunctions(workspace).serve(await freePort())).rejects.toThrow(
`Could not load ${join('functions', 'syntax-error.js')}: `,
);
expect(startedServers).toHaveLength(0);
expect(failure.status).toBe(502);
expect(failure.logged).toContain(`Could not load ${join('functions', 'syntax-error.js')}: `);
});

it('names the function file when it throws while loading', async () => {
writeFunctionFile(join('api', 'boom.js'), 'throw new Error("init"); export default function boom() {}');
it('names the function file when it throws while loading and answers its nested route with a 502', async () => {
const failure = await serveWithLoadFailure(join('api', 'boom.js'), 'throw new Error("init"); export default function boom() {}', '/api/boom');

await expect(new CloudFunctions(workspace).serve(await freePort())).rejects.toThrow(
`Could not load ${join('functions', 'api', 'boom.js')}: init`,
);
expect(startedServers).toHaveLength(0);
expect(failure.status).toBe(502);
expect(failure.logged).toContain(`Could not load ${join('functions', 'api', 'boom.js')}: init`);
});

it('names the package and the file importing it when a package is not installed, without a bundler warning', async () => {
Expand Down Expand Up @@ -2105,10 +2153,15 @@ describe('CloudFunctions serve failures', () => {
expect(JSON.parse(response.body)).toEqual({ hasPeer: false });
});

it('rejects when a function file imports a module that cannot be resolved', async () => {
writeFunctionFile('missing-import.js', 'import missing from "../util/cloud-function/not-here.js"; export default missing;');
it('answers a 502 on the route of a function file that imports a module that cannot be resolved', async () => {
const failure = await serveWithLoadFailure(
'missing-import.js',
'import missing from "../util/cloud-function/not-here.js"; export default missing;',
'/missing-import',
);

await expect(new CloudFunctions(workspace).serve(await freePort())).rejects.toThrow();
expect(failure.status).toBe(502);
expect(failure.logged).toContain(`Could not load ${join('functions', 'missing-import.js')}: `);
});

it('refuses with a port-in-use error rather than an unhandled error event', async () => {
Expand Down
15 changes: 14 additions & 1 deletion src/functions/cloud-functions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -381,6 +381,19 @@ function endLikeDeployedFunctions(response: Response, answering: Answering): voi
}
}

/**
* Each deployed function is its own Lambda, so a file that fails to load fails only its own route, with a 502, and
* every other function keeps serving. Serve logs why at startup and on each request to that route.
*/
function answerFailedLoad(failure: FunctionLoadError): CloudFunctionHandler {
console.error(failure.message);
const answer = (_request: Request, response: Response): void => {
console.error(failure.message);
response.status(502).end();
};
return answer as CloudFunctionHandler;
}

export function answerNotFound(_request: Request, response: Response): void {
response.status(404).end();
}
Expand Down Expand Up @@ -665,7 +678,7 @@ export class CloudFunctions {
throw cause;
}

throw new FunctionLoadError(functionFile, cause, this.sourceLocation(cause));
return answerFailedLoad(new FunctionLoadError(functionFile, cause, this.sourceLocation(cause)));
});
if (!handler) {
continue;
Expand Down
Loading