|
| 1 | +import { randomUUID } from "crypto"; |
| 2 | +import { readFile } from "fs/promises"; |
| 3 | +import events from "node:events"; |
| 4 | +import { writeFile } from "node:fs/promises"; |
| 5 | +import path from "path"; |
| 6 | +import { log } from "@cloudflare/cli"; |
| 7 | +import { spinnerWhile } from "@cloudflare/cli/interactive"; |
| 8 | +import chalk from "chalk"; |
| 9 | +import { Miniflare } from "miniflare"; |
| 10 | +import { WebSocket } from "ws"; |
| 11 | +import { createCLIParser } from ".."; |
| 12 | +import { createCommand, createNamespace } from "../core/create-command"; |
| 13 | +import { moduleTypeMimeType } from "../deployment-bundle/create-worker-upload-form"; |
| 14 | +import { |
| 15 | + flipObject, |
| 16 | + ModuleTypeToRuleType, |
| 17 | +} from "../deployment-bundle/module-collection"; |
| 18 | +import { UserError } from "../errors"; |
| 19 | +import { logger } from "../logger"; |
| 20 | +import { getWranglerTmpDir } from "../paths"; |
| 21 | +import type { Config } from "../config"; |
| 22 | +import type { ModuleDefinition } from "miniflare"; |
| 23 | +import type { FormData, FormDataEntryValue } from "undici"; |
| 24 | + |
| 25 | +const mimeTypeModuleType = flipObject(moduleTypeMimeType); |
| 26 | + |
| 27 | +export const checkNamespace = createNamespace({ |
| 28 | + metadata: { |
| 29 | + description: "☑︎ Run checks on your Worker", |
| 30 | + owner: "Workers: Authoring and Testing", |
| 31 | + status: "alpha", |
| 32 | + hidden: true, |
| 33 | + }, |
| 34 | +}); |
| 35 | + |
| 36 | +async function checkStartupHandler( |
| 37 | + { |
| 38 | + outfile, |
| 39 | + args, |
| 40 | + workerBundle, |
| 41 | + pages, |
| 42 | + }: { outfile: string; args?: string; workerBundle?: string; pages?: boolean }, |
| 43 | + { config }: { config: Config } |
| 44 | +) { |
| 45 | + if (workerBundle === undefined) { |
| 46 | + const tmpDir = getWranglerTmpDir(undefined, "startup-profile"); |
| 47 | + workerBundle = path.join(tmpDir.path, "worker.bundle"); |
| 48 | + |
| 49 | + if (config.pages_build_output_dir || pages) { |
| 50 | + log("Pages project detected"); |
| 51 | + log(""); |
| 52 | + } |
| 53 | + |
| 54 | + if (logger.loggerLevel !== "debug") { |
| 55 | + // Hide build logs |
| 56 | + logger.loggerLevel = "error"; |
| 57 | + } |
| 58 | + |
| 59 | + await spinnerWhile({ |
| 60 | + promise: async () => |
| 61 | + await createCLIParser( |
| 62 | + config.pages_build_output_dir || pages |
| 63 | + ? [ |
| 64 | + "pages", |
| 65 | + "functions", |
| 66 | + "build", |
| 67 | + ...(args?.split(" ") ?? []), |
| 68 | + `--outfile=${workerBundle}`, |
| 69 | + ] |
| 70 | + : [ |
| 71 | + "deploy", |
| 72 | + ...(args?.split(" ") ?? []), |
| 73 | + "--dry-run", |
| 74 | + `--outfile=${workerBundle}`, |
| 75 | + ] |
| 76 | + ).parse(), |
| 77 | + startMessage: "Building your Worker", |
| 78 | + endMessage: chalk.green("Worker Built! 🎉"), |
| 79 | + }); |
| 80 | + logger.resetLoggerLevel(); |
| 81 | + } |
| 82 | + const cpuProfileResult = await spinnerWhile({ |
| 83 | + promise: analyseBundle(workerBundle), |
| 84 | + startMessage: "Analysing", |
| 85 | + endMessage: chalk.green("Startup phase analysed"), |
| 86 | + }); |
| 87 | + |
| 88 | + await writeFile(outfile, JSON.stringify(await cpuProfileResult)); |
| 89 | + |
| 90 | + log( |
| 91 | + `CPU Profile written to ${outfile}. Load it into the Chrome DevTools profiler (or directly in VSCode) to view a flamegraph.` |
| 92 | + ); |
| 93 | +} |
| 94 | + |
| 95 | +export const checkStartupCommand = createCommand({ |
| 96 | + args: { |
| 97 | + outfile: { |
| 98 | + describe: "Output file for startup phase cpuprofile", |
| 99 | + type: "string", |
| 100 | + default: "worker-startup.cpuprofile", |
| 101 | + }, |
| 102 | + workerBundle: { |
| 103 | + alias: "worker", |
| 104 | + describe: |
| 105 | + "Path to a prebuilt worker bundle i.e the output of `wrangler deploy --outfile worker.bundle", |
| 106 | + type: "string", |
| 107 | + }, |
| 108 | + pages: { |
| 109 | + describe: "Force this project to be treated as a Pages project", |
| 110 | + type: "boolean", |
| 111 | + }, |
| 112 | + args: { |
| 113 | + describe: |
| 114 | + "Additional arguments passed to `wrangler deploy` or `wrangler pages functions build` e.g. `--no-bundle`", |
| 115 | + type: "string", |
| 116 | + }, |
| 117 | + }, |
| 118 | + validateArgs({ args, workerBundle }) { |
| 119 | + if (workerBundle && args) { |
| 120 | + throw new UserError( |
| 121 | + "`--args` and `--worker` are mutually exclusive—please only specify one" |
| 122 | + ); |
| 123 | + } |
| 124 | + |
| 125 | + if (args?.includes("outfile") || args?.includes("outdir")) { |
| 126 | + throw new UserError( |
| 127 | + "`--args` should not contain `--outfile` or `--outdir`" |
| 128 | + ); |
| 129 | + } |
| 130 | + }, |
| 131 | + metadata: { |
| 132 | + description: "⌛ Profile your Worker's startup performance", |
| 133 | + owner: "Workers: Authoring and Testing", |
| 134 | + status: "alpha", |
| 135 | + }, |
| 136 | + handler: checkStartupHandler, |
| 137 | +}); |
| 138 | + |
| 139 | +async function getEntryValue( |
| 140 | + entry: FormDataEntryValue |
| 141 | +): Promise<Uint8Array<ArrayBuffer> | string> { |
| 142 | + if (entry instanceof Blob) { |
| 143 | + return new Uint8Array(await entry.arrayBuffer()); |
| 144 | + } else { |
| 145 | + return entry as string; |
| 146 | + } |
| 147 | +} |
| 148 | + |
| 149 | +function getModuleType(entry: FormDataEntryValue) { |
| 150 | + if (entry instanceof Blob) { |
| 151 | + return ModuleTypeToRuleType[mimeTypeModuleType[entry.type]]; |
| 152 | + } else { |
| 153 | + return "Text"; |
| 154 | + } |
| 155 | +} |
| 156 | + |
| 157 | +async function convertWorkerBundleToModules( |
| 158 | + workerBundle: FormData |
| 159 | +): Promise<ModuleDefinition[]> { |
| 160 | + return await Promise.all( |
| 161 | + [...workerBundle.entries()].map(async (m) => ({ |
| 162 | + type: getModuleType(m[1]), |
| 163 | + path: m[0], |
| 164 | + contents: await getEntryValue(m[1]), |
| 165 | + })) |
| 166 | + ); |
| 167 | +} |
| 168 | + |
| 169 | +async function parseFormDataFromFile(file: string): Promise<FormData> { |
| 170 | + const bundle = await readFile(file); |
| 171 | + const firstLine = bundle.findIndex((v) => v === 10); |
| 172 | + const boundary = Uint8Array.prototype.slice |
| 173 | + .call(bundle, 2, firstLine) |
| 174 | + .toString(); |
| 175 | + return await new Response(bundle, { |
| 176 | + headers: { |
| 177 | + "Content-Type": "multipart/form-data; boundary=" + boundary, |
| 178 | + }, |
| 179 | + }).formData(); |
| 180 | +} |
| 181 | + |
| 182 | +export async function analyseBundle( |
| 183 | + workerBundle: string | FormData |
| 184 | +): Promise<Record<string, unknown>> { |
| 185 | + if (typeof workerBundle === "string") { |
| 186 | + workerBundle = await parseFormDataFromFile(workerBundle); |
| 187 | + } |
| 188 | + |
| 189 | + const metadata = JSON.parse(workerBundle.get("metadata") as string); |
| 190 | + |
| 191 | + if (!("main_module" in metadata)) { |
| 192 | + throw new UserError( |
| 193 | + "`wrangler check startup` does not support service-worker format Workers. Refer to https://developers.cloudflare.com/workers/reference/migrate-to-module-workers/ for migration guidance." |
| 194 | + ); |
| 195 | + } |
| 196 | + const mf = new Miniflare({ |
| 197 | + name: "profiler", |
| 198 | + compatibilityDate: metadata.compatibility_date, |
| 199 | + compatibilityFlags: metadata.compatibility_flags, |
| 200 | + modulesRoot: "/", |
| 201 | + modules: [ |
| 202 | + { |
| 203 | + type: "ESModule", |
| 204 | + // Make sure the entrypoint path doesn't conflict with a user worker module |
| 205 | + path: randomUUID(), |
| 206 | + contents: /* javascript */ ` |
| 207 | + async function startup() { |
| 208 | + await import("${metadata.main_module}"); |
| 209 | + } |
| 210 | + export default { |
| 211 | + async fetch() { |
| 212 | + await startup() |
| 213 | + return new Response("ok") |
| 214 | + } |
| 215 | + } |
| 216 | + `, |
| 217 | + }, |
| 218 | + ...(await convertWorkerBundleToModules(workerBundle)), |
| 219 | + ], |
| 220 | + inspectorPort: 0, |
| 221 | + }); |
| 222 | + await mf.ready; |
| 223 | + const inspectorUrl = await mf.getInspectorURL(); |
| 224 | + const ws = new WebSocket(new URL("/core:user:profiler", inspectorUrl.href)); |
| 225 | + await events.once(ws, "open"); |
| 226 | + ws.send(JSON.stringify({ id: 1, method: "Profiler.enable", params: {} })); |
| 227 | + ws.send(JSON.stringify({ id: 2, method: "Profiler.start", params: {} })); |
| 228 | + |
| 229 | + const cpuProfileResult = new Promise<Record<string, unknown>>((accept) => { |
| 230 | + ws.addEventListener("message", (e) => { |
| 231 | + const data = JSON.parse(e.data as string); |
| 232 | + if (data.method === "Profiler.stop") { |
| 233 | + void mf.dispose().then(() => accept(data.result.profile)); |
| 234 | + } |
| 235 | + }); |
| 236 | + }); |
| 237 | + |
| 238 | + await (await mf.dispatchFetch("https://example.com")).text(); |
| 239 | + ws.send(JSON.stringify({ id: 3, method: "Profiler.stop", params: {} })); |
| 240 | + |
| 241 | + return cpuProfileResult; |
| 242 | +} |
0 commit comments