Skip to content

Commit 2212916

Browse files
authored
Deploy cloud app to Cloudflare Workers (#119)
* Deploy cloud app to Cloudflare Workers - Add @cloudflare/vite-plugin and wrangler, configure for CF Workers - Add wrangler.jsonc with Hyperdrive binding and executor.sh custom domain - Add service binding to marketing worker for route proxying - Update vite.config.ts: replace SPA mode with Cloudflare plugin - Update db.ts: use Hyperdrive binding, remove auto-migrations - Update start.ts: add marketing middleware to proxy /, /home, /setup, /_astro - Fix auth handler to use x-forwarded-proto for HTTPS redirect URIs - Remove 1Password plugin from cloud app - Add .env files to .gitignore * Refactor db.ts to idiomatic Effect with scoped resources
1 parent 0f60c08 commit 2212916

10 files changed

Lines changed: 172 additions & 74 deletions

File tree

‎.gitignore‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,4 +49,6 @@ apps/desktop/resources/
4949
.claude/
5050
.nitro/
5151
.output/
52-
.tanstack/
52+
.tanstack/
53+
.env*
54+
!.env.example

‎apps/cloud/package.json‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
"private": true,
55
"type": "module",
66
"dependencies": {
7+
"@cloudflare/vite-plugin": "^1.31.1",
78
"@effect-atom/atom": "^0.5.0",
89
"@effect-atom/atom-react": "^0.5.0",
910
"@effect/platform": "catalog:",
@@ -35,12 +36,15 @@
3536
"@vitejs/plugin-react": "catalog:",
3637
"portless": "^0.10.1",
3738
"typescript": "catalog:",
38-
"vite": "catalog:"
39+
"vite": "catalog:",
40+
"wrangler": "^4.81.0"
3941
},
4042
"scripts": {
4143
"dev": "op run --env-file=.env -- portless run --name executor-cloud vite dev",
4244
"build": "vite build",
43-
"start": "bun ./server.ts",
45+
"preview": "vite preview",
46+
"deploy": "vite build && wrangler deploy",
47+
"cf-typegen": "wrangler types",
4448
"typecheck": "tsc --noEmit"
4549
}
4650
}

