Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Error if the user is trying to implement DO's in a service worker #640

Merged
merged 4 commits into from
Mar 22, 2022
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
8 changes: 8 additions & 0 deletions .changeset/tender-planes-tie.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
"wrangler": patch
---

Error if the user is trying to implement DO's in a service worker

Durable Objects can only be implemented in Module Workers, so we should throw if we detect that
the user is trying to implement a Durable Object but their worker is in Service Worker format.
126 changes: 126 additions & 0 deletions packages/wrangler/src/__tests__/publish.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2045,6 +2045,132 @@ export default{
});
});

describe("durable object bindings", () => {
it("should support durable object bindings", async () => {
writeWranglerToml({
durable_objects: {
bindings: [
{ name: "EXAMPLE_DO_BINDING", class_name: "ExampleDurableObject" },
],
},
});
writeWorkerSource({ type: "esm" });
mockSubDomainRequest();
mockUploadWorkerRequest({
expectedBindings: [
{
class_name: "ExampleDurableObject",
name: "EXAMPLE_DO_BINDING",
type: "durable_object_namespace",
},
],
});

await runWrangler("publish index.js");
expect(std.out).toMatchInlineSnapshot(`
"Uploaded test-name (TIMINGS)
Published test-name (TIMINGS)
test-name.test-sub-domain.workers.dev"
`);
expect(std.err).toMatchInlineSnapshot(`""`);
expect(std.warn).toMatchInlineSnapshot(`""`);
});

it("should support service-workers binding to external durable objects", async () => {
writeWranglerToml({
durable_objects: {
bindings: [
{
name: "EXAMPLE_DO_BINDING",
class_name: "ExampleDurableObject",
script_name: "example-do-binding-worker",
},
],
},
});
writeWorkerSource({ type: "sw" });
mockSubDomainRequest();
mockUploadWorkerRequest({
expectedType: "sw",
expectedBindings: [
{
name: "EXAMPLE_DO_BINDING",
class_name: "ExampleDurableObject",
script_name: "example-do-binding-worker",
type: "durable_object_namespace",
},
],
});

await runWrangler("publish index.js");
expect(std.out).toMatchInlineSnapshot(`
"Uploaded test-name (TIMINGS)
Published test-name (TIMINGS)
test-name.test-sub-domain.workers.dev"
`);
expect(std.err).toMatchInlineSnapshot(`""`);
expect(std.warn).toMatchInlineSnapshot(`""`);
});

it("should support module workers implementing durable objects", async () => {
writeWranglerToml({
durable_objects: {
bindings: [
{
name: "EXAMPLE_DO_BINDING",
class_name: "ExampleDurableObject",
},
],
},
});
writeWorkerSource({ type: "esm" });
mockSubDomainRequest();
mockUploadWorkerRequest({
expectedType: "esm",
expectedBindings: [
{
name: "EXAMPLE_DO_BINDING",
class_name: "ExampleDurableObject",
type: "durable_object_namespace",
},
],
});

await runWrangler("publish index.js");
expect(std.out).toMatchInlineSnapshot(`
"Uploaded test-name (TIMINGS)
Published test-name (TIMINGS)
test-name.test-sub-domain.workers.dev"
`);
expect(std.err).toMatchInlineSnapshot(`""`);
expect(std.warn).toMatchInlineSnapshot(`""`);
});

it("should error when detecting service workers implementing durable objects", async () => {
writeWranglerToml({
durable_objects: {
bindings: [
{
name: "EXAMPLE_DO_BINDING",
class_name: "ExampleDurableObject",
},
],
},
});
writeWorkerSource({ type: "sw" });
mockSubDomainRequest();

await expect(runWrangler("publish index.js")).rejects
.toThrowErrorMatchingInlineSnapshot(`
"You seem to be trying to use Durable Objects in a Worker written with Service Worker syntax.
You can use Durable Objects defined in other Workers by specifying a \`script_name\` in your wrangler.toml, where \`script_name\` is the name of the Worker that implements that Durable Object. For example:
{ name = EXAMPLE_DO_BINDING, class_name = ExampleDurableObject } ==> { name = EXAMPLE_DO_BINDING, class_name = ExampleDurableObject, script_name = example-do-binding-worker }
Alternatively, migrate your worker to ES Module syntax to implement a Durable Object in this Worker:
https://developers.cloudflare.com/workers/learning/migrating-to-module-workers/"
`);
});
});

describe("unsafe bindings", () => {
it("should warn if using unsafe bindings", async () => {
writeWranglerToml({
Expand Down
64 changes: 64 additions & 0 deletions packages/wrangler/src/entry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,22 @@ export async function getEntry(
directory,
args.format ?? config.build?.upload?.format
);

if (format === "service-worker" && hasDurableObjectImplementations(config)) {
const errorMessage =
"You seem to be trying to use Durable Objects in a Worker written with Service Worker syntax.";
const addScriptName =
"You can use Durable Objects defined in other Workers by specifying a `script_name` in your wrangler.toml, where `script_name` is the name of the Worker that implements that Durable Object. For example:";
const addScriptNameExamples = generateAddScriptNameExamples(config);
const migrateText =
"Alternatively, migrate your worker to ES Module syntax to implement a Durable Object in this Worker:";
const migrateUrl =
"https://developers.cloudflare.com/workers/learning/migrating-to-module-workers/";
throw new Error(
`${errorMessage}\n${addScriptName}\n${addScriptNameExamples}\n${migrateText}\n${migrateUrl}`
);
}

return { file, directory, format };
}

Expand Down Expand Up @@ -157,3 +173,51 @@ export function fileExists(filePath: string): boolean {
}
return false;
}

/**
* Returns true if the given config contains Durable Object bindings that are implemented
* in this worker instead of being implemented elsewhere, and bound via a `script_name`
* property in wrangler.toml
*/
function hasDurableObjectImplementations(config: Config): boolean {
const allBindings = getDurableObjectBindings(config);

return allBindings.some((binding) => binding.script_name === undefined);
}

/**
* Generates some help text based on the Durable Object bindings in a given
* config indicating how the user can add a `script_name` field to bind an
* externally defined Durable Object.
*/
function generateAddScriptNameExamples(config: Config): string {
const allBindings = getDurableObjectBindings(config);

function exampleScriptName(binding_name: string): string {
return `${binding_name.toLowerCase().replaceAll("_", "-")}-worker`;
}

return allBindings
.filter((binding) => binding.script_name === undefined)
.map(({ name, class_name }) => {
const script_name = exampleScriptName(name);
const currentBinding = `{ name = ${name}, class_name = ${class_name} }`;
const fixedBinding = `{ name = ${name}, class_name = ${class_name}, script_name = ${script_name} }`;

return `${currentBinding} ==> ${fixedBinding}`;
})
.join("\n");
}

/**
* Get the Durable Object bindings in a given config, including those
* specified in different environments
*/
function getDurableObjectBindings(config: Config) {
return [
...config.durable_objects.bindings,
...Object.values(config.env)
.map((env) => env.durable_objects.bindings)
.flat(),
];
}