@runeditrun/rer 0.2.16 → 0.2.17
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/cli/deploy-claim-request.mjs +32 -0
- package/cli/deploy-command.mjs +22 -8
- package/cli/deploy-hook.mjs +11 -3
- package/cli/deploy-observation.mjs +7 -4
- package/cli/deploy-owner.mjs +5 -4
- package/cli/deploy.mjs +4 -4
- package/cli/door.mjs +4 -3
- package/cli/local.mjs +5 -3
- package/cli/pnpm-probe.mjs +19 -10
- package/cli/port.mjs +17 -10
- package/cli/project-pnpm.mjs +4 -2
- package/cli/site-diagnostics.mjs +35 -0
- package/cli/site-render.mjs +4 -1
- package/cli/site.mjs +5 -0
- package/global/CHANGELOG.md +12 -0
- package/modules/container/boundary.mjs +70 -34
- package/modules/container/build.mjs +20 -3
- package/modules/container/import-graph.mjs +233 -0
- package/modules/deploy-kit/deploy.mjs +8 -3
- package/modules/deploy-kit/health-request.mjs +14 -11
- package/modules/deploy-kit/health.mjs +16 -6
- package/modules/deploy-kit/owner-cli.mjs +24 -4
- package/modules/deploy-kit/owner.mjs +6 -3
- package/modules/deploy-kit/provider.mjs +6 -2
- package/modules/deploy-kit/readiness-window.mjs +32 -0
- package/modules/deploy-kit/uploaded-worker.mjs +22 -0
- package/modules/deploy-kit/worker.mjs +1 -1
- package/onboarding/adapter.mjs +13 -4
- package/onboarding/process-diagnostics.mjs +142 -36
- package/package.json +1 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { readFile, writeFile, readdir, realpath, cp, mkdir, rm } from 'node:fs/promises';
|
|
2
|
-
import { dirname, join, resolve } from 'node:path';
|
|
2
|
+
import { dirname, join, resolve, sep } from 'node:path';
|
|
3
3
|
import { createRequire } from 'node:module';
|
|
4
4
|
import { pathToFileURL } from 'node:url';
|
|
5
5
|
import { createHash } from 'node:crypto';
|
|
@@ -23,10 +23,18 @@ async function buildImage(root, { output = join(root,'.rer/container/image'), en
|
|
|
23
23
|
if (!loaded) throw new Error('Vite configuration missing');
|
|
24
24
|
const config = loaded.config;
|
|
25
25
|
const outputExports = new Map();
|
|
26
|
+
const freshServerFiles = new Set(), serverOutput = resolve(root,'dist/server');
|
|
26
27
|
if (engine === 'workerd') config.plugins = [...(config.plugins ?? []), {
|
|
27
28
|
name:'rer-container-exports',
|
|
28
29
|
async writeBundle(output,bundle) {
|
|
29
|
-
|
|
30
|
+
const outputDir = resolve(root,output.dir ?? dirname(output.file));
|
|
31
|
+
if (outputDir === serverOutput || outputDir.startsWith(serverOutput + sep)) {
|
|
32
|
+
for (const chunk of Object.values(bundle)) if (chunk.type === 'chunk') {
|
|
33
|
+
const path = resolve(outputDir,chunk.fileName);
|
|
34
|
+
freshServerFiles.add(path);
|
|
35
|
+
if (chunk.isEntry) outputExports.set(await realpath(path),new Set(chunk.exports));
|
|
36
|
+
}
|
|
37
|
+
}
|
|
30
38
|
},
|
|
31
39
|
}];
|
|
32
40
|
if (engine === 'node') {
|
|
@@ -35,7 +43,13 @@ async function buildImage(root, { output = join(root,'.rer/container/image'), en
|
|
|
35
43
|
config.plugins = [{ name:'rer-container-bindings', enforce:'pre',
|
|
36
44
|
resolveId(id) { if (id === 'cloudflare:workers') return bindingShim; },
|
|
37
45
|
transform(source,id) { if (cacheContract === 'lamp-retained-v1' && id === join(root,'src/server.ts')) return source.replace(/export\s*\{\s*SnapshotCache\s*\}\s*from\s*['"][^'"]+['"];?/,''); },
|
|
38
|
-
},...plugins
|
|
46
|
+
},...plugins,{
|
|
47
|
+
name:'rer-container-boundary-output',
|
|
48
|
+
writeBundle(output,bundle) {
|
|
49
|
+
const outputDir = resolve(root,output.dir ?? dirname(output.file));
|
|
50
|
+
if (outputDir === serverOutput || outputDir.startsWith(serverOutput + sep)) for (const chunk of Object.values(bundle)) if (chunk.type === 'chunk') freshServerFiles.add(resolve(outputDir,chunk.fileName));
|
|
51
|
+
},
|
|
52
|
+
}];
|
|
39
53
|
config.ssr = { ...config.ssr,noExternal:true }; config.environments = { ...config.environments,ssr:{ ...config.environments?.ssr,resolve:{ noExternal:true },build:{ ...config.environments?.ssr?.build,rolldownOptions:{ output:{ entryFileNames:'index.mjs' } } } } };
|
|
40
54
|
}
|
|
41
55
|
const builder = await vite.createBuilder({ ...config,root,configFile:false }); await builder.buildApp();
|
|
@@ -47,6 +61,9 @@ async function buildImage(root, { output = join(root,'.rer/container/image'), en
|
|
|
47
61
|
localDurableObjects(workerConfig,outputExports.get(await realpath(resolve(root,'dist/server',workerConfig.main))));
|
|
48
62
|
}
|
|
49
63
|
else workerConfig = parseJsonc(await readFile(join(root,'wrangler.jsonc'),'utf8'));
|
|
64
|
+
const serverEntry = engine === 'workerd' ? resolve(root,'dist/server',workerConfig.main) : resolve(root,'dist/server/index.mjs');
|
|
65
|
+
if (!freshServerFiles.has(serverEntry)) throw new Error('Container server entry was not emitted by this build');
|
|
66
|
+
await checkBoundary(root,{engine,cacheContract,entries:[serverEntry],emittedFiles:freshServerFiles,outputRoot:serverOutput});
|
|
50
67
|
const { unstable_splitSqlQuery:split } = require('wrangler');
|
|
51
68
|
const migrations = {}, rewrites = await readMigrationRewrites(root);
|
|
52
69
|
for (const db of workerConfig.d1_databases ?? []) {
|
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
import { readFile, stat } from 'node:fs/promises';
|
|
2
|
+
import { createRequire } from 'node:module';
|
|
3
|
+
import { dirname, extname, isAbsolute, join, relative, resolve, sep } from 'node:path';
|
|
4
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
5
|
+
import { parseJsonc } from '../../cli/jsonc.mjs';
|
|
6
|
+
import { tomlMain } from '../../cli/deploy-config.mjs';
|
|
7
|
+
|
|
8
|
+
const sourceExtensions = new Set(['.js', '.jsx', '.mjs', '.cjs', '.ts', '.tsx', '.mts', '.cts']);
|
|
9
|
+
const builtExtensions = ['.mjs', '.js', '.cjs', '.jsx'];
|
|
10
|
+
|
|
11
|
+
const normalized = path => resolve(path);
|
|
12
|
+
const displayPath = (root, path) => relative(root, path).split(sep).join('/') || '.';
|
|
13
|
+
const isDeclaration = path => /\.d\.(?:ts|mts|cts)$/i.test(path);
|
|
14
|
+
const isCode = path => sourceExtensions.has(extname(path).toLowerCase()) && !isDeclaration(path);
|
|
15
|
+
const isPackagePath = path => path.split(sep).includes('node_modules');
|
|
16
|
+
const stripQuery = specifier => specifier.startsWith('#') ? specifier : specifier.split(/[?#]/, 1)[0];
|
|
17
|
+
const isRelative = specifier => specifier.startsWith('./') || specifier.startsWith('../');
|
|
18
|
+
const isScheme = specifier => /^[a-z][a-z\d+.-]*:/i.test(specifier);
|
|
19
|
+
|
|
20
|
+
function runtimeImport(ts, declaration) {
|
|
21
|
+
const clause = declaration.importClause;
|
|
22
|
+
if (!clause) return true;
|
|
23
|
+
if (clause.isTypeOnly) return false;
|
|
24
|
+
if (clause.name) return true;
|
|
25
|
+
const bindings = clause.namedBindings;
|
|
26
|
+
if (!bindings || ts.isNamespaceImport(bindings)) return Boolean(bindings);
|
|
27
|
+
return bindings.elements.length === 0 || bindings.elements.some(element => !element.isTypeOnly);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function runtimeReexport(ts, declaration) {
|
|
31
|
+
if (declaration.isTypeOnly) return false;
|
|
32
|
+
const clause = declaration.exportClause;
|
|
33
|
+
return !clause || !ts.isNamedExports(clause) || clause.elements.length === 0 || clause.elements.some(element => !element.isTypeOnly);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function runtimeEdges(ts, tree, options) {
|
|
37
|
+
const edges = [];
|
|
38
|
+
const add = (node, kind) => {
|
|
39
|
+
if (node && ts.isStringLiteralLike(node)) {
|
|
40
|
+
// Dynamic import keeps its ESM condition inside a CommonJS module; static
|
|
41
|
+
// TypeScript imports follow that file's emitted format instead.
|
|
42
|
+
const mode = kind === 'require' || kind === 'import-equals' ? ts.ModuleKind.CommonJS
|
|
43
|
+
: kind === 'dynamic-import' ? ts.ModuleKind.ESNext
|
|
44
|
+
: ts.getModeForUsageLocation(tree, node, options) ?? ts.ModuleKind.ESNext;
|
|
45
|
+
edges.push({ specifier: node.text, kind, mode });
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
function visit(node) {
|
|
49
|
+
if (ts.isImportDeclaration(node) && runtimeImport(ts, node)) add(node.moduleSpecifier, 'import');
|
|
50
|
+
else if (ts.isExportDeclaration(node) && node.moduleSpecifier && runtimeReexport(ts, node)) add(node.moduleSpecifier, 're-export');
|
|
51
|
+
else if (ts.isImportEqualsDeclaration(node) && !node.isTypeOnly && ts.isExternalModuleReference(node.moduleReference)) add(node.moduleReference.expression, 'import-equals');
|
|
52
|
+
else if (ts.isCallExpression(node)) {
|
|
53
|
+
if (node.expression.kind === ts.SyntaxKind.ImportKeyword) add(node.arguments[0], 'dynamic-import');
|
|
54
|
+
else if (ts.isIdentifier(node.expression) && node.expression.text === 'require') add(node.arguments[0], 'require');
|
|
55
|
+
}
|
|
56
|
+
ts.forEachChild(node, visit);
|
|
57
|
+
}
|
|
58
|
+
visit(tree);
|
|
59
|
+
return edges;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function matchesPathAlias(specifier, options) {
|
|
63
|
+
for (const pattern of Object.keys(options.paths ?? {})) {
|
|
64
|
+
const wildcard = pattern.indexOf('*');
|
|
65
|
+
if (wildcard < 0 ? specifier === pattern : specifier.startsWith(pattern.slice(0, wildcard)) && specifier.endsWith(pattern.slice(wildcard + 1))) return true;
|
|
66
|
+
}
|
|
67
|
+
return false;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
async function localAssetExists(from, specifier) {
|
|
71
|
+
const target = resolve(dirname(from), specifier);
|
|
72
|
+
try { return (await stat(target)).isFile() ? target : null; } catch (error) { if (error.code === 'ENOENT' || error.code === 'ENOTDIR') return null; throw error; }
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
async function loadTypeScript(root) {
|
|
76
|
+
const require = createRequire(join(root, 'package.json'));
|
|
77
|
+
const path = require.resolve('typescript');
|
|
78
|
+
return import(pathToFileURL(path));
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
async function compilerOptions(root, ts) {
|
|
82
|
+
const path = join(root, 'tsconfig.json');
|
|
83
|
+
if (!ts.sys.fileExists(path)) return { allowJs: true, resolveJsonModule: true, module: ts.ModuleKind.ESNext, moduleResolution: ts.ModuleResolutionKind.Bundler };
|
|
84
|
+
try {
|
|
85
|
+
const parsed = ts.getParsedCommandLineOfConfigFile(path, {}, {
|
|
86
|
+
...ts.sys,
|
|
87
|
+
onUnRecoverableConfigFileDiagnostic(diagnostic) {
|
|
88
|
+
throw new Error(ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'));
|
|
89
|
+
},
|
|
90
|
+
});
|
|
91
|
+
if (!parsed) throw new Error('TypeScript did not return parsed compiler options');
|
|
92
|
+
const errors = parsed.errors.filter(diagnostic => diagnostic.category === ts.DiagnosticCategory.Error);
|
|
93
|
+
if (errors.length) throw new Error(errors.map(diagnostic => ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n')).join('\n'));
|
|
94
|
+
return { ...parsed.options, allowJs: true, resolveJsonModule: true };
|
|
95
|
+
} catch (error) {
|
|
96
|
+
if (error.code === 'ENOENT') return { allowJs: true, resolveJsonModule: true, module: ts.ModuleKind.ESNext, moduleResolution: ts.ModuleResolutionKind.Bundler };
|
|
97
|
+
throw new Error(`Could not read TypeScript project configuration: ${error.message}`, { cause: error });
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
async function configuredEntry(root) {
|
|
102
|
+
for (const name of ['wrangler.jsonc', 'wrangler.json', 'wrangler.toml']) {
|
|
103
|
+
let text;
|
|
104
|
+
try { text = await readFile(join(root, name), 'utf8'); }
|
|
105
|
+
catch (error) { if (error.code === 'ENOENT') continue; throw error; }
|
|
106
|
+
let main;
|
|
107
|
+
try {
|
|
108
|
+
main = name.endsWith('.toml') ? tomlMain(text) : parseJsonc(text).main;
|
|
109
|
+
} catch (error) {
|
|
110
|
+
throw new Error(`Could not read Wrangler main from ${name}: ${error.message}`, { cause: error });
|
|
111
|
+
}
|
|
112
|
+
if (typeof main !== 'string' || !main.trim()) throw new Error(`${name} does not declare a Wrangler main entry`);
|
|
113
|
+
return resolve(root, main);
|
|
114
|
+
}
|
|
115
|
+
throw new Error('No root wrangler.jsonc, wrangler.json, or wrangler.toml declares the app main entry');
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function failure(path, api, extra = {}) {
|
|
119
|
+
return { path, api, ...extra };
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function runtimeRequest(specifier) {
|
|
123
|
+
return /^file:/i.test(specifier) ? fileURLToPath(specifier) : stripQuery(specifier);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
async function resolveSourceEdge(ts, edge, importer, options) {
|
|
127
|
+
const { specifier, mode } = edge;
|
|
128
|
+
let request;
|
|
129
|
+
try { request = runtimeRequest(specifier); }
|
|
130
|
+
catch { return { unresolved: true, reason: 'invalid local file URL' }; }
|
|
131
|
+
const local = isRelative(request) || isAbsolute(request) || request.startsWith('#') || matchesPathAlias(request, options);
|
|
132
|
+
if (isScheme(request)) return { external: true };
|
|
133
|
+
const javascriptRequest = builtExtensions.includes(extname(request).toLowerCase());
|
|
134
|
+
if (javascriptRequest && (isRelative(request) || isAbsolute(request))) {
|
|
135
|
+
const implementation = await localAssetExists(importer, request);
|
|
136
|
+
if (implementation) return isPackagePath(implementation) ? { external: true } : { path: implementation };
|
|
137
|
+
}
|
|
138
|
+
// TypeScript prefers declaration sidecars to JavaScript implementations. They
|
|
139
|
+
// describe types, not the code the runtime will execute, so exclude them from
|
|
140
|
+
// graph resolution. Explicit JavaScript imports first try real JavaScript;
|
|
141
|
+
// the second pass retains TypeScript's extension substitution for source apps
|
|
142
|
+
// that import ./module.js but author module.ts (including configured aliases).
|
|
143
|
+
const implementationHost = { ...ts.sys, fileExists: path => !isDeclaration(path) && ts.sys.fileExists(path) };
|
|
144
|
+
const javascriptHost = { ...ts.sys, fileExists: path => !/\.(?:ts|tsx|mts|cts)$/i.test(path) && ts.sys.fileExists(path) };
|
|
145
|
+
const resolveModule = host => ts.resolveModuleName(request, importer, options, host, undefined, undefined, mode).resolvedModule;
|
|
146
|
+
const resolved = (javascriptRequest && resolveModule(javascriptHost)) || resolveModule(implementationHost);
|
|
147
|
+
if (resolved) {
|
|
148
|
+
const path = normalized(resolved.resolvedFileName);
|
|
149
|
+
if (resolved.isExternalLibraryImport || isPackagePath(path)) return { external: true };
|
|
150
|
+
if (isCode(path)) return { path };
|
|
151
|
+
return { external: true };
|
|
152
|
+
}
|
|
153
|
+
if (!local) return { external: true };
|
|
154
|
+
const asset = await localAssetExists(importer, request);
|
|
155
|
+
if (asset && !isCode(asset) && !isDeclaration(asset)) return { external: true };
|
|
156
|
+
return { unresolved: true };
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
async function builtCandidates(importer, request) {
|
|
160
|
+
const target = resolve(dirname(importer), request);
|
|
161
|
+
if (extname(target)) return [target];
|
|
162
|
+
return [...builtExtensions.map(extension => target + extension), ...builtExtensions.map(extension => join(target, 'index' + extension))];
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function emittedModule(path, emittedFiles, outputRoot) {
|
|
166
|
+
const canonical = normalized(path), rel = relative(outputRoot, canonical);
|
|
167
|
+
if (rel.startsWith('..') || isAbsolute(rel)) return { unresolved: true, reason: 'local import escapes the built server output' };
|
|
168
|
+
if (!emittedFiles.has(canonical)) return { unresolved: true, reason: 'local import was not emitted by this build' };
|
|
169
|
+
return { path: canonical };
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
async function resolveBuiltEdge(ts, importer, edge, options, emittedFiles, outputRoot) {
|
|
173
|
+
let request;
|
|
174
|
+
try { request = runtimeRequest(edge.specifier); }
|
|
175
|
+
catch { return { unresolved: true, reason: 'invalid local file URL' }; }
|
|
176
|
+
if (!isScheme(request) && !isRelative(request) && !isAbsolute(request)) {
|
|
177
|
+
const result = await resolveSourceEdge(ts, edge, importer, options);
|
|
178
|
+
return result.path ? emittedModule(result.path, emittedFiles, outputRoot) : result;
|
|
179
|
+
}
|
|
180
|
+
if (isScheme(request)) return { external: true };
|
|
181
|
+
const requested = resolve(dirname(importer), request);
|
|
182
|
+
const candidates = await builtCandidates(importer, request);
|
|
183
|
+
for (const candidate of candidates) {
|
|
184
|
+
try {
|
|
185
|
+
if (!(await stat(candidate)).isFile()) continue;
|
|
186
|
+
} catch (error) { if (error.code === 'ENOENT' || error.code === 'ENOTDIR') continue; throw error; }
|
|
187
|
+
if (!isCode(candidate)) return { external: true };
|
|
188
|
+
return emittedModule(candidate, emittedFiles, outputRoot);
|
|
189
|
+
}
|
|
190
|
+
if (extname(requested) && !sourceExtensions.has(extname(requested).toLowerCase())) {
|
|
191
|
+
const asset = await localAssetExists(importer, request);
|
|
192
|
+
if (asset) return { external: true };
|
|
193
|
+
}
|
|
194
|
+
return { unresolved: true };
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
export async function walkImportGraph(root, { entries, emittedFiles, outputRoot, onFile }) {
|
|
198
|
+
// A package's `types` condition must not select a different runtime branch.
|
|
199
|
+
const ts = await loadTypeScript(root), options = { ...await compilerOptions(root, ts), noDtsResolution: true };
|
|
200
|
+
const failures = [], visited = new Set(), pending = (await Promise.all(entries.map(async entry => {
|
|
201
|
+
if (isAbsolute(entry)) return normalized(entry);
|
|
202
|
+
return resolve(root, entry);
|
|
203
|
+
}))).reverse();
|
|
204
|
+
const emitted = emittedFiles ? new Set([...emittedFiles].map(normalized)) : null;
|
|
205
|
+
const builtRoot = outputRoot ? normalized(outputRoot) : null;
|
|
206
|
+
const built = Boolean(emitted && builtRoot);
|
|
207
|
+
|
|
208
|
+
while (pending.length) {
|
|
209
|
+
const path = pending.pop(), canonical = normalized(path);
|
|
210
|
+
if (visited.has(canonical)) continue;
|
|
211
|
+
visited.add(canonical);
|
|
212
|
+
let source;
|
|
213
|
+
try { source = await readFile(canonical, 'utf8'); }
|
|
214
|
+
catch (error) { failures.push(failure(displayPath(root, canonical), 'Missing app entry or runtime module', { message: error.message })); continue; }
|
|
215
|
+
if (!isCode(canonical)) { failures.push(failure(displayPath(root, canonical), 'App graph entry is not a JavaScript or TypeScript module')); continue; }
|
|
216
|
+
const tree = ts.createSourceFile(canonical, source, ts.ScriptTarget.Latest, true);
|
|
217
|
+
tree.impliedNodeFormat = ts.getImpliedNodeFormatForFile(canonical, undefined, ts.sys, options);
|
|
218
|
+
onFile?.({ ts, tree, path: canonical, source });
|
|
219
|
+
// Emitted JavaScript already contains its runtime syntax; do not apply the
|
|
220
|
+
// source project's TypeScript module transform to it again.
|
|
221
|
+
for (const edge of runtimeEdges(ts, tree, built ? { ...options, module: ts.ModuleKind.Preserve } : options)) {
|
|
222
|
+
const result = built
|
|
223
|
+
? await resolveBuiltEdge(ts, canonical, edge, options, emitted, builtRoot)
|
|
224
|
+
: await resolveSourceEdge(ts, edge, canonical, options);
|
|
225
|
+
if (result.unresolved) {
|
|
226
|
+
failures.push(failure(displayPath(root, canonical), 'Unresolved local runtime import', { specifier: edge.specifier, kind: edge.kind, ...(result.reason ? { message: result.reason } : {}) }));
|
|
227
|
+
} else if (result.path) pending.push(result.path);
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
return { ts, files: visited, failures };
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
export { configuredEntry, isCode };
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { readinessWindow, readinessAPI } from './readiness-window.mjs';
|
|
2
|
+
import { uploadedWorker } from './uploaded-worker.mjs';
|
|
1
3
|
import { recordDeployFailure } from './diagnostics.mjs';
|
|
2
4
|
import { verifyServiceGrants } from './service-grants.mjs';
|
|
3
5
|
import { assert, hash, validatePlan } from './validation.mjs';
|
|
@@ -42,8 +44,11 @@ export async function deploy({api,plan,artifact,artifactSha256,previousReceipt,r
|
|
|
42
44
|
const migrations = [];
|
|
43
45
|
// A migration failure names its database, so the owner knows which one to inspect.
|
|
44
46
|
for (const item of plan.d1) migrations.push({binding:item.binding,...await migrate(api,resources.d1.find(x => x.binding === item.binding).id,item.migrations,{apply:!unchanged,upgrade:true}).catch(error => { error.resource ??= `d1:${item.name}`; throw error; })});
|
|
45
|
-
|
|
46
|
-
|
|
47
|
+
const window = readiness.window ?? readinessWindow({...(healthOptions.now ? {clock:healthOptions.now} : {}), ...(healthOptions.sleep ? {sleep:healthOptions.sleep} : {}), ...readiness});
|
|
48
|
+
let upload;
|
|
49
|
+
if (!unchanged) { window.start(); upload = await uploadWorker(api,{plan,artifact,bindings,secrets,migration,fingerprint}); }
|
|
50
|
+
if (!unchanged) api = readinessAPI(api, window);
|
|
51
|
+
const published = unchanged ? existing : await uploadedWorker({api,worker:plan.worker,upload,previous:existing,fingerprint,window}); assert(published,'missing-deployed-worker');
|
|
47
52
|
verifyBindings(published.settings.bindings,bindings);
|
|
48
53
|
verifyScheduledHandler(published,plan);
|
|
49
54
|
// Finish routing activation before applying schedules to this deployment.
|
|
@@ -61,7 +66,7 @@ export async function deploy({api,plan,artifact,artifactSha256,previousReceipt,r
|
|
|
61
66
|
const asset = publicAssetPaths(artifact.assets.map(x => x.path))[0];
|
|
62
67
|
try {
|
|
63
68
|
if (unchanged) await verifyHealth({...healthOptions,api,plan,receipt,fetch,asset});
|
|
64
|
-
else await firstHealth({api,plan,receipt,fetch,healthOptions,readiness,onHealth,asset});
|
|
69
|
+
else await firstHealth({api,plan,receipt,fetch,healthOptions,readiness:{...readiness,window,freshUpload:!existing},onHealth,asset});
|
|
65
70
|
} catch (error) { throw recordDeployFailure(error,{step:'health',...(error.code ? {code:error.code,output:error.message} : {})}); }
|
|
66
71
|
return receipt;
|
|
67
72
|
}
|
|
@@ -6,17 +6,17 @@ import { assert } from './validation.mjs';
|
|
|
6
6
|
const decodePrefix = bytes => new StringDecoder('utf8').write(bytes.subarray(0,256));
|
|
7
7
|
|
|
8
8
|
async function bodyPrefix(response) {
|
|
9
|
-
if (!response.body) return '';
|
|
10
|
-
const reader = response.body.getReader(); let bytes = Buffer.alloc(0);
|
|
9
|
+
if (!response.body) return {body:'',complete:true};
|
|
10
|
+
const reader = response.body.getReader(); let bytes = Buffer.alloc(0), complete = false;
|
|
11
11
|
try {
|
|
12
12
|
while (bytes.length < 256) {
|
|
13
13
|
const {done,value} = await reader.read();
|
|
14
|
-
if (done) break;
|
|
14
|
+
if (done) { complete = true; break; }
|
|
15
15
|
bytes = Buffer.concat([bytes,value.subarray(0,256-bytes.length)]);
|
|
16
16
|
}
|
|
17
17
|
} catch { /* HTTP status remains authoritative if its diagnostic body breaks. */ }
|
|
18
18
|
finally { await reader.cancel().catch(() => {}); }
|
|
19
|
-
return decodePrefix(bytes);
|
|
19
|
+
return {body:decodePrefix(bytes),complete};
|
|
20
20
|
}
|
|
21
21
|
|
|
22
22
|
/** One credential-free, bounded request. Retain only bounded response evidence. */
|
|
@@ -34,9 +34,10 @@ export async function healthRequest({origin, expected, request, timeoutMs, offse
|
|
|
34
34
|
attempt.cfRay = response.headers.get('cf-ray')?.slice(0,256) ?? null;
|
|
35
35
|
attempt.contentType = response.headers.get('content-type')?.slice(0,256) ?? null;
|
|
36
36
|
if (response.status !== 200 || response.redirected) {
|
|
37
|
-
|
|
37
|
+
const prefix = await bodyPrefix(response);
|
|
38
|
+
attempt.body = prefix.body;
|
|
38
39
|
attempt.errorClass = 'health-http-failed';
|
|
39
|
-
return {attempt,transient:!response.redirected && (response.status === 404 || response.status >= 500 && response.status <= 599)};
|
|
40
|
+
return {attempt,routePropagation:!response.redirected && response.status === 404 && prefix.complete && prefix.body.trim() === 'error code: 1042',transient:!response.redirected && (response.status === 404 || response.status >= 500 && response.status <= 599)};
|
|
40
41
|
}
|
|
41
42
|
let bytes = Buffer.alloc(0);
|
|
42
43
|
try {
|
|
@@ -76,18 +77,20 @@ const MIN_DELAY_MS = 2000, MAX_DELAY_MS = 10000;
|
|
|
76
77
|
|
|
77
78
|
/** The total bound includes requests, body reads and backoff; no request starts at the deadline.
|
|
78
79
|
* Only a transient outcome is retried. Every attempt is recorded, in order, whatever the end. */
|
|
79
|
-
export async function waitHealth({origin,receipt,versionId,expected={sourceSha:receipt.source.sha,fingerprint:receipt.fingerprint,versionId},request,timeoutMs=30000,totalMs=90000,clock=()=>performance.now(),sleep=ms=>new Promise(resolve=>setTimeout(resolve,ms)),onAttempt=()=>{},single=false}) {
|
|
80
|
+
export async function waitHealth({origin,receipt,versionId,expected={sourceSha:receipt.source.sha,fingerprint:receipt.fingerprint,versionId},request,timeoutMs=30000,totalMs=90000,clock=()=>performance.now(),sleep=ms=>new Promise(resolve=>setTimeout(resolve,ms)),onAttempt=()=>{},single=false,freshUpload=false,window}) {
|
|
80
81
|
assert(Number.isFinite(totalMs) && totalMs > 0 && totalMs <= 90000 && Number.isFinite(timeoutMs) && timeoutMs > 0,'invalid-health-bound');
|
|
81
82
|
const start = clock(); const attempts = []; let delay = 1000;
|
|
82
83
|
while (true) {
|
|
83
|
-
const remaining = totalMs - (clock()-start);
|
|
84
|
+
const remaining = Math.min(totalMs - (clock()-start), window?.remaining() ?? Infinity);
|
|
84
85
|
if (remaining <= 0) break;
|
|
85
86
|
const result = await healthRequest({origin,expected,request,timeoutMs:Math.max(1,Math.ceil(Math.min(timeoutMs,remaining))),offsetMs:Math.round(clock()-start)});
|
|
86
87
|
attempts.push(result.attempt); await onAttempt(result.attempt,attempts);
|
|
87
88
|
if (!result.attempt.errorClass) return {ok:true,versionId,attempts};
|
|
88
|
-
//
|
|
89
|
-
|
|
90
|
-
const
|
|
89
|
+
// A newly uploaded workers.dev route can briefly disappear even after its
|
|
90
|
+
// first healthy answer. Only the observed edge 1042 response gets this exception.
|
|
91
|
+
const routePropagation = freshUpload && new URL(origin).protocol === 'https:' && new URL(origin).hostname.endsWith('.workers.dev') && result.routePropagation;
|
|
92
|
+
if (!result.transient || single && result.attempt.errorClass !== 'health-identity-mismatch' && !routePropagation) break;
|
|
93
|
+
const rest = Math.min(totalMs - (clock()-start), window?.remaining() ?? Infinity);
|
|
91
94
|
if (rest <= 0) break;
|
|
92
95
|
await sleep(Math.min(Math.max(delay,MIN_DELAY_MS),rest)); delay = Math.min(delay*2,MAX_DELAY_MS);
|
|
93
96
|
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { readinessAPI } from './readiness-window.mjs';
|
|
1
2
|
import { verifyServiceGrants } from './service-grants.mjs';
|
|
2
3
|
import { assert, stable } from './validation.mjs';
|
|
3
4
|
import { boundedJSON } from './provider.mjs';
|
|
@@ -49,11 +50,13 @@ export async function waitForDeploymentHealth(url, {
|
|
|
49
50
|
/** An unauthenticated GET of a built file; anything but 200 means the browser gets no assets.
|
|
50
51
|
* After an upload (`windowMs`), an edge still serving the previous version answers 404 for
|
|
51
52
|
* the new build's hashed files: 404, 5xx and transport failures are retried within the window. */
|
|
52
|
-
async function servedAsset(origin, path, request, timeoutMs, {windowMs = 0, clock = () => performance.now(), sleep = ms => new Promise(resolve => setTimeout(resolve, ms))} = {}) {
|
|
53
|
+
async function servedAsset(origin, path, request, timeoutMs, {window, windowMs = 0, clock = () => performance.now(), sleep = ms => new Promise(resolve => setTimeout(resolve, ms))} = {}) {
|
|
53
54
|
const start = clock();
|
|
54
55
|
for (;;) {
|
|
55
56
|
let response, failure;
|
|
56
|
-
|
|
57
|
+
const remaining = window?.remaining() ?? timeoutMs;
|
|
58
|
+
assert(remaining > 0, 'asset-readiness-timeout');
|
|
59
|
+
try { response = await request(`${origin}/${path.split('/').map(encodeURIComponent).join('/')}`,{redirect:'manual',signal:AbortSignal.timeout(Math.max(1, Math.ceil(Math.min(timeoutMs,remaining)))),headers:{'Cache-Control':'no-cache'}}); }
|
|
57
60
|
catch { failure = 'asset-transport-failed'; }
|
|
58
61
|
if (response) {
|
|
59
62
|
await response.body?.cancel().catch(() => {});
|
|
@@ -62,7 +65,7 @@ async function servedAsset(origin, path, request, timeoutMs, {windowMs = 0, cloc
|
|
|
62
65
|
if (response.redirected || response.status !== 404 && response.status < 500) throw new Error(failure);
|
|
63
66
|
}
|
|
64
67
|
if (clock() - start + 2000 > windowMs) throw new Error(failure);
|
|
65
|
-
await sleep(2000);
|
|
68
|
+
await sleep(Math.min(2000,window?.remaining() ?? 2000));
|
|
66
69
|
}
|
|
67
70
|
}
|
|
68
71
|
|
|
@@ -71,6 +74,7 @@ async function servedAsset(origin, path, request, timeoutMs, {windowMs = 0, cloc
|
|
|
71
74
|
* With `readiness` (deploy after an upload) it gets the recorded 90-second wait of health-request.mjs.
|
|
72
75
|
* `asset`, a built file's path, is then requested once and must answer 200. */
|
|
73
76
|
export async function verifyHealth({api,plan,receipt,fetch:request=globalThis.fetch,timeoutMs=30000,intervalMs=2000,now,sleep,readiness,asset}) {
|
|
77
|
+
if (readiness?.window) api = readinessAPI(api, readiness.window);
|
|
74
78
|
assert(receipt?.version === 1 && receipt.accountId === api.accountId && receipt.worker === plan.worker,'receipt-target-mismatch');
|
|
75
79
|
await verifyServiceGrants(api, plan);
|
|
76
80
|
const current = await activeWorker(api,plan.worker);
|
|
@@ -85,8 +89,14 @@ export async function verifyHealth({api,plan,receipt,fetch:request=globalThis.fe
|
|
|
85
89
|
const namespaces = await durableNamespaces(api,plan,{requireAll:true});
|
|
86
90
|
assert(stable(namespaces) === stable(receipt.durableObjects),'durable-object-identity-drift');
|
|
87
91
|
for (const item of plan.d1) await migrate(api,resources.d1.find(x => x.binding === item.binding).id,item.migrations,{apply:false});
|
|
88
|
-
|
|
89
|
-
|
|
92
|
+
for (;;) {
|
|
93
|
+
assert(!readiness?.window || readiness.window.remaining() > 0, 'missing-deployed-secret');
|
|
94
|
+
const secrets = await api.request(`/workers/scripts/${plan.worker}/secrets`);
|
|
95
|
+
assert(Array.isArray(secrets) && secrets.every(row => typeof row?.name === 'string' && row.type === 'secret_text'), 'invalid-secret-list');
|
|
96
|
+
if (plan.secrets.every(x => secrets.some(y => y.name === x.binding && y.type === 'secret_text'))) break;
|
|
97
|
+
assert(readiness?.freshUpload && readiness.window?.remaining() > 0, 'missing-deployed-secret');
|
|
98
|
+
await readiness.window.pause();
|
|
99
|
+
}
|
|
90
100
|
let health;
|
|
91
101
|
// A Worker without a public route (reached only through service bindings) has no /health to request.
|
|
92
102
|
if (plan.workersDev === false) health = {ok:true,versionId:current.versionId,route:'none'};
|
|
@@ -111,7 +121,7 @@ export async function verifyHealth({api,plan,receipt,fetch:request=globalThis.fe
|
|
|
111
121
|
assert(body?.ok === true && body.deployment?.sourceSha === receipt.source.sha && body.deployment?.fingerprint === receipt.fingerprint && body.deployment?.versionId === current.versionId,'health-identity-mismatch');
|
|
112
122
|
health = {ok:true,versionId:current.versionId};
|
|
113
123
|
}
|
|
114
|
-
if (asset && origin) health.asset = await servedAsset(origin,asset,request,timeoutMs,readiness ? {windowMs:60000,...(readiness.clock ? {clock:readiness.clock} : {}),...(readiness.sleep ? {sleep:readiness.sleep} : {})} : {});
|
|
124
|
+
if (asset && origin) health.asset = await servedAsset(origin,asset,request,timeoutMs,readiness ? {window:readiness.window,windowMs:60000,...(readiness.clock ? {clock:readiness.clock} : {}),...(readiness.sleep ? {sleep:readiness.sleep} : {})} : {});
|
|
115
125
|
const after = await activeWorker(api,plan.worker);
|
|
116
126
|
assert(after.versionId === current.versionId && after.deploymentId === current.deploymentId && after.etag === current.etag,'deployment-changed-during-health');
|
|
117
127
|
await verifyServiceGrants(api, plan);
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { readinessWindow, rememberReadiness } from './readiness-window.mjs';
|
|
1
2
|
import { deploymentDiagnostics, deployDiagnostic } from './diagnostics.mjs';
|
|
2
3
|
import { execFileSync } from 'node:child_process';
|
|
3
4
|
import { resolve, join } from 'node:path';
|
|
@@ -25,7 +26,7 @@ async function ownerArtifact(root, product) {
|
|
|
25
26
|
}
|
|
26
27
|
|
|
27
28
|
/** Inputs: CLOUDFLARE_ACCOUNT_ID and CLOUDFLARE_API_TOKEN, plus the secrets the declaration names on first deploy. */
|
|
28
|
-
export async function main(argv = process.argv.slice(2), env = process.env, {fetch = globalThis.fetch, cwd = process.cwd(), healthOptions, settle, localOnlyKeys = [], notice = line => console.error(line), onCreated} = {}) {
|
|
29
|
+
export async function main(argv = process.argv.slice(2), env = process.env, {fetch = globalThis.fetch, cwd = process.cwd(), healthOptions, propagation, settle, localOnlyKeys = [], notice = line => console.error(line), onCreated} = {}) {
|
|
29
30
|
let parsed;
|
|
30
31
|
try { parsed = parseArgs({args:argv,allowPositionals:true,strict:true,options:{declaration:{type:'string'},environment:{type:'string'},product:{type:'string',default:''},state:{type:'string'},set:{type:'string'},unset:{type:'string'},outcome:{type:'string'}}}); }
|
|
31
32
|
catch { throw new Error('usage'); }
|
|
@@ -44,6 +45,15 @@ export async function main(argv = process.argv.slice(2), env = process.env, {fet
|
|
|
44
45
|
assert(typeof declaration?.project === 'string','missing-owner-project');
|
|
45
46
|
// Removal reads identity before each object DELETE and may span many pages.
|
|
46
47
|
// Bound each response, not the owner's bucket size; failures retain ownership.
|
|
48
|
+
let requestWindow = propagation?.freshUpload ? propagation.window : undefined;
|
|
49
|
+
const request = fetch;
|
|
50
|
+
fetch = (input, init = {}) => {
|
|
51
|
+
if (!requestWindow?.active) return request(input, init);
|
|
52
|
+
const remaining = requestWindow.remaining();
|
|
53
|
+
assert(remaining > 0, 'deployment-readiness-timeout');
|
|
54
|
+
const deadline = AbortSignal.timeout(Math.max(1, Math.ceil(remaining)));
|
|
55
|
+
return request(input, {...init,signal:init.signal ? AbortSignal.any([init.signal,deadline]) : deadline});
|
|
56
|
+
};
|
|
47
57
|
const api = deploymentDiagnostics(cloudflare({accountId:env.CLOUDFLARE_ACCOUNT_ID,token:env.CLOUDFLARE_API_TOKEN,fetch,...(command === 'remove' ? {maxRequests:Infinity} : {})}),{onCreated});
|
|
48
58
|
const target = await ownerTarget(api,{project:declaration.project,environment:values.environment});
|
|
49
59
|
const statePath = values.state ? resolve(root,values.state) : join(root,'.rer','deploy',`${target.environment}.json`);
|
|
@@ -79,18 +89,28 @@ export async function main(argv = process.argv.slice(2), env = process.env, {fet
|
|
|
79
89
|
const artifact = await ownerArtifact(root,values.product);
|
|
80
90
|
const plan = ownerPlan(target,current,artifact,{localOnlyKeys});
|
|
81
91
|
if (command === 'health') {
|
|
82
|
-
|
|
92
|
+
const readiness = {...(healthOptions?.now ? {clock:healthOptions.now} : {}), ...(healthOptions?.sleep ? {sleep:healthOptions.sleep} : {}),
|
|
93
|
+
...healthOptions?.readiness,single:true,totalMs:30000,
|
|
94
|
+
...(propagation ? {window:propagation.window,freshUpload:propagation.freshUpload && propagation.versionId === state.receipt?.provider.versionId} : {})};
|
|
95
|
+
await ownerHealth({api,target,plan,statePath,fetch,healthOptions:{...healthOptions,readiness}}).catch(error=>{throw api.annotateFailure(error,'health');});
|
|
83
96
|
return {ok:true,worker:target.worker,origin:target.origin};
|
|
84
97
|
}
|
|
85
98
|
// Dispatch is the provider's: on some accounts a new Cron starts only at the account scheduler's next refresh.
|
|
86
99
|
if (plan.crons.length) notice(cronNotice);
|
|
87
100
|
// The fingerprint names every declared secret, retired ones too: an untouched repeat after the claim is a no-op.
|
|
88
101
|
const declaredSecrets = current === declaration ? plan.secrets : ownerPlan(target,declaration,artifact,{localOnlyKeys}).secrets;
|
|
89
|
-
const
|
|
102
|
+
const window = readinessWindow({...(healthOptions?.now ? {clock:healthOptions.now} : {}), ...(healthOptions?.sleep ? {sleep:healthOptions.sleep} : {}), ...healthOptions?.readiness});
|
|
103
|
+
requestWindow = window;
|
|
104
|
+
const {receipt,created,sentSecrets,freshUpload} = await ownerDeploy({api,target,plan,artifact,statePath,env,fetch,healthOptions,readiness:{...healthOptions?.readiness,window},settle,declaredSecrets}).catch(error => {
|
|
90
105
|
api.annotateFailure(error,error.message.startsWith('missing-secret-') ? 'secrets' : undefined);
|
|
91
106
|
throw error;
|
|
92
107
|
});
|
|
93
|
-
|
|
108
|
+
const result = {ok:true,changed:receipt.changed,worker:target.worker,origin:receipt.origin,versionId:receipt.provider.versionId,created,sentSecrets,retiredSecrets,...(state.ownerClaim ? {ownerClaim:state.ownerClaim} : {}),state:statePath};
|
|
109
|
+
const sentTokens = new Map(sentSecrets.map(binding => [binding,env[declaration.secrets.find(item => item.binding === binding)?.environment]]));
|
|
110
|
+
Object.defineProperty(result, 'propagation', {value: {window,freshUpload,sentSecrets,versionId:receipt.provider.versionId,
|
|
111
|
+
matchesToken:(binding,token) => sentTokens.has(binding) && sentTokens.get(binding) === token}});
|
|
112
|
+
rememberReadiness(result);
|
|
113
|
+
return result;
|
|
94
114
|
}
|
|
95
115
|
|
|
96
116
|
/** Prints refusal codes and resource names only; never inputs, tokens or provider bodies. */
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { readinessWindow } from './readiness-window.mjs';
|
|
2
|
+
import { uploadedWorker } from './uploaded-worker.mjs';
|
|
1
3
|
import { ingressBindings } from './container-config.mjs';
|
|
2
4
|
import { mkdir, open, rename, rm, writeFile } from 'node:fs/promises';
|
|
3
5
|
import { dirname } from 'node:path';
|
|
@@ -373,6 +375,8 @@ async function deployLocked({api, target, plan, artifact, statePath, env, fetch,
|
|
|
373
375
|
await listedAfterCreate(api,kind,item,settle);
|
|
374
376
|
}
|
|
375
377
|
if (!exists && !state.owned.worker) { state.owned.worker = {status:'pending'}; await save(); }
|
|
378
|
+
const window = readiness.window ?? readinessWindow({...(healthOptions.now ? {clock:healthOptions.now} : {}), ...(healthOptions.sleep ? {sleep:healthOptions.sleep} : {}), ...readiness});
|
|
379
|
+
readiness = {...readiness,window};
|
|
376
380
|
const upload = `/workers/scripts/${plan.worker}?bindings_inherit=strict`;
|
|
377
381
|
const observed = {...api, async request(path, options) {
|
|
378
382
|
const sending = path === upload && options?.method === 'PUT';
|
|
@@ -387,8 +391,7 @@ async function deployLocked({api, target, plan, artifact, statePath, env, fetch,
|
|
|
387
391
|
// A successful upload creates a Worker only when ownership preflight found
|
|
388
392
|
// it absent. Record it before readback, which can fail after creation.
|
|
389
393
|
if (!exists) api.recordCreated?.(`Worker:${plan.worker}`);
|
|
390
|
-
const active = await
|
|
391
|
-
assert(active && deployedFingerprint(active.settings) === state.pendingUpload.fingerprint, 'uploaded-worker-drift');
|
|
394
|
+
const active = await uploadedWorker({api,worker:plan.worker,upload:result,previous:priorWorker,fingerprint:state.pendingUpload.fingerprint,window});
|
|
392
395
|
state.pendingUpload.provider = {versionId:active.versionId,deploymentId:active.deploymentId,etag:active.etag};
|
|
393
396
|
state.owned.worker = {status:'created'}; await save();
|
|
394
397
|
}
|
|
@@ -399,7 +402,7 @@ async function deployLocked({api, target, plan, artifact, statePath, env, fetch,
|
|
|
399
402
|
onReceipt: async candidate => { if (candidate.changed || !state.receipt) { state.receipt = candidate; delete state.pendingUpload; delete state.pendingSecret; await save(); } },
|
|
400
403
|
// Keep each first-health attempt beside the identity it belongs to.
|
|
401
404
|
onHealth: async candidate => { if (candidate.changed) { state.receipt = candidate; await save(); } }});
|
|
402
|
-
return {receipt, created:create.map(({kind,item}) => `${kind}:${item.name}`), sentSecrets};
|
|
405
|
+
return {receipt, created:create.map(({kind,item}) => `${kind}:${item.name}`), sentSecrets, freshUpload:!exists && receipt.changed};
|
|
403
406
|
}
|
|
404
407
|
|
|
405
408
|
/** Independent read-only health of the last owner deployment recorded in the state file. */
|
|
@@ -37,7 +37,7 @@ export function cloudflare({ accountId, token, fetch: request = globalThis.fetch
|
|
|
37
37
|
assert(typeof token === 'string' && token.trim() && !/[\r\n]/.test(token), 'invalid-cloudflare-api-token');
|
|
38
38
|
let requests = 0;
|
|
39
39
|
// `zone` scope: the zone-level API (/zones/...), for a run site's zone lookup and redirect rule.
|
|
40
|
-
async function envelope(path, { method = 'GET', body, assetToken, zone = false } = {}) {
|
|
40
|
+
async function envelope(path, { method = 'GET', body, assetToken, zone = false, signal: callerSignal } = {}) {
|
|
41
41
|
assert(typeof path === 'string' && (isR2ObjectDelete(path, method) || /^\/[a-z0-9/_?=&.,%-]+$/i.test(path) && !path.includes('..') && !path.split('?')[0].includes('%')), 'invalid-provider-path');
|
|
42
42
|
assert(!zone || /^\/zones(?:[/?]|$)/.test(path), 'invalid-provider-path');
|
|
43
43
|
assert(++requests <= maxRequests, 'provider-request-budget');
|
|
@@ -46,13 +46,17 @@ export function cloudflare({ accountId, token, fetch: request = globalThis.fetch
|
|
|
46
46
|
// Preserve complete text for the CLI's remaining redaction before truncation.
|
|
47
47
|
const redactAuth = text => /\/r2\/buckets\/[^/]+\/objects(?:[/?]|$)/.test(path) ? '[R2 object details omitted]' : /\/d1\/database\/[^/]+\/import$/.test(path) ? '[D1 import details omitted]' : [accountId,token,assetToken].filter(Boolean).flatMap(value=>[value,encodeURIComponent(value),JSON.stringify(value).slice(1,-1)]).sort((a,b)=>b.length-a.length).reduce((value,secret)=>value.split(secret).join('[REDACTED]'),text);
|
|
48
48
|
const transportFailure = cause => recordDeployFailure(new Error('provider-transport-failed'),{output:redactAuth(transportOutput(cause))});
|
|
49
|
-
const
|
|
49
|
+
const timeout = AbortSignal.timeout(timeoutMs);
|
|
50
|
+
const signal = callerSignal ? AbortSignal.any([callerSignal,timeout]) : timeout;
|
|
50
51
|
let response;
|
|
51
52
|
try { response = isR2ObjectDelete(path, method) ? await objectDelete(`/client/v4/accounts/${accountId}${path}`, {headers:{Authorization:`Bearer ${token}`},signal}) : await request(zone ? `https://api.cloudflare.com/client/v4${path}` : `https://api.cloudflare.com/client/v4/accounts/${accountId}${path}`, {
|
|
52
53
|
method, redirect: 'error', signal, headers: { Authorization: `Bearer ${assetToken ?? token}`, ...(body && !(body instanceof FormData) ? { 'Content-Type':'application/json' } : {}) },
|
|
53
54
|
...(body === undefined ? {} : { body: body instanceof FormData ? body : JSON.stringify(body) }),
|
|
54
55
|
}); } catch (cause) { throw transportFailure(cause); }
|
|
55
56
|
const output = response.body ? await boundedText(response,undefined,transportFailure) : '';
|
|
57
|
+
// A successful DELETE may have no response body (including HTTP 200).
|
|
58
|
+
// Nonempty replies and all other methods still require the API envelope.
|
|
59
|
+
if (method === 'DELETE' && response.ok && output === '') return { success: true, result: null };
|
|
56
60
|
let payload;
|
|
57
61
|
try { payload = JSON.parse(output); } catch { if (response.ok) throw new Error('malformed-response'); }
|
|
58
62
|
if (!response.ok || payload?.success === false) {
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
2
|
+
import { assert } from './validation.mjs';
|
|
3
|
+
|
|
4
|
+
// A single, in-memory deadline travels with this upload. It is deliberately not
|
|
5
|
+
// persisted: an old receipt is not evidence of a fresh propagation window.
|
|
6
|
+
export function readinessWindow({ totalMs = 90000, clock = () => performance.now(), sleep = ms => new Promise(resolve => setTimeout(resolve, ms)) } = {}) {
|
|
7
|
+
assert(Number.isFinite(totalMs) && totalMs > 0 && totalMs <= 90000, 'invalid-health-bound');
|
|
8
|
+
let start;
|
|
9
|
+
return {
|
|
10
|
+
clock, sleep,
|
|
11
|
+
get active() { return start !== undefined; },
|
|
12
|
+
start() { start ??= clock(); },
|
|
13
|
+
remaining() { return start === undefined ? totalMs : Math.max(0, totalMs - (clock() - start)); },
|
|
14
|
+
async pause() { const left = this.remaining(); if (left > 0) await sleep(Math.min(2000, left)); },
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// Custom deploy hooks can claim before returning their result. Keep the proof
|
|
19
|
+
// inside their current observation scope, never in a process-global cache.
|
|
20
|
+
const observations = new AsyncLocalStorage();
|
|
21
|
+
export const observeReadiness = run => observations.getStore() ? run() : observations.run(new Map(), run);
|
|
22
|
+
export const rememberReadiness = deployed => observations.getStore()?.set(deployed.origin, deployed);
|
|
23
|
+
export const observedReadiness = origin => observations.getStore()?.get(origin);
|
|
24
|
+
|
|
25
|
+
export function readinessAPI(api, window, failure = 'deployment-readiness-timeout') {
|
|
26
|
+
return {...api, request(path, options = {}) {
|
|
27
|
+
const remaining = window.remaining();
|
|
28
|
+
assert(remaining > 0, failure);
|
|
29
|
+
const deadline = AbortSignal.timeout(Math.max(1, Math.ceil(remaining)));
|
|
30
|
+
return api.request(path, {...options, signal:options.signal ? AbortSignal.any([options.signal,deadline]) : deadline});
|
|
31
|
+
}};
|
|
32
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { readinessAPI } from './readiness-window.mjs';
|
|
2
|
+
import { activeWorker, deployedFingerprint } from './worker.mjs';
|
|
3
|
+
import { assert, uuid } from './validation.mjs';
|
|
4
|
+
|
|
5
|
+
// Poll only the missing fresh Worker or the exact pre-upload version. A new
|
|
6
|
+
// unrelated version is drift, even during propagation; provider errors fail.
|
|
7
|
+
export async function uploadedWorker({ api, worker, upload, previous, fingerprint, window }) {
|
|
8
|
+
const rawVersion = typeof upload?.deployment_id === 'string' ? upload.deployment_id.toLowerCase() : upload?.deployment_id;
|
|
9
|
+
// The legacy upload API also returns the UUID without separators (Wrangler
|
|
10
|
+
// normalizes this field before treating it as its uploaded version ID).
|
|
11
|
+
const versionId = typeof rawVersion === 'string' && /^[a-f0-9]{32}$/i.test(rawVersion) ? rawVersion.replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/, '$1-$2-$3-$4-$5').toLowerCase() : rawVersion;
|
|
12
|
+
if (versionId !== undefined) assert(uuid(versionId), 'invalid-upload-version');
|
|
13
|
+
const bounded = readinessAPI(api, window, 'uploaded-worker-timeout');
|
|
14
|
+
while (window.remaining() > 0) {
|
|
15
|
+
const current = await activeWorker(bounded, worker);
|
|
16
|
+
if (current && (!versionId || current.versionId === versionId) && deployedFingerprint(current.settings) === fingerprint) return current;
|
|
17
|
+
const prior = previous && current?.versionId === previous.versionId && current.deploymentId === previous.deploymentId && current.etag === previous.etag;
|
|
18
|
+
assert(!current || prior || current.versionId === versionId, 'uploaded-worker-drift');
|
|
19
|
+
await window.pause();
|
|
20
|
+
}
|
|
21
|
+
throw new Error('uploaded-worker-timeout');
|
|
22
|
+
}
|