cf-orbs 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/NOTICE +11 -0
- package/README.md +275 -2
- package/bin/cf-orbs.js +14 -0
- package/dist/api.js +124 -0
- package/dist/args.js +77 -0
- package/dist/commands/bench.js +6 -0
- package/dist/commands/deploy.js +183 -0
- package/dist/commands/doctor.js +159 -0
- package/dist/commands/init.js +466 -0
- package/dist/commands/logs.js +42 -0
- package/dist/commands/snapshots.js +306 -0
- package/dist/commands/status.js +215 -0
- package/dist/commands/uninstall.js +96 -0
- package/dist/commands/upgrade.js +108 -0
- package/dist/config.js +460 -0
- package/dist/connect.js +19 -0
- package/dist/context.js +16 -0
- package/dist/errors.js +35 -0
- package/dist/index.js +197 -0
- package/dist/probes.js +21 -0
- package/dist/project.js +215 -0
- package/dist/subdomain.js +81 -0
- package/dist/ui.js +113 -0
- package/dist/wrangler-template.js +69 -0
- package/dist/wrangler.js +169 -0
- package/package.json +40 -4
- package/templates/cf-orbs.config.example.jsonc +56 -0
- package/templates/dispatch/README.md +69 -0
- package/templates/dispatch/dispatch.sh +438 -0
- package/templates/image/Dockerfile +34 -0
- package/templates/image/README.md +83 -0
- package/templates/provider/Dockerfile +25 -0
- package/templates/provider/README.md +134 -0
- package/templates/provider/entry.sh +116 -0
- package/templates/worker/src/api.ts +532 -0
- package/templates/worker/src/core/config.ts +149 -0
- package/templates/worker/src/core/container-port.ts +137 -0
- package/templates/worker/src/core/registry-core.ts +635 -0
- package/templates/worker/src/core/types.ts +263 -0
- package/templates/worker/src/env.ts +26 -0
- package/templates/worker/src/index.ts +29 -0
- package/templates/worker/src/orb/alarm.ts +318 -0
- package/templates/worker/src/orb/bench.ts +129 -0
- package/templates/worker/src/orb/context.ts +16 -0
- package/templates/worker/src/orb/delete.ts +33 -0
- package/templates/worker/src/orb/exclusive.ts +22 -0
- package/templates/worker/src/orb/images.ts +47 -0
- package/templates/worker/src/orb/journal.ts +203 -0
- package/templates/worker/src/orb/pause.ts +269 -0
- package/templates/worker/src/orb/prewarm.ts +122 -0
- package/templates/worker/src/orb/scripts.ts +544 -0
- package/templates/worker/src/orb/session.ts +557 -0
- package/templates/worker/src/orb/spawn.ts +697 -0
- package/templates/worker/src/provider-restart.ts +73 -0
- package/templates/worker/src/provider.ts +487 -0
- package/templates/worker/src/registry.ts +136 -0
package/dist/args.js
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
// Small argv parser. Supports --flag, --flag=value, --flag value, --no-flag, -h, and "--" to end flags.
|
|
2
|
+
import { CliError } from "./errors.js";
|
|
3
|
+
export function parseArgs(argv, spec) {
|
|
4
|
+
const flags = {};
|
|
5
|
+
const positionals = [];
|
|
6
|
+
const byShort = new Map();
|
|
7
|
+
for (const [name, s] of Object.entries(spec))
|
|
8
|
+
if (s.short)
|
|
9
|
+
byShort.set(s.short, name);
|
|
10
|
+
for (let i = 0; i < argv.length; i++) {
|
|
11
|
+
const a = argv[i];
|
|
12
|
+
if (a === "--") {
|
|
13
|
+
positionals.push(...argv.slice(i + 1));
|
|
14
|
+
break;
|
|
15
|
+
}
|
|
16
|
+
if (a.startsWith("--")) {
|
|
17
|
+
const eq = a.indexOf("=");
|
|
18
|
+
let name = eq === -1 ? a.slice(2) : a.slice(2, eq);
|
|
19
|
+
let inline = eq === -1 ? undefined : a.slice(eq + 1);
|
|
20
|
+
let negated = false;
|
|
21
|
+
if (!spec[name] && name.startsWith("no-") && spec[name.slice(3)]?.type === "boolean") {
|
|
22
|
+
name = name.slice(3);
|
|
23
|
+
negated = true;
|
|
24
|
+
}
|
|
25
|
+
const s = spec[name];
|
|
26
|
+
if (!s)
|
|
27
|
+
throw new CliError(`unknown flag --${name}`, "run cf-orbs --help");
|
|
28
|
+
if (s.type === "boolean") {
|
|
29
|
+
if (inline !== undefined) {
|
|
30
|
+
if (!/^(true|false|1|0)$/.test(inline))
|
|
31
|
+
throw new CliError(`--${name} takes no value`, `use --${name} or --no-${name}`);
|
|
32
|
+
flags[name] = negated !== (inline === "true" || inline === "1");
|
|
33
|
+
}
|
|
34
|
+
else
|
|
35
|
+
flags[name] = !negated;
|
|
36
|
+
continue;
|
|
37
|
+
}
|
|
38
|
+
if (negated)
|
|
39
|
+
throw new CliError(`--no-${name} is not valid`, `pass --${name} <value>`);
|
|
40
|
+
if (inline === undefined) {
|
|
41
|
+
const next = argv[i + 1];
|
|
42
|
+
if (next === undefined || (next.startsWith("-") && next !== "-")) {
|
|
43
|
+
throw new CliError(`--${name} needs a value`, `pass --${name} <value>`);
|
|
44
|
+
}
|
|
45
|
+
inline = next;
|
|
46
|
+
i++;
|
|
47
|
+
}
|
|
48
|
+
flags[name] = inline;
|
|
49
|
+
continue;
|
|
50
|
+
}
|
|
51
|
+
if (a.startsWith("-") && a.length > 1) {
|
|
52
|
+
const name = byShort.get(a.slice(1));
|
|
53
|
+
if (!name)
|
|
54
|
+
throw new CliError(`unknown flag ${a}`, "run cf-orbs --help");
|
|
55
|
+
const s = spec[name];
|
|
56
|
+
if (s?.type === "boolean")
|
|
57
|
+
flags[name] = true;
|
|
58
|
+
else {
|
|
59
|
+
const next = argv[i + 1];
|
|
60
|
+
if (next === undefined)
|
|
61
|
+
throw new CliError(`${a} needs a value`, `pass ${a} <value>`);
|
|
62
|
+
flags[name] = next;
|
|
63
|
+
i++;
|
|
64
|
+
}
|
|
65
|
+
continue;
|
|
66
|
+
}
|
|
67
|
+
positionals.push(a);
|
|
68
|
+
}
|
|
69
|
+
return { positionals, flags };
|
|
70
|
+
}
|
|
71
|
+
export function flagString(p, name) {
|
|
72
|
+
const v = p.flags[name];
|
|
73
|
+
return typeof v === "string" ? v : undefined;
|
|
74
|
+
}
|
|
75
|
+
export function flagBool(p, name) {
|
|
76
|
+
return p.flags[name] === true;
|
|
77
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
const HOWTO = 'cf-orbs bench: run the harness from a clone of the cf-orbs repo: npm run bench:substrate -- --dir <this directory> (needs "debugExec": true)';
|
|
2
|
+
export async function benchCommand(ctx) {
|
|
3
|
+
ctx.ui.out(HOWTO);
|
|
4
|
+
ctx.ui.result({ ok: true, message: HOWTO });
|
|
5
|
+
return 0;
|
|
6
|
+
}
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
// cf-orbs deploy: refresh templates, regenerate wrangler.jsonc, wrangler deploy with retries.
|
|
2
|
+
// Always re-sends CONTROL_TOKEN (secrets are additive; this repairs a lost secret).
|
|
3
|
+
// providerHost "external": also deletes AMP_ORB_PROVIDER_TOKEN so the Worker runs no provider.
|
|
4
|
+
// Then asks the Worker to restart the provider if its image changed, and to prewarm (config prewarm).
|
|
5
|
+
// Both are best effort and never fail the deploy.
|
|
6
|
+
import { makeApi } from "../api.js";
|
|
7
|
+
import { loadConfig } from "../config.js";
|
|
8
|
+
import { CliError } from "../errors.js";
|
|
9
|
+
import { cliVersion, materialize, missingDockerfiles, readState, requireControlToken, withSecretsFile, writeState, writeWranglerConfig, } from "../project.js";
|
|
10
|
+
import { deployWithRetry, lastErrorLine, makeWrangler } from "../wrangler.js";
|
|
11
|
+
/** Shared by init, deploy and upgrade. Returns the Worker URL. */
|
|
12
|
+
export async function deployProject(ctx, input) {
|
|
13
|
+
const { ui, paths } = ctx;
|
|
14
|
+
const { config, state } = input;
|
|
15
|
+
await materialize(paths, { templates: ctx.templates });
|
|
16
|
+
const missing = missingDockerfiles(paths, config);
|
|
17
|
+
if (missing.length > 0) {
|
|
18
|
+
throw new CliError(`image Dockerfile missing: ${missing.join(", ")}`, "create it, or remove its key from images in cf-orbs.config.jsonc");
|
|
19
|
+
}
|
|
20
|
+
const providerBuild = await writeWranglerConfig(paths, config, state.accountId);
|
|
21
|
+
ui.step(`deploy: wrangler deploy (${config.name}); first deploy builds and pushes a ~1.8 GB image, allow 5-15 min`);
|
|
22
|
+
const w = makeWrangler(ctx.run, { configPath: paths.wrangler, accountId: state.accountId });
|
|
23
|
+
const t0 = ctx.now();
|
|
24
|
+
const r = await withSecretsFile(input.secrets, (file) => deployWithRetry(w, ["--secrets-file", file], {
|
|
25
|
+
name: config.name,
|
|
26
|
+
onOutput: (s) => ui.raw(s),
|
|
27
|
+
onRetry: (n, why) => ui.step(`deploy: ${why}; retry ${n} of 3 (layers already pushed are kept)`),
|
|
28
|
+
sleep: ctx.sleep,
|
|
29
|
+
}));
|
|
30
|
+
const url = r.url ?? state.url;
|
|
31
|
+
if (!url) {
|
|
32
|
+
throw new CliError("deploy finished but no workers.dev URL was printed", "pass --url https://<name>.<subdomain>.workers.dev to status/doctor");
|
|
33
|
+
}
|
|
34
|
+
ui.step(`deploy: done in ${Math.round((ctx.now() - t0) / 1000)} s (${r.attempts} attempt${r.attempts > 1 ? "s" : ""}); ${url}`);
|
|
35
|
+
if (config.providerHost === "external")
|
|
36
|
+
await dropProviderToken(ctx, w);
|
|
37
|
+
await writeState(paths, {
|
|
38
|
+
...state,
|
|
39
|
+
url,
|
|
40
|
+
workerName: config.name,
|
|
41
|
+
mode: config.providerHost,
|
|
42
|
+
deployedAt: new Date(ctx.now()).toISOString(),
|
|
43
|
+
cliVersion: await cliVersion(),
|
|
44
|
+
});
|
|
45
|
+
return { url, attempts: r.attempts, providerBuild };
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* External mode: the Worker must run no provider. Secrets are additive, so delete AMP_ORB_PROVIDER_TOKEN;
|
|
49
|
+
* without it ProviderHost never starts and a running one stops at its next check. Not-found is fine.
|
|
50
|
+
*/
|
|
51
|
+
export async function dropProviderToken(ctx, w) {
|
|
52
|
+
const d = await w.run(["secret", "delete", "AMP_ORB_PROVIDER_TOKEN"], {
|
|
53
|
+
env: { CI: "1" },
|
|
54
|
+
timeoutMs: 60_000,
|
|
55
|
+
});
|
|
56
|
+
const out = `${d.stdout}\n${d.stderr}`;
|
|
57
|
+
if (d.code === 0 && !/not found|does not exist|10056/i.test(out))
|
|
58
|
+
ctx.ui.step("provider: removed AMP_ORB_PROVIDER_TOKEN from the Worker (external mode); its provider stops");
|
|
59
|
+
else if (d.code !== 0 && !/not found|does not exist|10056/i.test(out)) {
|
|
60
|
+
ctx.ui.warn(`Failed: could not remove AMP_ORB_PROVIDER_TOKEN from the Worker (${lastErrorLine(out)}) — fix: npx wrangler secret delete AMP_ORB_PROVIDER_TOKEN --config ${ctx.paths.wrangler}`);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
/** Wait between checks for a provider DO on old code to unload. Each check keeps it loaded, so > 140 s. */
|
|
64
|
+
export const OLD_CODE_WAIT_MS = 150_000;
|
|
65
|
+
const OLD_CODE_TRIES = 3;
|
|
66
|
+
const asObj = (v) => (v && typeof v === "object" && !Array.isArray(v) ? v : {});
|
|
67
|
+
const cause = (e) => String(e instanceof Error ? e.message : e)
|
|
68
|
+
.replace(/^Failed: /, "")
|
|
69
|
+
.replace(/ — fix: .*$/s, "");
|
|
70
|
+
/**
|
|
71
|
+
* POST /v1/provider/restart?ifImageChanged=1 after a deploy. The Worker restarts the provider container only
|
|
72
|
+
* when the provider image (build) changed. Best effort: a failure is one warning; the cron checks every 5 min.
|
|
73
|
+
*/
|
|
74
|
+
export async function restartProviderAfterDeploy(ctx, api, build) {
|
|
75
|
+
const { ui } = ctx;
|
|
76
|
+
let body;
|
|
77
|
+
try {
|
|
78
|
+
const r = await api.post("/v1/provider/restart?ifImageChanged=1");
|
|
79
|
+
body = asObj(r.body);
|
|
80
|
+
if (r.status < 200 || r.status >= 300)
|
|
81
|
+
throw new Error(typeof body.error === "string" ? body.error : `HTTP ${r.status}`);
|
|
82
|
+
}
|
|
83
|
+
catch (e) {
|
|
84
|
+
const error = `Failed: provider restart check did not run (${cause(e)}) — fix: run cf-orbs status; the 5-min check restarts the provider for a new image`;
|
|
85
|
+
ui.warn(error);
|
|
86
|
+
return { action: "error", restarted: false, error };
|
|
87
|
+
}
|
|
88
|
+
const action = String(body.action);
|
|
89
|
+
const reason = typeof body.reason === "string" ? body.reason : "";
|
|
90
|
+
if (action === "restart" && reason.startsWith("provider image changed"))
|
|
91
|
+
ui.step("provider: restarted for the new image");
|
|
92
|
+
else if (action === "restart")
|
|
93
|
+
ui.step(`provider: restarted (${reason})`);
|
|
94
|
+
else if (action === "keep")
|
|
95
|
+
ui.step("provider: image unchanged");
|
|
96
|
+
else if (action === "start")
|
|
97
|
+
ui.step("provider: started with the new image (it was not running)");
|
|
98
|
+
else if (action === "stopped-old-code")
|
|
99
|
+
return waitForNewCode(ctx, api, build);
|
|
100
|
+
else
|
|
101
|
+
ui.step(`provider: not restarted (${reason || action})`);
|
|
102
|
+
return { action, restarted: body.restarted === true };
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* The provider DO ran code from before provider restarts. The Worker stopped it; it loads the new code only
|
|
106
|
+
* after it unloads (no request for 70-140 s). Then start it here, or the cron starts it.
|
|
107
|
+
*/
|
|
108
|
+
async function waitForNewCode(ctx, api, build) {
|
|
109
|
+
const { ui } = ctx;
|
|
110
|
+
ui.step(`provider: its Durable Object ran old code, so it was stopped; waiting for it to load the new code (up to ${Math.round((OLD_CODE_WAIT_MS * OLD_CODE_TRIES) / 60_000)} min)`);
|
|
111
|
+
for (let i = 0; i < OLD_CODE_TRIES; i++) {
|
|
112
|
+
await ctx.sleep(OLD_CODE_WAIT_MS);
|
|
113
|
+
let p;
|
|
114
|
+
try {
|
|
115
|
+
p = asObj(asObj((await api.get("/v1/status")).body).provider);
|
|
116
|
+
}
|
|
117
|
+
catch {
|
|
118
|
+
continue;
|
|
119
|
+
}
|
|
120
|
+
if (p.deployedBuild !== build)
|
|
121
|
+
continue;
|
|
122
|
+
if (p.running !== true) {
|
|
123
|
+
try {
|
|
124
|
+
const r = await api.post("/v1/provider/start");
|
|
125
|
+
if (r.status < 200 || r.status >= 300)
|
|
126
|
+
continue;
|
|
127
|
+
}
|
|
128
|
+
catch {
|
|
129
|
+
continue;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
ui.step("provider: restarted for the new image");
|
|
133
|
+
return { action: "restart", restarted: true };
|
|
134
|
+
}
|
|
135
|
+
ui.step("provider: stopped; the 5-min check starts it with the new image once its Durable Object unloads; check cf-orbs status");
|
|
136
|
+
return { action: "stopped-old-code", restarted: false };
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* POST /v1/warm after a deploy. The Worker starts `prewarm` throwaway instances from the new image in the
|
|
140
|
+
* background and destroys them when they are ready. Best effort: a failure is one warning line.
|
|
141
|
+
*/
|
|
142
|
+
export async function startPrewarm(ctx, api, config) {
|
|
143
|
+
if (config.prewarm === 0)
|
|
144
|
+
return { started: 0 };
|
|
145
|
+
let cause;
|
|
146
|
+
try {
|
|
147
|
+
const r = await api.post("/v1/warm");
|
|
148
|
+
const body = (r.body && typeof r.body === "object" ? r.body : {});
|
|
149
|
+
if (r.status >= 200 && r.status < 300 && typeof body.started === "number") {
|
|
150
|
+
const n = body.started;
|
|
151
|
+
if (n > 0) {
|
|
152
|
+
ctx.ui.step(`prewarm: started ${n} instance${n === 1 ? "" : "s"} in the background; check cf-orbs status`);
|
|
153
|
+
return { started: n };
|
|
154
|
+
}
|
|
155
|
+
cause = Array.isArray(body.errors) ? String(body.errors[0]) : "the Worker started no instance";
|
|
156
|
+
}
|
|
157
|
+
else
|
|
158
|
+
cause =
|
|
159
|
+
typeof body.error === "string"
|
|
160
|
+
? body.error.replace(/^Failed: /, "").replace(/ — fix: .*$/s, "")
|
|
161
|
+
: `HTTP ${r.status}`;
|
|
162
|
+
}
|
|
163
|
+
catch (e) {
|
|
164
|
+
cause = e.message.replace(/^Failed: /, "").replace(/ — fix: .*$/s, "");
|
|
165
|
+
}
|
|
166
|
+
const error = `Failed: prewarm did not start (${cause}) — fix: run cf-orbs deploy again to retry, or set "prewarm": 0 in cf-orbs.config.jsonc`;
|
|
167
|
+
ctx.ui.warn(error);
|
|
168
|
+
return { started: 0, error };
|
|
169
|
+
}
|
|
170
|
+
export async function deployCommand(ctx) {
|
|
171
|
+
const config = await loadConfig(ctx.paths.config);
|
|
172
|
+
const state = await readState(ctx.paths);
|
|
173
|
+
const token = await requireControlToken(ctx.paths);
|
|
174
|
+
const r = await deployProject(ctx, { config, state, secrets: { CONTROL_TOKEN: token } });
|
|
175
|
+
const api = makeApi(r.url, token, ctx.fetch);
|
|
176
|
+
const provider = config.providerHost === "external"
|
|
177
|
+
? undefined
|
|
178
|
+
: await restartProviderAfterDeploy(ctx, api, r.providerBuild);
|
|
179
|
+
const prewarm = await startPrewarm(ctx, api, config);
|
|
180
|
+
ctx.ui.out(`Deployed ${config.name}: ${r.url}`);
|
|
181
|
+
ctx.ui.result({ ok: true, url: r.url, attempts: r.attempts, provider, prewarm });
|
|
182
|
+
return 0;
|
|
183
|
+
}
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
// cf-orbs doctor: PASS/FAIL per check with a one-line fix, plus INFO hints that never fail. Read-only: never starts a provider or an orb.
|
|
2
|
+
import { existsSync } from "node:fs";
|
|
3
|
+
import { collectImageKeys, expectOk, providerInfo } from "../api.js";
|
|
4
|
+
import { CONFIG_FILE, loadConfig, orbImageKeys } from "../config.js";
|
|
5
|
+
import { connect } from "../connect.js";
|
|
6
|
+
import { CliError, toFailedLine } from "../errors.js";
|
|
7
|
+
import { fileMode, readState } from "../project.js";
|
|
8
|
+
import { classifyDeployFailure, lastErrorLine, makeWrangler } from "../wrangler.js";
|
|
9
|
+
import { AMP_CACHE_HINT } from "./snapshots.js";
|
|
10
|
+
const pass = (name, detail) => ({ name, status: "PASS", detail });
|
|
11
|
+
const failed = (name, e) => ({ name, status: "FAIL", detail: toFailedLine(e) });
|
|
12
|
+
const skip = (name, detail) => ({ name, status: "SKIP", detail });
|
|
13
|
+
const info = (name, detail) => ({ name, status: "INFO", detail });
|
|
14
|
+
/**
|
|
15
|
+
* INFO, never FAIL: Amp keeps one prepared snapshot per provider for 72 h and cf-orbs cannot see or delete it.
|
|
16
|
+
* After an image or bootstrap change, a stale cache entry makes new threads skip setup on the old disk.
|
|
17
|
+
*/
|
|
18
|
+
export function ampCacheCheck(status) {
|
|
19
|
+
const reg = status && typeof status === "object" ? status.registry : undefined;
|
|
20
|
+
const n = reg && typeof reg === "object" ? reg.projectSnapshots : undefined;
|
|
21
|
+
const held = typeof n === "number" ? `cf-orbs holds ${n} project snapshot mapping(s). ` : "";
|
|
22
|
+
return info("Amp snapshot cache", `${held}${AMP_CACHE_HINT}`);
|
|
23
|
+
}
|
|
24
|
+
export function describeInstance(c) {
|
|
25
|
+
const i = c.instance;
|
|
26
|
+
return typeof i === "string" ? i : `${i.vcpu} vCPU, ${i.memoryMib} MiB, ${i.diskMb} MB disk`;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Checks that need only /v1/status and the config. Pure.
|
|
30
|
+
* tokenSecret: whether the Worker has AMP_ORB_PROVIDER_TOKEN (from wrangler secret list), if known.
|
|
31
|
+
*/
|
|
32
|
+
export function statusChecks(status, config, opts = {}) {
|
|
33
|
+
const out = [];
|
|
34
|
+
const p = providerInfo(status);
|
|
35
|
+
const last = `${p.lastError ? `; last error: ${p.lastError}` : ""}${p.lastLogLine ? `; last log: ${p.lastLogLine}` : ""}`;
|
|
36
|
+
if (config.providerHost === "cloudflare") {
|
|
37
|
+
if (opts.tokenSecret === false) {
|
|
38
|
+
out.push(failed("provider", new CliError("the Worker has no AMP_ORB_PROVIDER_TOKEN secret, so it runs no provider", "rerun cf-orbs init with AMP_ORB_PROVIDER_TOKEN set (or --token-file <file>)")));
|
|
39
|
+
}
|
|
40
|
+
else if (p.running === true)
|
|
41
|
+
out.push(pass("provider", `running${last}`));
|
|
42
|
+
else {
|
|
43
|
+
out.push(failed("provider", new CliError(`provider is ${p.running === false ? "not running" : "not reported"}${last}`, "wait for the 5-min cron to restart it, check cf-orbs logs --provider, or rerun cf-orbs init")));
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
else if (p.running === true) {
|
|
47
|
+
out.push(failed("provider", new CliError("providerHost is external but the Worker's own provider is running too (two providers on one token)", `npx wrangler secret delete AMP_ORB_PROVIDER_TOKEN --config ${opts.wranglerPath ?? ".cf-orbs/wrangler.jsonc"}`)));
|
|
48
|
+
}
|
|
49
|
+
else
|
|
50
|
+
out.push(skip("provider", "providerHost is external; check the amp orb provider service on your host"));
|
|
51
|
+
const known = new Set(orbImageKeys(config));
|
|
52
|
+
const used = [...collectImageKeys(status)];
|
|
53
|
+
const stale = used.filter((k) => !known.has(k));
|
|
54
|
+
if (stale.length === 0)
|
|
55
|
+
out.push(pass("image keys", `${used.length} key(s) in use, all built (${[...known].join(", ")})`));
|
|
56
|
+
else {
|
|
57
|
+
out.push(failed("image keys", new CliError(`snapshots or orbs use image keys not in ${CONFIG_FILE}: ${stale.join(", ")}`, `add them back to images in ${CONFIG_FILE} with their image/<key>.Dockerfile, then cf-orbs deploy`)));
|
|
58
|
+
}
|
|
59
|
+
return out;
|
|
60
|
+
}
|
|
61
|
+
export async function runDoctor(ctx) {
|
|
62
|
+
const checks = [];
|
|
63
|
+
let config;
|
|
64
|
+
try {
|
|
65
|
+
config = await loadConfig(ctx.paths.config);
|
|
66
|
+
checks.push(pass("config", `${describeInstance(config)}; maxRunning ${config.maxRunning}; providerHost ${config.providerHost}`));
|
|
67
|
+
}
|
|
68
|
+
catch (e) {
|
|
69
|
+
checks.push(failed("config", e));
|
|
70
|
+
}
|
|
71
|
+
const state = await readState(ctx.paths);
|
|
72
|
+
const mode = await fileMode(ctx.paths.controlToken);
|
|
73
|
+
if (mode === undefined)
|
|
74
|
+
checks.push(failed("control token", new CliError(`${ctx.paths.controlToken} missing`, "run cf-orbs init")));
|
|
75
|
+
else if (mode !== 0o600) {
|
|
76
|
+
checks.push(failed("control token", new CliError(`${ctx.paths.controlToken} has mode ${mode.toString(8)}`, `chmod 600 ${ctx.paths.controlToken}`)));
|
|
77
|
+
}
|
|
78
|
+
else
|
|
79
|
+
checks.push(pass("control token", "present, mode 600"));
|
|
80
|
+
const name = config?.name ?? state.workerName ?? "cf-orbs";
|
|
81
|
+
const w = makeWrangler(ctx.run, { accountId: state.accountId });
|
|
82
|
+
const d = await w.run(["deployments", "list", "--json", "--name", name], { timeoutMs: 60_000 });
|
|
83
|
+
let deployments = [];
|
|
84
|
+
try {
|
|
85
|
+
deployments = JSON.parse(d.stdout.slice(Math.max(0, d.stdout.indexOf("["))));
|
|
86
|
+
}
|
|
87
|
+
catch { }
|
|
88
|
+
if (d.code === 0 && Array.isArray(deployments) && deployments.length > 0) {
|
|
89
|
+
checks.push(pass("deployment", `Worker ${name} deployed; latest ${deployments[0]?.created_on ?? "?"}`));
|
|
90
|
+
}
|
|
91
|
+
else if (d.code !== 0 && !/not found|does not exist|10007/i.test(`${d.stdout}\n${d.stderr}`)) {
|
|
92
|
+
// wrangler itself failed (logged out, expired token, network): do not send the user into a rebuild.
|
|
93
|
+
const out = `${d.stdout}\n${d.stderr}`;
|
|
94
|
+
checks.push(failed("deployment", classifyDeployFailure(out) === "auth"
|
|
95
|
+
? new CliError("wrangler is not logged in or its token expired", "run npx wrangler login")
|
|
96
|
+
: new CliError(`wrangler deployments list failed: ${lastErrorLine(out)}`, "check your network and npx wrangler whoami")));
|
|
97
|
+
}
|
|
98
|
+
else {
|
|
99
|
+
checks.push(failed("deployment", new CliError(`no deployment of Worker ${name} found`, "run cf-orbs deploy (or cf-orbs init)")));
|
|
100
|
+
}
|
|
101
|
+
let api;
|
|
102
|
+
try {
|
|
103
|
+
api = (await connect(ctx)).api;
|
|
104
|
+
}
|
|
105
|
+
catch (e) {
|
|
106
|
+
checks.push(failed("health", e));
|
|
107
|
+
}
|
|
108
|
+
let status;
|
|
109
|
+
if (api) {
|
|
110
|
+
try {
|
|
111
|
+
expectOk(await api.get("/v1/health"), "health");
|
|
112
|
+
checks.push(pass("health", `${api.url}/v1/health ok`));
|
|
113
|
+
}
|
|
114
|
+
catch (e) {
|
|
115
|
+
checks.push(failed("health", e));
|
|
116
|
+
}
|
|
117
|
+
try {
|
|
118
|
+
status = expectOk(await api.get("/v1/status"), "status");
|
|
119
|
+
checks.push(pass("status", "/v1/status ok (control token accepted)"));
|
|
120
|
+
}
|
|
121
|
+
catch (e) {
|
|
122
|
+
checks.push(failed("status", e));
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
// Names only: wrangler secret list never returns values.
|
|
126
|
+
let tokenSecret;
|
|
127
|
+
if (config?.providerHost === "cloudflare" && existsSync(ctx.paths.wrangler)) {
|
|
128
|
+
const sl = await makeWrangler(ctx.run, {
|
|
129
|
+
configPath: ctx.paths.wrangler,
|
|
130
|
+
accountId: state.accountId,
|
|
131
|
+
}).run(["secret", "list", "--format", "json"], { timeoutMs: 60_000 });
|
|
132
|
+
if (sl.code === 0) {
|
|
133
|
+
try {
|
|
134
|
+
const list = JSON.parse(sl.stdout.slice(Math.max(0, sl.stdout.indexOf("["))));
|
|
135
|
+
if (Array.isArray(list))
|
|
136
|
+
tokenSecret = list.some((x) => x.name === "AMP_ORB_PROVIDER_TOKEN");
|
|
137
|
+
}
|
|
138
|
+
catch { }
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
if (status !== undefined && config)
|
|
142
|
+
checks.push(...statusChecks(status, config, { tokenSecret, wranglerPath: ctx.paths.wrangler }));
|
|
143
|
+
else {
|
|
144
|
+
checks.push(skip("provider", "needs /v1/status and a valid config"));
|
|
145
|
+
checks.push(skip("image keys", "needs /v1/status and a valid config"));
|
|
146
|
+
}
|
|
147
|
+
checks.push(ampCacheCheck(status));
|
|
148
|
+
return checks;
|
|
149
|
+
}
|
|
150
|
+
export async function doctorCommand(ctx) {
|
|
151
|
+
const checks = await runDoctor(ctx);
|
|
152
|
+
const bad = checks.filter((c) => c.status === "FAIL").length;
|
|
153
|
+
ctx.ui.result({ ok: bad === 0, checks });
|
|
154
|
+
const w = Math.max(...checks.map((c) => c.name.length));
|
|
155
|
+
for (const c of checks)
|
|
156
|
+
ctx.ui.out(`${c.status} ${c.name.padEnd(w)} ${c.detail}`);
|
|
157
|
+
ctx.ui.out(bad === 0 ? "All checks passed." : `${bad} check(s) failed.`);
|
|
158
|
+
return bad === 0 ? 0 : 1;
|
|
159
|
+
}
|