Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 58 additions & 28 deletions packages/alchemy/src/Cloudflare/Logs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,30 @@ export const CloudflareLogs = Effect.gen(function* () {
const createScriptTail = yield* workers.createScriptTail;
const deleteScriptTail = yield* workers.deleteScriptTail;

/**
* The telemetry query needs the `workers_observability:read` OAuth scope.
* A token minted by an older `alchemy login` (before the scope joined the
* defaults) keeps its original grants forever, so the query fails with a
* bare `Unauthorized`/`Forbidden` even though a fresh login would work —
* explain the fix instead of surfacing the raw tag.
*/
const explainMissingObservabilityScope = <A, R>(
effect: Effect.Effect<A, workers.QueryObservabilityTelemetryError, R>,
): Effect.Effect<A, workers.QueryObservabilityTelemetryError, R> =>
effect.pipe(
Effect.catchTag("Unauthorized", () =>
Effect.die(
new Error(
"Cloudflare rejected the observability telemetry query (Unauthorized). " +
'Your stored credentials are likely missing the "workers_observability:read" scope — ' +
"OAuth tokens keep the scopes they were minted with, so tokens from an older " +
"`alchemy login` won't have it. Run `alchemy login` again to mint a token with " +
"the current default scopes, or use an API token that grants Workers Observability read access.",
),
),
),
);

const queryLogs = (opts: {
accountId: string;
filters: TelemetryFilter[];
Expand All @@ -88,30 +112,34 @@ export const CloudflareLogs = Effect.gen(function* () {
const limit = opts.options.limit ?? 100;

if (opts.options.since) {
const response = yield* queryTelemetry({
const response = yield* explainMissingObservabilityScope(
queryTelemetry({
accountId: opts.accountId,
queryId: "events",
view: "events",
timeframe: { from: opts.options.since.getTime(), to: now },
limit,
parameters: {
filters: opts.filters,
// orderBy: { value: "timestamp", order: "desc" },
},
}),
);
return parseEvents(response);
}

const response = yield* explainMissingObservabilityScope(
queryTelemetry({
accountId: opts.accountId,
queryId: "events",
view: "events",
timeframe: { from: opts.options.since.getTime(), to: now },
timeframe: { from: now - DEFAULT_LOOKBACK_MS, to: now },
limit,
parameters: {
filters: opts.filters,
// orderBy: { value: "timestamp", order: "desc" },
},
});
return parseEvents(response);
}

const response = yield* queryTelemetry({
accountId: opts.accountId,
queryId: "events",
view: "events",
timeframe: { from: now - DEFAULT_LOOKBACK_MS, to: now },
limit,
parameters: {
filters: opts.filters,
},
});
}),
);

return parseEvents(response);
});
Expand Down Expand Up @@ -207,17 +235,19 @@ export const CloudflareLogs = Effect.gen(function* () {
yield* Effect.sleep("2 seconds");
const now = Date.now();

const response = yield* queryTelemetry({
accountId: opts.accountId,
queryId: "events",
view: "events",
timeframe: { from: since, to: now },
limit: 100,
parameters: {
filters: opts.filters,
orderBy: { value: "timestamp", order: "asc" },
},
});
const response = yield* explainMissingObservabilityScope(
queryTelemetry({
accountId: opts.accountId,
queryId: "events",
view: "events",
timeframe: { from: since, to: now },
limit: 100,
parameters: {
filters: opts.filters,
orderBy: { value: "timestamp", order: "asc" },
},
}),
);

const lines = parseEvents(response);
const nextSince =
Expand Down
101 changes: 89 additions & 12 deletions packages/alchemy/src/Cloudflare/Website/StaticSite.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,11 @@ import * as Command from "../../Command/index.ts";
import type { Input, InputProps } from "../../Input.ts";
import * as Namespace from "../../Namespace.ts";
import * as Output from "../../Output.ts";
import { effectClass } from "../../Util/effect.ts";
import {
effectClass,
isYieldableEffectLike,
type YieldableEffectLike,
} from "../../Util/effect.ts";
import { asEffect } from "../../Util/types.ts";
import type { Providers } from "../Providers.ts";
import type { AssetsConfig } from "../Workers/Assets.ts";
Expand Down Expand Up @@ -175,6 +179,25 @@ type StaticSiteWorker<Bindings extends WorkerBindingProps> = Worker<{
* });
* ```
*
* @example Rebuilding when a sibling workspace package changes
* The default scope only hashes files under `cwd` (plus the nearest
* lockfile), so edits to a sibling workspace package the app imports do
* not retrigger the build on their own. Add the sibling's sources with a
* `../` include glob — and keep `lockfile: true`, since providing
* `include` otherwise drops the lockfile from the hash:
* ```typescript
* const site = yield* Cloudflare.Website.StaticSite("Web", {
* cwd: "apps/web",
* command: "npm run build",
* outdir: "dist",
* main: "./src/worker.ts",
* memo: {
* include: ["**\/*", "../../packages/env/src/**"],
* lockfile: true,
* },
* });
* ```
*
* @section Class Form
* Calling `StaticSite` with no arguments returns a constructor you can
* `extend` to declare the Worker as a named class. The class is both
Expand Down Expand Up @@ -241,7 +264,7 @@ const makeStaticSite = <
cwd:
props.dev.cwd ??
(typeof props.cwd === "string" ? props.cwd : undefined),
env: serializeEnv(props.dev.env ?? props.env),
env: yield* serializeEnv(props.dev.env ?? props.env),
}).pipe(
Effect.map((d) =>
Output.map(d.url, (url) => ({
Expand All @@ -258,7 +281,7 @@ const makeStaticSite = <
cwd: props.cwd,
memo: props.memo,
outdir: props.outdir,
env: serializeEnv(props.env),
env: yield* serializeEnv(props.env),
});

// Pure-static sites (neither `main` nor `script`) deploy as
Expand All @@ -281,17 +304,71 @@ const makeStaticSite = <
});
}).pipe(Namespace.push(id));

const serializeEnv = (
/**
* Serialize the site's `env` for the build/dev subprocess. The same record
* doubles as the Worker's binding props, so entries may be plain strings,
* `Redacted` secrets, `effect/Config` values, `Output` references, or
* binding Effects:
*
* - strings and `Redacted` values pass through unchanged
* - `Config` (and any other runnable Effect) is resolved here, at stack
* construction — passing it through unresolved would hand the subprocess
* the JSON-serialized `Config` object (`{"_id":"Config"}`) instead of its
* value (#796)
* - `Output` references resolve at reconcile; the resolved value is
* serialized the same way inline values are (an `Output<object>` must
* reach the subprocess as JSON, not `[object Object]`)
* - binding Effects (`~alchemy/Kind`-marked, e.g. a `WorkerLoader`) have no
* env-var representation and are dropped
* - remaining plain values (`null`, numbers, JSON objects) are stringified
*/
const serializeEnv = Effect.fn(function* (
env: Input<
| WorkerBindingProps
| Record<string, string | Redacted.Redacted<string>>
| undefined
>,
) =>
Object.fromEntries(
Object.entries(env ?? {}).flatMap(([k, v]) => {
if (v === undefined) return [];
if (typeof v === "string" || Redacted.isRedacted(v)) return [[k, v]];
return [[k, JSON.stringify(v)]];
}),
);
) {
const entries: [string, unknown][] = [];
for (const [k, v] of Object.entries(env ?? {})) {
if (v === undefined) continue;
if (typeof v === "string" || Redacted.isRedacted(v)) {
entries.push([k, v]);
} else if (Output.isOutput(v)) {
entries.push([k, Output.map(v, serializeEnvValue)]);
} else if (isYieldableEffectLike(v)) {
const resolved = serializeEnvValue(
yield* asEffect(v as YieldableEffectLike<unknown, unknown, never>).pipe(
Effect.orDie,
),
);
if (resolved === undefined) continue;
entries.push([k, resolved]);
} else if (v !== null && typeof v === "object" && "~alchemy/Kind" in v) {
// A binding Effect (e.g. WorkerLoader) — deploy-time only, nothing to
// expose to the build subprocess.
continue;
} else {
entries.push([k, JSON.stringify(v)]);
}
}
return Object.fromEntries(entries) as Record<
string,
string | Redacted.Redacted<string>
>;
});

/**
* Serialize one resolved env value for the build/dev subprocess: strings and
* `Redacted` pass through, everything else becomes JSON.
*/
const serializeEnvValue = (
value: unknown,
): string | Redacted.Redacted<string> | undefined =>
value === undefined
? undefined
: typeof value === "string"
? value
: Redacted.isRedacted(value)
? (value as Redacted.Redacted<string>)
: JSON.stringify(value);
52 changes: 33 additions & 19 deletions packages/alchemy/src/Cloudflare/Website/Vite.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,28 +47,34 @@ export interface ViteProps<Bindings extends WorkerBindingProps = {}>
* ```
*
* @section SSR Frameworks
* For SSR frameworks like TanStack Start or SolidStart, enable
* `nodejs_compat` so the server bundle can use Node.js APIs.
* SSR frameworks like TanStack Start or SolidStart work with a single
* call — the `nodejs_compat` compatibility flag is enabled by default
* so the server bundle can use Node.js APIs.
*
* @example TanStack Start
* ```typescript
* const app = yield* Cloudflare.Website.Vite("TanStackStart", {
* compatibility: {
* flags: ["nodejs_compat"],
* },
* });
* const app = yield* Cloudflare.Website.Vite("TanStackStart");
* ```
*
* @example SolidStart with worker-first routing
* ```typescript
* const app = yield* Cloudflare.Website.Vite("SolidStart", {
* compatibility: {
* flags: ["nodejs_compat"],
* },
* assets: { runWorkerFirst: true },
* });
* ```
*
* @example React Router
* React Router's server build (`virtual:react-router/server-build`) is a
* build manifest with no default export, so it cannot be deployed as the
* Worker entry directly. Point `main` at a module that wraps it with
* `createRequestHandler` (React Router's Cloudflare template ships this
* as `workers/app.ts`):
* ```typescript
* const app = yield* Cloudflare.Website.Vite("ReactRouter", {
* main: "workers/app.ts",
* });
* ```
*
* @section React Server Components
* Frameworks that emit more than one server environment (e.g. React
* Server Components, which split into an `rsc` environment and an `ssr`
Expand All @@ -80,9 +86,6 @@ export interface ViteProps<Bindings extends WorkerBindingProps = {}>
* @example React Router with RSC
* ```typescript
* const app = yield* Cloudflare.Website.Vite("ReactRouterRSC", {
* compatibility: {
* flags: ["nodejs_compat"],
* },
* viteEnvironments: {
* entry: "rsc",
* children: ["ssr"],
Expand Down Expand Up @@ -116,9 +119,6 @@ export interface ViteProps<Bindings extends WorkerBindingProps = {}>
* @example Vue SPA
* ```typescript
* const app = yield* Cloudflare.Website.Vite("Vue", {
* compatibility: {
* flags: ["nodejs_compat"],
* },
* assets: {
* htmlHandling: "auto-trailing-slash",
* notFoundHandling: "single-page-application",
Expand All @@ -140,6 +140,22 @@ export interface ViteProps<Bindings extends WorkerBindingProps = {}>
* });
* ```
*
* @example Rebuilding when a sibling workspace package changes
* The default scope only hashes files under the project root (plus the
* nearest lockfile), so edits to a sibling workspace package the app
* imports do not retrigger the build on their own. Add the sibling's
* sources with a `../` include glob — and keep `lockfile: true`, since
* providing `include` otherwise drops the lockfile from the hash:
* ```typescript
* const site = yield* Cloudflare.Website.Vite("Web", {
* rootDir: "apps/web",
* memo: {
* include: ["**\/*", "../../packages/env/src/**"],
* lockfile: true,
* },
* });
* ```
*
* @section Class Form
* Calling `Vite` with no arguments returns a constructor you can
* `extend` to declare the Worker as a named class. The class is both
Expand All @@ -148,9 +164,7 @@ export interface ViteProps<Bindings extends WorkerBindingProps = {}>
*
* @example Declaring a Worker class
* ```typescript
* class Website extends Cloudflare.Website.Vite<Website>()("Website", {
* compatibility: { flags: ["nodejs_compat"] },
* }) {}
* class Website extends Cloudflare.Website.Vite<Website>()("Website") {}
*
* const site = yield* Website;
* ```
Expand Down
Loading
Loading