Skip to content

Commit

Permalink
feat(wrangler): WIP
Browse files Browse the repository at this point in the history
  • Loading branch information
CarmenPopoviciu committed Jul 30, 2024
1 parent 81d57c4 commit 9a4f07b
Show file tree
Hide file tree
Showing 5 changed files with 78 additions and 8 deletions.
9 changes: 3 additions & 6 deletions packages/wrangler/src/deployment-bundle/entry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,13 +55,10 @@ export async function getEntry(
? path.resolve(config.site?.["entry-point"])
: // site.entry-point could be a directory
path.resolve(config.site?.["entry-point"], "index.js");
} else if (
args.legacyAssets ||
config.legacy_assets ||
args.experimentalAssets ||
config.experimental_assets
) {
} else if (args.legacyAssets || config.legacy_assets) {
file = path.resolve(getBasePath(), "templates/no-op-worker.js");
} else if (args.experimentalAssets || config.experimental_assets) {
file = path.resolve(getBasePath(), "templates/no-op-assets-worker.ts");
} else {
throw new UserError(
`Missing entry-point: The entry-point should be specified via the command line (e.g. \`wrangler ${command} path/to/script\`) or the \`main\` config field.`
Expand Down
3 changes: 3 additions & 0 deletions packages/wrangler/src/dev.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -877,6 +877,7 @@ export async function startDev(args: StartDevOptions) {
}
legacyAssetPaths={legacyAssetPaths}
legacyAssetsConfig={configParam.legacy_assets}
experimentalAssets={experimentalAssets}
initialPort={
args.port ?? configParam.dev.port ?? (await getLocalPort())
}
Expand Down Expand Up @@ -1039,6 +1040,8 @@ export async function startApiDev(args: StartDevOptions) {
args.accountId ?? configParam.account_id ?? getAccountFromCache()?.id,
legacyAssetPaths: legacyAssetPaths,
legacyAssetsConfig: configParam.legacy_assets,
// TODO @Carmen can/should we pass this via configParam?
experimentalAssets: undefined,
//port can be 0, which means to use a random port
initialPort: args.port ?? configParam.dev.port ?? (await getLocalPort()),
initialIp: args.ip ?? configParam.dev.ip,
Expand Down
3 changes: 3 additions & 0 deletions packages/wrangler/src/dev/local.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import assert from "node:assert";
import chalk from "chalk";
import { useEffect, useRef } from "react";
import onExit from "signal-exit";
import { ExperimentalAssets } from "../config/environment";
import { registerWorker } from "../dev-registry";
import { logger } from "../logger";
import { DEFAULT_WORKER_NAME, MiniflareServer } from "./miniflare";
Expand Down Expand Up @@ -31,6 +32,7 @@ export interface LocalProps {
bindings: CfWorkerInit["bindings"];
workerDefinitions: WorkerRegistry | undefined;
legacyAssetPaths: LegacyAssetPaths | undefined;
experimentalAssets: ExperimentalAssets | undefined;
initialPort: number | undefined;
initialIp: string;
rules: Config["rules"];
Expand Down Expand Up @@ -90,6 +92,7 @@ export async function localPropsToConfigBundle(
bindings: props.bindings,
workerDefinitions: props.workerDefinitions,
legacyAssetPaths: props.legacyAssetPaths,
experimentalAssets: props.experimentalAssets,
initialPort: props.initialPort,
initialIp: props.initialIp,
rules: props.rules,
Expand Down
40 changes: 38 additions & 2 deletions packages/wrangler/src/dev/miniflare.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import assert from "node:assert";
import { randomUUID } from "node:crypto";
import path from "node:path";
import path, { resolve } from "node:path";
import * as esmLexer from "es-module-lexer";
import {
CoreHeaders,
Expand All @@ -16,6 +16,7 @@ import {
EXTERNAL_AI_WORKER_NAME,
EXTERNAL_AI_WORKER_SCRIPT,
} from "../ai/fetcher";
import { ExperimentalAssets } from "../config/environment";
import { ModuleTypeToRuleType } from "../deployment-bundle/module-collection";
import { withSourceURLs } from "../deployment-bundle/source-url";
import { UserError } from "../errors";
Expand Down Expand Up @@ -172,6 +173,7 @@ export interface ConfigBundle {
bindings: CfWorkerInit["bindings"];
workerDefinitions: WorkerRegistry | undefined;
legacyAssetPaths: LegacyAssetPaths | undefined;
experimentalAssets: ExperimentalAssets | undefined;
initialPort: Port;
initialIp: string;
rules: Config["rules"];
Expand Down Expand Up @@ -374,7 +376,7 @@ type MiniflareBindingsConfig = Pick<
| "services"
| "serviceBindings"
> &
Partial<Pick<ConfigBundle, "format" | "bundle">>;
Partial<Pick<ConfigBundle, "format" | "bundle" | "experimentalAssets">>;

// TODO(someday): would be nice to type these methods more, can we export types for
// each plugin options schema and use those
Expand Down Expand Up @@ -408,7 +410,9 @@ export function buildMiniflareBindingOptions(config: MiniflareBindingsConfig): {
// Setup service bindings to external services
const serviceBindings: NonNullable<WorkerOptions["serviceBindings"]> = {
...config.serviceBindings,
...(config.experimentalAssets ? { ASSET_SERVER: "asset-server" } : {}),
};

const notFoundServices = new Set<string>();
for (const service of config.services ?? []) {
if (service.service === config.name) {
Expand Down Expand Up @@ -837,6 +841,32 @@ export async function buildMiniflareOptions(
}
}

// TODO @Carmen can we read the toml config instead?
const assetServerWorker: WorkerOptions | undefined = config.experimentalAssets
? {
name: "asset-server",
compatibilityDate: "2024-01-01",
compatibilityFlags: ["nodejs_compat"],
modulesRoot: resolve(
"../../packages/workers-shared/asset-server-worker/src/index.ts"
),
modules: [
{
type: "ESModule",
path: resolve(
"../../packages/workers-shared/asset-server-worker/src/index.ts"
),
},
],
unsafeDirectSockets: [
{
host: "127.0.0.1",
port: 0,
},
],
}
: undefined;

const upstream =
typeof config.localUpstream === "string"
? `${config.upstreamProtocol}://${config.localUpstream}`
Expand Down Expand Up @@ -879,6 +909,9 @@ export async function buildMiniflareOptions(
proxy: true,
})),
},
...(config.experimentalAssets
? [assetServerWorker as WorkerOptions]
: []),
...externalWorkers,
],
};
Expand Down Expand Up @@ -947,9 +980,11 @@ export class MiniflareServer extends TypedEventTarget<MiniflareServerEventMap> {
config,
this.#proxyToUserWorkerAuthenticationSecret
);

if (opts?.signal?.aborted) {
return;
}

if (this.#mf === undefined) {
this.#mf = new Miniflare(options);
} else {
Expand Down Expand Up @@ -981,6 +1016,7 @@ export class MiniflareServer extends TypedEventTarget<MiniflareServerEventMap> {
this.dispatchEvent(new ErrorEvent("error", { error }));
}
}

onBundleUpdate(config: ConfigBundle, opts?: Abortable): Promise<void> {
return this.#mutex.runWith(() => this.#onBundleUpdate(config, opts));
}
Expand Down
31 changes: 31 additions & 0 deletions packages/wrangler/templates/no-op-assets-worker.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/**
* This Worker is used as a default entry-point for Assets-only
* Workers. It proxies the request directly on to the Asset Sever
* Worker service binding.
*
* In an Assets-only Workers world, we want to enable users
* to deploy a Worker with Assets without ever having to provide
* a User Worker.
*
* ```bash
* wrangler dev --experimental-assets dist
* wrangler deploy --experimental-assets dist
* ```
*
* ```toml
* name = "assets-only-worker"
* compatibility_date = "2024-01-01"
* ```
*
* Without a user-defined Worker, which usually serves as the entry
* point in the bundling process, wrangler needs to default to some
* other entry-point Worker for all intents and purposes. This is what
* this Worker is.
*/

export default {
async fetch(request: Request, env) {
const response = await env.ASSET_SERVER.fetch(request.url, request);
return new Response(response.body, response);
},
};

0 comments on commit 9a4f07b

Please sign in to comment.