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
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
.astro
.vercel
.wrangler/
.dev.vars*
.tanstack
.claude

Expand Down
20 changes: 20 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,26 @@ Feel free to file Issues to suggest features or report bugs. PR's are welcome!

Report suspected vulnerabilities privately by emailing [assmann@hey.com](mailto:assmann@hey.com) or DM to @ccssmnn on X; please avoid filing public issues until I respond.

## Cloudflare hosting

`bun run build:cloudflare` selects the Cloudflare adapter; other builds retain
the existing Vercel or Node adapter. `bun run deploy:cloudflare` deploys staging:
https://tilly-migration.assmann-568.workers.dev.

The Worker preserves app deep links and the Plausible proxy. Jazz workers belong
to one request and stay open until streaming chat ends or is cancelled. Server
credentials stay in Worker secrets; public build settings come from the existing
production environment. Do not commit environment files.

The scheduled handler invokes the existing authenticated notification route.
Staging deliberately has no cron trigger: Vercel still runs the hourly job.
Before production cutover, attach the domain, connect automatic builds and
verify sign-in/chat. Disable the Vercel cron, then enable `0 * * * *` in the
production Worker's triggers. Keep Vercel available for rollback. Never enable
both schedulers together.

written with GPT-6 in Codex (T3 Code)

## License

MIT License - See LICENSE file for details.
Expand Down
11 changes: 10 additions & 1 deletion astro.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,19 @@ import tailwindcss from "@tailwindcss/vite"
import { tanstackRouter } from "@tanstack/router-plugin/vite"

import vercel from "@astrojs/vercel"
import cloudflare from "@astrojs/cloudflare"
import node from "@astrojs/node"

let useNodeAdapter = process.env.ASTRO_ADAPTER === "node"
let runtimeAdapter = useNodeAdapter ? node({ mode: "standalone" }) : vercel()
let runtimeAdapter = useNodeAdapter
? node({ mode: "standalone" })
: process.env.ASTRO_ADAPTER === "cloudflare"
? cloudflare({
imageService: "compile",
platformProxy: { enabled: false },
workerEntryPoint: { path: "./src/server/cloudflare.ts" },
})
: vercel()

// `work` serves the dev server on per-workspace URLs (e.g. over the tailnet)
// and passes them in WORK_URLS.
Expand Down
325 changes: 321 additions & 4 deletions bun.lock

Large diffs are not rendered by default.

9 changes: 7 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@
"test:e2e": "playwright test",
"test:e2e:headed": "playwright test --headed",
"knip": "knip --no-config-hints",
"knip:fix": "knip --fix --no-config-hints"
"knip:fix": "knip --fix --no-config-hints",
"build:cloudflare": "ASTRO_ADAPTER=cloudflare astro build",
"deploy:cloudflare": "bun run build:cloudflare && wrangler deploy --profile carlassmann-holding"
},
"dependencies": {
"@ai-sdk/gateway": "3.0.110",
Expand All @@ -41,6 +43,7 @@
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cmdk": "^1.1.1",
"cojson-transport-ws": "0.20.18",
"date-fns": "^4.1.0",
"date-fns-tz": "^3.2.0",
"hono": "^4.12.17",
Expand All @@ -67,6 +70,7 @@
},
"devDependencies": {
"@astrojs/check": "^0.9.9",
"@astrojs/cloudflare": "^12",
"@astrojs/node": "^9.5.5",
"@astrojs/react": "^4.4.2",
"@astrojs/ts-plugin": "^1.10.7",
Expand Down Expand Up @@ -114,6 +118,7 @@
"vitest": "^4.1.5",
"workbox-precaching": "^7.4.1",
"workbox-routing": "^7.4.1",
"workbox-strategies": "^7.4.1"
"workbox-strategies": "^7.4.1",
"wrangler": "^4.165.0"
}
}
4 changes: 4 additions & 0 deletions public/.assetsignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
_worker.js
_routes.json
_redirects
_headers
61 changes: 61 additions & 0 deletions src/server/cloudflare.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import "jazz-tools/load-edge-wasm"
import { createExports as createAstroExports } from "@astrojs/cloudflare/entrypoints/server.js"
import type { SSRManifest } from "astro"
import { CRON_SECRET } from "astro:env/server"
import { cronDeliveryApp } from "./features/push"
import { runWithRequestWorkers } from "./lib/request-workers"

export { createExports }

type WorkerFetch = ReturnType<typeof createAstroExports>["default"]["fetch"]