‎apps/cloud/src/auth/handlers.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,8 @@ export const CloudAuthPublicHandlers = HttpApiBuilder.group(
3232
Effect.gen(function* () {
3333
const workos = yield* WorkOSAuth;
3434
const req = yield* HttpServerRequest.HttpServerRequest;
35-
const origin = new URL(req.url, `http://${req.headers["host"]}`).origin;
35+
const proto = req.headers["x-forwarded-proto"] ?? "https";
36+
const origin = new URL(req.url, `${proto}://${req.headers["host"]}`).origin;
3637
const url = workos.getAuthorizationUrl(`${origin}${AUTH_PATHS.callback}`);
3738
return HttpServerResponse.redirect(url, { status: 302 });
3839
}),

‎apps/cloud/src/routeTree.gen.ts‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -147,11 +147,10 @@ export const routeTree = rootRouteImport
147147
._addFileTypes<FileRouteTypes>()
148148

149149
import type { getRouter } from './router.tsx'
150-
import type { startInstance } from './start.ts'
150+
import type { createStart } from '@tanstack/react-start'
151151
declare module '@tanstack/react-start' {
152152
interface Register {
153153
ssr: true
154154
router: Awaited<ReturnType<typeof getRouter>>
155-
config: Awaited<ReturnType<typeof startInstance.getOptions>>
156155
}
157156
}

‎apps/cloud/src/services/db.ts‎

Lines changed: 58 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
// ---------------------------------------------------------------------------
2-
// Database service — PGlite for dev, node-postgres for prod
2+
// Database service — Hyperdrive on Cloudflare, node-postgres for local dev
33
// ---------------------------------------------------------------------------
4+
//
5+
// Migrations are run out-of-band (e.g. via a separate script or CI step),
6+
// not at request time — Cloudflare Workers cannot read the filesystem.
47

58
import { Context, Effect, Layer } from "effect";
6-
import { resolve } from "node:path";
79
import * as sharedSchema from "@executor/storage-postgres/schema";
810
import * as cloudSchema from "./schema";
911
import type { DrizzleDb } from "@executor/storage-postgres";
@@ -13,62 +15,77 @@ const schema = { ...sharedSchema, ...cloudSchema };
1315

1416
export type { DrizzleDb };
1517

16-
const MIGRATIONS_DIR = resolve(
17-
import.meta.dirname,
18-
"../../../../packages/core/storage-postgres/drizzle",
18+
// ---------------------------------------------------------------------------
19+
// Connection string resolution
20+
// ---------------------------------------------------------------------------
21+
22+
const resolveHyperdriveUrl = Effect.tryPromise({
23+
try: async () => {
24+
const { env } = await import("cloudflare:workers");
25+
const hyperdrive = (env as any).HYPERDRIVE;
26+
return (hyperdrive?.connectionString as string) ?? null;
27+
},
28+
catch: () => null,
29+
}).pipe(Effect.map((v) => v ?? undefined));
30+
31+
const resolveConnectionString = resolveHyperdriveUrl.pipe(
32+
Effect.map((url) => url ?? (server.DATABASE_URL || undefined)),
1933
);
2034

21-
type DbResource = {
22-
readonly db: DrizzleDb;
23-
readonly close: () => Promise<void>;
24-
};
35+
// ---------------------------------------------------------------------------
36+
// Postgres via node-postgres (used with Hyperdrive or DATABASE_URL)
37+
// ---------------------------------------------------------------------------
2538

26-
const createDbResource = async (): Promise<DbResource> => {
27-
if (server.DATABASE_URL) {
39+
const acquirePostgres = (connectionString: string) =>
40+
Effect.tryPromise(async () => {
2841
const { drizzle } = await import("drizzle-orm/node-postgres");
29-
const { migrate } = await import("drizzle-orm/node-postgres/migrator");
3042
const { Pool } = await import("pg");
31-
const pool = new Pool({ connectionString: server.DATABASE_URL });
32-
const db = drizzle(pool, { schema }) as DrizzleDb;
33-
await migrate(db as any, { migrationsFolder: MIGRATIONS_DIR });
34-
return {
35-
db,
36-
close: () => pool.end(),
37-
};
38-
}
43+
const pool = new Pool({ connectionString });
44+
return { db: drizzle(pool, { schema }) as DrizzleDb, pool };
45+
});
46+
47+
const releasePostgres = ({ pool }: { pool: { end: () => Promise<void> } }) =>
48+
Effect.promise(() => pool.end()).pipe(Effect.orElseSucceed(() => undefined));
3949

50+
// ---------------------------------------------------------------------------
51+
// PGlite — local dev fallback
52+
// ---------------------------------------------------------------------------
53+
54+
const acquirePglite = Effect.tryPromise(async () => {
4055
const { PGlite } = await import("@electric-sql/pglite");
4156
const { drizzle } = await import("drizzle-orm/pglite");
42-
const { migrate } = await import("drizzle-orm/pglite/migrator");
43-
const dataDir = server.PGLITE_DATA_DIR;
44-
const client = new PGlite(dataDir);
45-
const db = drizzle(client, { schema }) as DrizzleDb;
46-
await migrate(db, { migrationsFolder: MIGRATIONS_DIR });
47-
return {
48-
db,
49-
close: async () => {
50-
const closeClient = client.close;
51-
if (closeClient) {
52-
await closeClient.call(client);
53-
}
54-
},
55-
};
56-
};
57+
const client = new PGlite(server.PGLITE_DATA_DIR);
58+
return { db: drizzle(client, { schema }) as DrizzleDb, client };
59+
});
5760

58-
const closeDbResource = (resource: DbResource) =>
59-
Effect.promise(() => resource.close()).pipe(
61+
const releasePglite = ({ client }: { client: { close?: () => Promise<void> } }) =>
62+
Effect.promise(() => client.close?.() ?? Promise.resolve()).pipe(
6063
Effect.orElseSucceed(() => undefined),
6164
);
6265

66+
// ---------------------------------------------------------------------------
67+
// Service
68+
// ---------------------------------------------------------------------------
69+
6370
export class DbService extends Context.Tag("@executor/cloud/DbService")<
6471
DbService,
6572
DrizzleDb
6673
>() {
6774
static Live = Layer.scoped(
6875
this,
69-
Effect.acquireRelease(
70-
Effect.promise(() => createDbResource()),
71-
closeDbResource,
72-
).pipe(Effect.map((resource) => resource.db)),
76+
Effect.gen(function* () {
77+
const connectionString = yield* resolveConnectionString;
78+
79+
if (connectionString) {
80+
const { db } = yield* Effect.acquireRelease(
81+
acquirePostgres(connectionString),
82+
releasePostgres,
83+
);
84+
return db;
85+
}
86+
87+
const { db } = yield* Effect.acquireRelease(acquirePglite, releasePglite);
88+
return db;
89+
}),
7390
);
7491
}

‎apps/cloud/src/start.ts‎

Lines changed: 52 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,57 @@
11
import { createMiddleware, createStart } from "@tanstack/react-start";
22
import { handleApiRequest } from "./api";
33

4+
// ---------------------------------------------------------------------------
5+
// Marketing routes — proxied to the marketing worker via service binding
6+
// ---------------------------------------------------------------------------
7+
8+
const MARKETING_PATHS = ["/home", "/setup", "/api/detect", "/_astro", "/favicon.ico", "/favicon.svg"];
9+
10+
const isMarketingPath = (pathname: string) =>
11+
MARKETING_PATHS.some((p) => pathname === p || pathname.startsWith(`${p}/`));
12+
13+
const getMarketingWorker = async () => {
14+
try {
15+
const { env } = await import("cloudflare:workers");
16+
return (env as any).MARKETING as { fetch: typeof fetch } | undefined;
17+
} catch {
18+
return undefined;
19+
}
20+
};
21+
22+
const marketingMiddleware = createMiddleware({ type: "request" }).server(
23+
async ({ pathname, request, next }) => {
24+
const shouldProxyToMarketing =
25+
isMarketingPath(pathname) ||
26+
(pathname === "/" && !parseCookie(request.headers.get("cookie"), "wos-session"));
27+
28+
if (!shouldProxyToMarketing) return next();
29+
30+
const marketing = await getMarketingWorker();
31+
if (!marketing) return next();
32+
33+
// Rewrite path: if user hits "/" without auth, serve marketing homepage
34+
const url = new URL(request.url);
35+
if (pathname === "/") {
36+
url.pathname = "/";
37+
}
38+
return marketing.fetch(new Request(url, request));
39+
},
40+
);
41+
42+
const parseCookie = (cookieHeader: string | null, name: string): string | null => {
43+
if (!cookieHeader) return null;
44+
const match = cookieHeader
45+
.split(";")
46+
.map((v) => v.trim())
47+
.find((v) => v.startsWith(`${name}=`));
48+
return match ? match.slice(name.length + 1) || null : null;
49+
};
50+
51+
// ---------------------------------------------------------------------------
52+
// API middleware — routes /api/* to the Effect HTTP layer
53+
// ---------------------------------------------------------------------------
54+
455
const apiRequestMiddleware = createMiddleware({ type: "request" }).server(
556
({ pathname, request, next }) => {
657
if (pathname === "/api" || pathname.startsWith("/api/")) {
@@ -13,5 +64,5 @@ const apiRequestMiddleware = createMiddleware({ type: "request" }).server(
1364
);
1465

1566
export const startInstance = createStart(() => ({
16-
requestMiddleware: [apiRequestMiddleware],
67+
requestMiddleware: [marketingMiddleware, apiRequestMiddleware],
1768
}));

‎apps/cloud/vite.config.ts‎

Lines changed: 3 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,15 @@
11
import { defineConfig } from "vite";
2+
import { cloudflare } from "@cloudflare/vite-plugin";
23
import { tanstackStart } from "@tanstack/react-start/plugin/vite";
34
import react from "@vitejs/plugin-react";
45
import tailwindcss from "@tailwindcss/vite";
5-
import { createEnv, Env } from "@executor/env";
6-
7-
const server = {
8-
PORT: Env.numberOr("PORT", 5173),
9-
};
10-
11-
type ViteEnv = Readonly<{
12-
PORT: number;
13-
}>;
14-
15-
const viteEnv = createEnv(server, {
16-
runtimeEnv: process.env,
17-
emptyStringAsUndefined: true,
18-
}) as ViteEnv;
196

207
export default defineConfig({
21-
server: {
22-
port: viteEnv.PORT,
23-
host: "127.0.0.1",
24-
},
258
resolve: { tsconfigPaths: true },
269
plugins: [
2710
tailwindcss(),
28-
tanstackStart({
29-
spa: { enabled: true },
30-
}),
11+
cloudflare({ viteEnvironment: { name: "ssr" }, inspectorPort: false }),
12+
tanstackStart(),
3113
react(),
3214
],
3315
});
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
// Generated by wrangler types (run `bun run cf-typegen` to regenerate)
2+
3+
declare namespace Cloudflare {
4+
interface Env {
5+
HYPERDRIVE: Hyperdrive;
6+
MARKETING: Fetcher;
7+
WORKOS_API_KEY: string;
8+
WORKOS_CLIENT_ID: string;
9+
WORKOS_COOKIE_PASSWORD: string;
10+
ENCRYPTION_KEY: string;
11+
NODE_ENV: string;
12+
}
13+
}
14+
15+
interface Env extends Cloudflare.Env {}

‎apps/cloud/wrangler.jsonc‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
{
2+
"$schema": "node_modules/wrangler/config-schema.json",
3+
"name": "executor-cloud",
4+
"compatibility_date": "2025-04-01",
5+
"compatibility_flags": ["nodejs_compat"],
6+
"main": "@tanstack/react-start/server-entry",
7+
"routes": [
8+
{ "pattern": "executor.sh", "custom_domain": true }
9+
],
10+
"observability": {
11+
"enabled": true
12+
},
13+
"services": [
14+
{
15+
"binding": "MARKETING",
16+
"service": "executor-marketing"
17+
}
18+
],
19+
"hyperdrive": [
20+
{
21+
"binding": "HYPERDRIVE",
22+
"id": "776c27dfec5f47f59343603b35a7b4c2"
23+
}
24+
]
25+
}

‎bun.lock‎

Lines changed: 7 additions & 5 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)