Skip to content

Commit 4b18c6f

Browse files
Introduce internal isWorkerNotFoundError utility and avoid worker-not-found error code magic numbers in wrangler (#11519)
1 parent ed8aaef commit 4b18c6f

9 files changed

Lines changed: 56 additions & 32 deletions

File tree

packages/wrangler/src/__tests__/secret.test.ts

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,10 @@ import * as TOML from "@iarna/toml";
55
import { http, HttpResponse } from "msw";
66
import { vi } from "vitest";
77
import { VERSION_NOT_DEPLOYED_ERR_CODE } from "../secret";
8+
import {
9+
WORKER_NOT_FOUND_ERR_CODE,
10+
workerNotFoundErrorMessage,
11+
} from "../utils/worker-not-found-error";
812
import { mockAccountId, mockApiToken } from "./helpers/mock-account-id";
913
import { mockConsoleMethods } from "./helpers/mock-console";
1014
import { clearDialogs, mockConfirm, mockPrompt } from "./helpers/mock-dialogs";
@@ -52,8 +56,8 @@ function mockNoWorkerFound(isBulk = false) {
5256
return HttpResponse.json(
5357
createFetchResult(null, false, [
5458
{
55-
code: 10007,
56-
message: "This Worker does not exist on your account.",
59+
code: WORKER_NOT_FOUND_ERR_CODE,
60+
message: workerNotFoundErrorMessage,
5761
},
5862
])
5963
);
@@ -69,8 +73,8 @@ function mockNoWorkerFound(isBulk = false) {
6973
return HttpResponse.json(
7074
createFetchResult(null, false, [
7175
{
72-
code: 10007,
73-
message: "This Worker does not exist on your account.",
76+
code: WORKER_NOT_FOUND_ERR_CODE,
77+
message: workerNotFoundErrorMessage,
7478
},
7579
])
7680
);

packages/wrangler/src/deploy/deploy.ts

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ import triggersDeploy from "../triggers/deploy";
4545
import { helpIfErrorIsSizeOrScriptStartup } from "../utils/friendly-validator-errors";
4646
import { printBindings } from "../utils/print-bindings";
4747
import { retryOnAPIFailure } from "../utils/retry";
48+
import { isWorkerNotFoundError } from "../utils/worker-not-found-error";
4849
import {
4950
createDeployment,
5051
patchNonVersionedScriptSettings,
@@ -377,12 +378,10 @@ export default async function deploy(props: Props): Promise<{
377378
}
378379
}
379380
} catch (e) {
380-
// code: 10090, message: workers.api.error.service_not_found
381-
// is thrown from the above fetchResult on the first deploy of a Worker
382-
if ((e as { code?: number }).code !== 10090) {
383-
throw e;
384-
} else {
381+
if (isWorkerNotFoundError(e)) {
385382
workerExists = false;
383+
} else {
384+
throw e;
386385
}
387386
}
388387
}

packages/wrangler/src/durable.ts

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import assert from "node:assert";
22
import { fetchResult } from "./cfetch";
33
import { configFileName } from "./config";
44
import { logger } from "./logger";
5+
import { isWorkerNotFoundError } from "./utils/worker-not-found-error";
56
import type { Config } from "./config";
67
import type { CfWorkerInit } from "./deployment-bundle/worker";
78

@@ -108,10 +109,8 @@ export async function getMigrationsToUpload(
108109

109110
const suppressNotFoundError = (err: unknown) => {
110111
if (
111-
![
112-
10090, // corresponds to workers.api.error.service_not_found, so the script wasn't previously published at all
113-
10092, // workers.api.error.environment_not_found, so the script wasn't published to this environment yet
114-
].includes((err as { code: number }).code)
112+
!isWorkerNotFoundError(err) &&
113+
(err as { code: number }).code !== 10092 // workers.api.error.environment_not_found, so the script wasn't published to this environment yet
115114
) {
116115
throw err;
117116
}

packages/wrangler/src/init.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import { getBasePath } from "./paths";
2222
import { requireAuth } from "./user";
2323
import { createBatches } from "./utils/create-batches";
2424
import * as shellquote from "./utils/shell-quote";
25+
import { isWorkerNotFoundError } from "./utils/worker-not-found-error";
2526
import { printWranglerBanner } from "./wrangler-banner";
2627
import type { RawConfig } from "./config";
2728
import type {
@@ -226,7 +227,7 @@ export async function initHandler(args: InitArgs) {
226227
`/accounts/${accountId}/workers/services/${fromDashWorkerName}`
227228
);
228229
} catch (err) {
229-
if ((err as { code?: number }).code === 10090) {
230+
if (isWorkerNotFoundError(err)) {
230231
throw new UserError(
231232
"wrangler couldn't find a Worker script with that name in your account.\nRun `wrangler whoami` to confirm you're logged into the correct account."
232233
);

packages/wrangler/src/match-tag.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { getCIMatchTag } from "./environment-variables/misc-variables";
44
import { FatalError } from "./errors";
55
import { logger } from "./logger";
66
import { getCloudflareAccountIdFromEnv } from "./user/auth-variables";
7+
import { isWorkerNotFoundError } from "./utils/worker-not-found-error";
78
import type { ServiceMetadataRes } from "./init";
89

910
export async function verifyWorkerMatchesCITag(
@@ -43,8 +44,7 @@ export async function verifyWorkerMatchesCITag(
4344
logger.debug(`API returned with tag: ${tag} for worker: ${workerName}`);
4445
} catch (e) {
4546
logger.debug(e);
46-
// code: 10090, message: workers.api.error.service_not_found
47-
if ((e as { code?: number }).code === 10090) {
47+
if (isWorkerNotFoundError(e)) {
4848
throw new FatalError(
4949
`The name in your ${configFileName(configPath)} file (${workerName}) must match the name of your Worker. Please update the name field in your ${configFileName(configPath)} file.`
5050
);

packages/wrangler/src/secret/index.ts

Lines changed: 3 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import { requireAuth } from "../user";
1919
import { getLegacyScriptName } from "../utils/getLegacyScriptName";
2020
import { isLegacyEnv } from "../utils/isLegacyEnv";
2121
import { readFromStdin, trimTrailingWhitespace } from "../utils/std";
22+
import { isWorkerNotFoundError } from "../utils/worker-not-found-error";
2223
import type { Config } from "../config";
2324
import type { WorkerMetadataBinding } from "../deployment-bundle/create-worker-upload-form";
2425

@@ -37,14 +38,6 @@ type InheritBindingUpload = {
3738

3839
type SecretBindingRedacted = Omit<SecretBindingUpload, "text">;
3940

40-
function isMissingWorkerError(e: unknown): e is { code: 10007 } {
41-
return (
42-
typeof e === "object" &&
43-
e !== null &&
44-
(e as { code: number }).code === 10007
45-
);
46-
}
47-
4841
async function createDraftWorker({
4942
config,
5043
args,
@@ -227,7 +220,7 @@ export const secretPutCommand = createCommand({
227220
sendMetrics: config.send_metrics,
228221
});
229222
} catch (e) {
230-
if (isMissingWorkerError(e)) {
223+
if (isWorkerNotFoundError(e)) {
231224
// create a draft worker and try again
232225
const result = await createDraftWorker({
233226
config,
@@ -474,7 +467,7 @@ export const secretBulkCommand = createCommand({
474467
const settings = await getSettings();
475468
existingBindings = settings.bindings;
476469
} catch (e) {
477-
if (isMissingWorkerError(e)) {
470+
if (isWorkerNotFoundError(e)) {
478471
// create a draft worker before patching
479472
const result = await createDraftWorker({
480473
config,
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/**
2+
This is the error code from the Cloudflare API signaling that a worker could not be found on the target account
3+
*/
4+
export const WORKER_NOT_FOUND_ERR_CODE = 10007 as const;
5+
6+
/**
7+
This is the error code from the Cloudflare API signaling that a worker environment (legacy) could not be found on the target account
8+
*/
9+
export const WORKER_LEGACY_ENVIRONMENT_NOT_FOUND_ERR_CODE = 10090 as const;
10+
11+
/**
12+
This is the error message from the Cloudflare API signaling that a worker could not be found on the target account
13+
*/
14+
export const workerNotFoundErrorMessage =
15+
"This Worker does not exist on your account.";
16+
17+
/**
18+
* Given an error from the Cloudflare API discerns wether it is caused by a worker that could not be found on the target account
19+
*
20+
* @param error The error object
21+
* @returns true is the object represents an error from the Cloudflare API caused by a not found worker, false otherwise
22+
*/
23+
export function isWorkerNotFoundError(error: unknown): boolean {
24+
return (
25+
error instanceof Object &&
26+
"code" in error &&
27+
(error.code === WORKER_NOT_FOUND_ERR_CODE ||
28+
error.code === WORKER_LEGACY_ENVIRONMENT_NOT_FOUND_ERR_CODE)
29+
);
30+
}

packages/wrangler/src/versions/deploy.ts

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,9 @@ import { isNonInteractiveOrCI } from "../is-interactive";
1414
import { logger } from "../logger";
1515
import * as metrics from "../metrics";
1616
import { writeOutput } from "../output";
17-
import { APIError } from "../parse";
1817
import { requireAuth } from "../user";
1918
import formatLabelledValues from "../utils/render-labelled-values";
19+
import { isWorkerNotFoundError } from "../utils/worker-not-found-error";
2020
import {
2121
createDeployment,
2222
fetchDeployableVersions,
@@ -268,8 +268,7 @@ export async function confirmLatestDeploymentOverwrite(
268268
});
269269
}
270270
} catch (e) {
271-
const isNotFound = e instanceof APIError && e.code == 10007;
272-
if (!isNotFound) {
271+
if (!isWorkerNotFoundError(e)) {
273272
throw e;
274273
}
275274
}

packages/wrangler/src/versions/upload.ts

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ import { getScriptName } from "../utils/getScriptName";
5050
import { isLegacyEnv } from "../utils/isLegacyEnv";
5151
import { printBindings } from "../utils/print-bindings";
5252
import { retryOnAPIFailure } from "../utils/retry";
53+
import { isWorkerNotFoundError } from "../utils/worker-not-found-error";
5354
import type { AssetsOptions } from "../assets";
5455
import type { Config } from "../config";
5556
import type { Entry } from "../deployment-bundle/entry";
@@ -451,9 +452,7 @@ export default async function versionsUpload(props: Props): Promise<{
451452
}
452453
}
453454
} catch (e) {
454-
// code: 10090, message: workers.api.error.service_not_found
455-
// is thrown from the above fetchResult on the first deploy of a Worker
456-
if ((e as { code?: number }).code !== 10090) {
455+
if (!isWorkerNotFoundError(e)) {
457456
throw e;
458457
}
459458
}

0 commit comments

Comments
 (0)