function createExports(manifest: SSRManifest) {
let astro = createAstroExports(manifest).default
let fetch: WorkerFetch = async (request, environment, context) => {
let url = new URL(request.url)
if (url.pathname === "/app" || url.pathname.startsWith("/app/")) {
url.pathname = "/app/"
return environment.ASSETS.fetch(url.href)
}
if (
url.pathname.startsWith("/plausible/") ||
url.pathname === "/api/event"
) {
let originalHost = url.host
url.host = "plausible.io"
url.protocol = "https:"
url.pathname = url.pathname.replace(/^\/plausible\//, "/")
let forwarded = new Request(url, {
method: request.method,
headers: Object.fromEntries(request.headers),
body:
request.method === "GET" || request.method === "HEAD"
? undefined
: await request.arrayBuffer(),
})
forwarded.headers.delete("cookie")
forwarded.headers.delete("authorization")
forwarded.headers.delete("host")
forwarded.headers.delete("X-Forwarded-For")
forwarded.headers.set("X-Forwarded-Host", originalHost)
let clientAddress = request.headers.get("CF-Connecting-IP")
if (clientAddress) forwarded.headers.set("X-Forwarded-For", clientAddress)
return globalThis.fetch(new Request(forwarded, { redirect: "manual" }))
}
return runWithRequestWorkers(
() => astro.fetch(request, environment, context),
task => context.waitUntil(task),
)
}
async function scheduled() {
let response = await runWithRequestWorkers(async () =>
cronDeliveryApp.request("https://tilly.social/deliver-notifications", {
headers: { authorization: `Bearer ${CRON_SECRET}` },
}),
)
await response.text()
if (!response.ok)
throw new Error(`Notification job failed: ${response.status}`)
}
return { default: { fetch, scheduled } }
}
13 changes: 8 additions & 5 deletions src/server/features/chat/handlers/chat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { streamSSE } from "hono/streaming"
import { authMiddleware, requireAuth, requirePlus } from "#server/features/auth"
import { errorToStatus } from "#server/lib/errors"
import { processChatMessage } from "../operations/process-chat-message"
import { runWithRequestWorkerTask } from "#server/lib/request-workers"

export { chatMessagesApp }

Expand All @@ -18,11 +19,13 @@ let chatMessagesApp = new Hono()

return result.match({
ok: ({ generate }) =>
streamSSE(c, async stream => {
await stream.writeSSE({ data: "generation-started" })
await generate()
await stream.writeSSE({ data: "generation-finished" })
}),
streamSSE(c, stream =>
runWithRequestWorkerTask(async () => {
await stream.writeSSE({ data: "generation-started" })
await generate()
await stream.writeSSE({ data: "generation-finished" })
}),
),
err: e => c.json({ error: e.message, code: e._tag }, errorToStatus(e)),
})
})
129 changes: 129 additions & 0 deletions src/server/lib/request-workers.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
import { expect, test } from "vitest"
import {
requestWorkers,
runWithRequestWorkers,
runWithRequestWorkerTask,
} from "./request-workers"

test("streaming keeps workers until the body ends, then releases them", async () => {
let events: string[] = []
let response = await runWithRequestWorkers(async () => {
requestWorkers.getStore()?.cleanups.add(async () => {
events.push("closed")
})
return new Response("streamed chat")
})
events.push("response received")
let body = await response.text()
expect({ body, events }).toMatchInlineSnapshot(`
{
"body": "streamed chat",
"events": [
"response received",
"closed",
],
}
`)
})

test("cancellation releases workers and cancels the upstream body", async () => {
let events: string[] = []
let response = await runWithRequestWorkers(async () => {
requestWorkers.getStore()?.cleanups.add(async () => {
events.push("closed")
})
return new Response(
new ReadableStream({
cancel() {
events.push("upstream cancelled")
},
}),
)
})
await response.body?.cancel()
expect(events).toMatchInlineSnapshot(`
[
"upstream cancelled",
"closed",
]
`)
})

test("failed requests release workers", async () => {
let events: string[] = []
await expect(
runWithRequestWorkers(async () => {
requestWorkers.getStore()?.cleanups.add(async () => {
events.push("closed")
})
throw new Error("request failed")
}),
).rejects.toThrow("request failed")
expect(events).toMatchInlineSnapshot(`
[
"closed",
]
`)
})

test("overlapping requests keep their worker scopes separate", async () => {
let events: string[] = []
let first = await runWithRequestWorkers(async () => {
requestWorkers.getStore()?.cleanups.add(async () => {
events.push("first closed")
})
return new Response("first")
})
let second = await runWithRequestWorkers(async () => {
requestWorkers.getStore()?.cleanups.add(async () => {
events.push("second closed")
})
return new Response("second")
})
await second.text()
events.push("second consumed")
await first.text()
expect(events).toMatchInlineSnapshot(`
[
"second closed",
"second consumed",
"first closed",
]
`)
})

test("disconnect waits for generation to finish before closing workers", async () => {
let events: string[] = []
let finishGeneration = () => {}
let generation = new Promise<void>(resolve => {
finishGeneration = resolve
})
let pending: Promise<unknown>[] = []
let response = await runWithRequestWorkers(
async () => {
requestWorkers.getStore()?.cleanups.add(async () => {
events.push("closed")
})
void runWithRequestWorkerTask(async () => {
await generation
events.push("generation finished")
})
return new Response(new ReadableStream())
},
task => {
pending.push(task)
},
)
let cancelled = response.body?.cancel()
events.push("disconnected")
finishGeneration()
await cancelled
await Promise.all(pending)
expect(events).toMatchInlineSnapshot(`
[
"disconnected",
"generation finished",
"closed",
]
`)
})
Loading
Loading