Skip to content

Commit 118747d

Browse files
Introduce internal isWorkerNotFoundError utility and avoid worker-not-found error code magic numbers in wrangler
1 parent 59534ba commit 118747d

File tree

9 files changed

+57
-32
lines changed

9 files changed

+57
-32
lines changed

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 { http, HttpResponse } from "msw";
55
import * as TOML from "smol-toml";
66
import { afterEach, beforeEach, describe, expect, it, 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";
@@ -53,8 +57,8 @@ function mockNoWorkerFound(isBulk = false) {
5357
return HttpResponse.json(
5458
createFetchResult(null, false, [
5559
{
56-
code: 10007,
57-
message: "This Worker does not exist on your account.",
60+
code: WORKER_NOT_FOUND_ERR_CODE,
61+
message: workerNotFoundErrorMessage,
5862
},
5963
])
6064
);
@@ -70,8 +74,8 @@ function mockNoWorkerFound(isBulk = false) {
7074
return HttpResponse.json(
7175
createFetchResult(null, false, [
7276
{
73-
code: 10007,
74-
message: "This Worker does not exist on your account.",
77+
code: WORKER_NOT_FOUND_ERR_CODE,
78+
message: workerNotFoundErrorMessage,
7579
},
7680
])
7781
);

packages/wrangler/src/deploy/deploy.ts

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,7 @@ import { downloadWorkerConfig } from "../utils/download-worker-config";
6363
import { helpIfErrorIsSizeOrScriptStartup } from "../utils/friendly-validator-errors";
6464
import { printBindings } from "../utils/print-bindings";
6565
import { retryOnAPIFailure } from "../utils/retry";
66+
import { isWorkerNotFoundError } from "../utils/worker-not-found-error";
6667
import {
6768
createDeployment,
6869
patchNonVersionedScriptSettings,
@@ -463,12 +464,10 @@ export default async function deploy(props: Props): Promise<{
463464
}
464465
}
465466
} catch (e) {
466-
// code: 10090, message: workers.api.error.service_not_found
467-
// is thrown from the above fetchResult on the first deploy of a Worker
468-
if ((e as { code?: number }).code !== 10090) {
469-
throw e;
470-
} else {
467+
if (isWorkerNotFoundError(e)) {
471468
workerExists = false;
469+
} else {
470+
throw e;
472471
}
473472
}
474473
}

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 { configFileName } from "@cloudflare/workers-utils";
33
import { fetchResult } from "./cfetch";
44
import { logger } from "./logger";
5+
import { isWorkerNotFoundError } from "./utils/worker-not-found-error";
56
import type { CfWorkerInit, Config } from "@cloudflare/workers-utils";
67

78
/**
@@ -111,10 +112,8 @@ export async function getMigrationsToUpload(
111112

112113
const suppressNotFoundError = (err: unknown) => {
113114
if (
114-
![
115-
10090, // corresponds to workers.api.error.service_not_found, so the script wasn't previously published at all
116-
10092, // workers.api.error.environment_not_found, so the script wasn't published to this environment yet
117-
].includes((err as { code: number }).code)
115+
!isWorkerNotFoundError(err) &&
116+
(err as { code: number }).code !== 10092 // workers.api.error.environment_not_found, so the script wasn't published to this environment yet
118117
) {
119118
throw err;
120119
}

packages/wrangler/src/init.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import { requireAuth } from "./user";
1717
import { createBatches } from "./utils/create-batches";
1818
import { downloadWorkerConfig } from "./utils/download-worker-config";
1919
import * as shellquote from "./utils/shell-quote";
20+
import { isWorkerNotFoundError } from "./utils/worker-not-found-error";
2021
import type { PackageManager } from "./package-manager";
2122
import type { ServiceMetadataRes } from "@cloudflare/workers-utils";
2223
import type { ReadableStream } from "node:stream/web";
@@ -83,7 +84,7 @@ export const init = createCommand({
8384
`/accounts/${accountId}/workers/services/${args.fromDash}`
8485
);
8586
} catch (err) {
86-
if ((err as { code?: number }).code === 10090) {
87+
if (isWorkerNotFoundError(err)) {
8788
throw new UserError(
8889
"wrangler couldn't find a Worker with that name in your account.\nRun `wrangler whoami` to confirm you're logged into the correct account.",
8990
{

packages/wrangler/src/match-tag.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import {
88
import { fetchResult } from "./cfetch";
99
import { logger } from "./logger";
1010
import { getCloudflareAccountIdFromEnv } from "./user/auth-variables";
11+
import { isWorkerNotFoundError } from "./utils/worker-not-found-error";
1112
import type {
1213
ComplianceConfig,
1314
ServiceMetadataRes,
@@ -52,8 +53,7 @@ export async function verifyWorkerMatchesCITag(
5253
logger.debug(`API returned with tag: ${tag} for worker: ${workerName}`);
5354
} catch (e) {
5455
logger.debug(e);
55-
// code: 10090, message: workers.api.error.service_not_found
56-
if ((e as { code?: number }).code === 10090) {
56+
if (isWorkerNotFoundError(e)) {
5757
throw new FatalError(
5858
`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.`
5959
);

packages/wrangler/src/secret/index.ts

Lines changed: 3 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import { fetchSecrets } from "../utils/fetch-secrets";
2121
import { getLegacyScriptName } from "../utils/getLegacyScriptName";
2222
import { readFromStdin, trimTrailingWhitespace } from "../utils/std";
2323
import { useServiceEnvironments } from "../utils/useServiceEnvironments";
24+
import { isWorkerNotFoundError } from "../utils/worker-not-found-error";
2425
import type { Config, WorkerMetadataBinding } from "@cloudflare/workers-utils";
2526

2627
export const VERSION_NOT_DEPLOYED_ERR_CODE = 10215;
@@ -38,14 +39,6 @@ type InheritBindingUpload = {
3839

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

41-
function isMissingWorkerError(e: unknown): e is { code: 10007 } {
42-
return (
43-
typeof e === "object" &&
44-
e !== null &&
45-
(e as { code: number }).code === 10007
46-
);
47-
}
48-
4942
async function createDraftWorker({
5043
config,
5144
args,
@@ -239,7 +232,7 @@ export const secretPutCommand = createCommand({
239232
sendMetrics: config.send_metrics,
240233
});
241234
} catch (e) {
242-
if (isMissingWorkerError(e)) {
235+
if (isWorkerNotFoundError(e)) {
243236
// create a draft worker and try again
244237
const result = await createDraftWorker({
245238
config,
@@ -486,7 +479,7 @@ export const secretBulkCommand = createCommand({
486479
const settings = await getSettings();
487480
existingBindings = settings.bindings;
488481
} catch (e) {
489-
if (isMissingWorkerError(e)) {
482+
if (isWorkerNotFoundError(e)) {
490483
// create a draft worker before patching
491484
const result = await createDraftWorker({
492485
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: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,14 +7,15 @@ import {
77
leftT,
88
spinnerWhile,
99
} from "@cloudflare/cli/interactive";
10-
import { APIError, UserError } from "@cloudflare/workers-utils";
10+
import { UserError } from "@cloudflare/workers-utils";
1111
import { fetchResult } from "../cfetch";
1212
import { createCommand } from "../core/create-command";
1313
import { isNonInteractiveOrCI } from "../is-interactive";
1414
import * as metrics from "../metrics";
1515
import { writeOutput } from "../output";
1616
import { requireAuth } from "../user";
1717
import formatLabelledValues from "../utils/render-labelled-values";
18+
import { isWorkerNotFoundError } from "../utils/worker-not-found-error";
1819
import {
1920
createDeployment,
2021
fetchDeployableVersions,
@@ -263,8 +264,7 @@ export async function confirmLatestDeploymentOverwrite(
263264
});
264265
}
265266
} catch (e) {
266-
const isNotFound = e instanceof APIError && e.code == 10007;
267-
if (!isNotFound) {
267+
if (!isWorkerNotFoundError(e)) {
268268
throw e;
269269
}
270270
}

packages/wrangler/src/versions/upload.ts

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,7 @@ import { getScriptName } from "../utils/getScriptName";
6464
import { printBindings } from "../utils/print-bindings";
6565
import { retryOnAPIFailure } from "../utils/retry";
6666
import { useServiceEnvironments } from "../utils/useServiceEnvironments";
67+
import { isWorkerNotFoundError } from "../utils/worker-not-found-error";
6768
import { patchNonVersionedScriptSettings } from "./api";
6869
import type { AssetsOptions } from "../assets";
6970
import type { Entry } from "../deployment-bundle/entry";
@@ -463,9 +464,7 @@ export default async function versionsUpload(props: Props): Promise<{
463464
}
464465
}
465466
} catch (e) {
466-
// code: 10090, message: workers.api.error.service_not_found
467-
// is thrown from the above fetchResult on the first deploy of a Worker
468-
if ((e as { code?: number }).code !== 10090) {
467+
if (!isWorkerNotFoundError(e)) {
469468
throw e;
470469
}
471470
}

0 commit comments

Comments
 (0)