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
1 change: 1 addition & 0 deletions specs/epics/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,6 @@ folder is the adoption; the merge creates the epic in the workspace.

| Epic | Cluster | Status | What it is |
|------|---------|--------|------------|
| [`postgres-kysely/`](./postgres-kysely/) | **KY** | In progress (KY0) | Vercel's Postgres + Kysely Next.js Starter, its `db` resolved per request over Hyperdrive to Supabase Postgres and its table applied by db-migrate — and an Orun baseline that instantiates it in one landing (KY2) |

As-built ≠ intent: what shipped lives in each epic's `IMPLEMENTATION-STATUS.md`.
11 changes: 11 additions & 0 deletions specs/epics/postgres-kysely/IMPLEMENTATION-STATUS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# postgres-kysely — implementation status

| Milestone | State | Landed |
|---|---|---|
| KY0 — the spec | ✅ | KY-1 |
| KY1 — the profiles table on Workers and Supabase | planned | KY-2 |
| KY2 — a baseline | planned | KY-3 |

## Departures from the upstream template

Recorded as they land, from KY1 on.
33 changes: 33 additions & 0 deletions specs/epics/postgres-kysely/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# Epic: postgres-kysely (KY)

**Vercel's Postgres + Kysely starter is the Kysely twin of its Postgres + Drizzle starter: one page, one `selectFrom('profiles')`, and a seed that creates the table with Kysely's schema builder on first use. On Cloudflare the socket goes through Hyperdrive to a Supabase Postgres project — postgres-drizzle-starter's data plane — and the code that changes is where the client comes from: upstream's module-level `db` is kept at every call site, resolved to a Kysely client per request from the `HYPERDRIVE` binding, because the Workers runtime refuses to share a socket across requests.**

The port keeps the page, the table component, the refresh button, the Kysely types and the seed rows. The table itself moves into a `packages/db` migration — upstream's lazy `createTable().ifNotExists()` races on a fresh database and needs DDL rights at request time — applied by `db-migrate` with row-level security before the Worker serves; a local database gets the very same files through Kysely's own `Migrator`. It adds the Workers build, tests, the Supabase and Hyperdrive Terraform roots and the deploy contract, and makes the repository an Orun baseline.

## Status

| Field | Value |
|-------|-------|
| Status | In progress — KY0 on main |
| Cluster | **KY** (KY0–KY2) |
| Owner(s) | `apps/web` (the page, `lib/kysely.ts`, `lib/seed.ts`, `scripts/migrate.mjs`) · `packages/db` (the migrations and their runner) · `tests/web`, `tests/db` · `infra/terraform/{supabase,cloudflare-hyperdrive}`, `infra/db-migrate` |
| Builds on | `postgres-drizzle-starter` (the same template family: its Supabase and Hyperdrive roots, migrations, health check and baseline machinery), and through it `lumen` |
| Upstream | [vercel/examples `storage/postgres-kysely`](https://github.com/vercel/examples/tree/main/storage/postgres-kysely) at `de86723` |
| Changes | The client resolution (module-level `POSTGRES_URL` → a Kysely client per request over Hyperdrive, behind upstream's `db`), the table as migrations, the Workers build, tests, two Terraform roots, the deploy contract; page copy says Cloudflare |
| Decisions locked | (1) `db` stays upstream's name and API; a Proxy resolves it per request (WeakMap by the request's ExecutionContext). (2) postgres.js keeps its default type fetch (risk KY-K). (3) The table and RLS are `db-migrate`'s; the page seeds only rows, on an empty table. (4) Local migrations through Kysely's `Migrator` over the same files, its ledger in schema `kysely`. (5) Infra before app on main: supabase → cloudflare-hyperdrive → db-migrate → web, enforced; advisory on pull requests. |
| Shipped as | `baseline-v1`; proven offline (Baseline CI: migrated into a real Postgres and served through the built Worker under `wrangler dev`), deploy gated until a workspace is linked |

## Read order

1. `design.md` — what maps to what, the connection flow, what is out of scope
2. `implementation-plan.md` — the milestones and what "done" means for each
3. `risks-and-open-questions.md` — what could go wrong and what was decided
4. `IMPLEMENTATION-STATUS.md` — what actually shipped (kept distinct from intent)

## Milestones at a glance

| Milestone | What it lands | Done when |
|---|---|---|
| KY0 — the spec | this doc set and the task contracts | merged on `main` |
| KY1 — the profiles table on Workers and Supabase | `apps/web`, `packages/db`, the two Terraform roots, `infra/db-migrate`, `tests/web`, `tests/db` | green; `wrangler dev` seeds and lists the profiles over a migrated database |
| KY2 — a baseline | card, build document, rename, bootstrap tooling, the product's README and context pack, the baseline's tests | a new product goes from nothing to live on stage and prod in one landing; Baseline CI green |
91 changes: 91 additions & 0 deletions specs/epics/postgres-kysely/design.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
# postgres-kysely — design

## 1. What the template is

`lib/kysely.ts` declares the `Database` interface (one `profiles` table:
`Generated<number>` id, name, email, image, a `ColumnType<Date, string |
undefined, never>` createdAt) and a module-level `db = new Kysely<Database>`
over `PostgresJSDialect({ postgres: postgres(POSTGRES_URL, { ssl: 'require' }) })`,
re-exporting Kysely's `sql`. `components/table.tsx` runs
`db.selectFrom('profiles').selectAll().execute()`; on `relation "profiles"
does not exist` it calls `lib/seed.ts` — `db.schema.createTable('profiles')
.ifNotExists()` plus three `` sql`INSERT … ON CONFLICT (email) DO NOTHING`.execute(db) `` —
and selects again. The page is `force-dynamic` (and asks Vercel for
`preferredRegion = 'home'`) and shows the rows with `timeAgo`; a client
button calls `router.refresh()`.

## 2. The mapping (Vercel → Cloudflare + Supabase)

| Vercel primitive the template uses | Here |
|---|---|
| Next.js hosting (dynamic page) | Cloudflare Workers + Static Assets; the Worker is `@opennextjs/cloudflare`'s output, Next.js 16.3.8 |
| Vercel Postgres (`POSTGRES_URL` with `ssl: 'require'`) | Supabase Postgres through Cloudflare Hyperdrive: `postgres(env.HYPERDRIVE.connectionString, { max: 5, prepare: false })` under Kysely's `PostgresJSDialect`, or `postgres(POSTGRES_URL, { ssl: 'require' })` without a Cloudflare context |
| A module-level `db` | The same `db`, a Proxy: every property read resolves to the current request's Kysely client, kept in a `WeakMap` against `getCloudflareContext().ctx` (the request's ExecutionContext). Call sites are upstream's (risk KY-A) |
| The page creates the table on its first request | `infra/db-migrate` applies `packages/db/src/migrations` — `010_profiles` (upstream's Kysely DDL, compiled), `020_row_level_security` — per environment, after the project and the Hyperdrive config exist and before the Worker deploys; the page seeds only the rows, on an empty table (risk KY-B) |
| (no local migrations: the page made the table) | `pnpm --filter @app/web db:migrate`: Kysely's `Migrator` over the same files, its ledger in schema `kysely` |
| `preferredRegion = 'home'` | Dropped: Vercel's function-region hint. A Worker runs near its visitor and Hyperdrive pools near the database |
| `images.domains` | `images.remotePatterns` for `images.ctfassets.net` (the `domains` key is gone in Next 16) |
| Hard-coded `metadataBase` | `NEXT_PUBLIC_SITE_URL`, set by the Orun build to the environment's Worker URL (or `SITE_URL`) |
| A database created in the dashboard | `infra/terraform/supabase` (one project per environment) + `infra/terraform/cloudflare-hyperdrive` (the config fronting it; wiring `{hyperdrive_id, hyperdrive_name}`) |
| Deploy on push | Orun: `apps/web/component.yaml` renders the config for `$ORUN_ENVIRONMENT`, builds and deploys `postgres-kysely-web-{stage,prod}` on merge to `main` once linked, after `cloudflare-hyperdrive` and `db-migrate` (enforced on main) |

Alternatives rejected:
- **`getDb()` per call** (postgres-drizzle-starter's shape). It changes every
call site; a Proxy over a per-request client keeps upstream's `db` and
`` sql`…`.execute(db) `` exactly as written.
- **Kysely's `PostgresDialect` over `pg`.** The template's point is
`kysely-postgres-js` over postgres.js; the one trap that combination has on
Workers (KY-K) is a connection option, not a reason to change drivers.
- **Keeping the lazy CREATE TABLE.** It races (KY-B) and needs DDL rights per
request; a schema applied before the app serves is what an unattended first
deploy needs.
- **A drizzle-kit-style twin of the SQL for local databases.** Kysely's own
`Migrator` applies the very files db-migrate applies, so there is one copy.

## 3. The connection flow

```
request ──► Worker ──► db (Proxy) ──► per-request Kysely ──► postgres.js reserve ──► Hyperdrive (pooled) ──► Supabase Postgres
▲ no Cloudflare context (next dev / scripts): one POSTGRES_URL client, ssl required
before the first deploy: db-migrate → profiles (+ row-level security)
first render: select → no rows → seed() (INSERT … ON CONFLICT DO NOTHING) → select … where now() is not null
select → "relation does not exist" → "apply the migrations" (never created here)
```

kysely-postgres-js runs every query on a reserved connection
(`sql.reserve()`); postgres.js 3.4 resolves a reserve on a fresh connection
only after its type fetch, so `fetch_types` keeps its default (KY-K).

## 4. The wiring flow

`wrangler.template.jsonc` carries `@@wiring(cloudflare-hyperdrive/__ENV__:hyperdrive_id)@@`
and a `localConnectionString` for wrangler dev (the Supabase CLI's default
Postgres); `pnpm run wire:fixture` renders it from `wiring.fixture.json` into
the COMMITTED `wrangler.jsonc` (the composition checks it exists before the
build, in a fresh checkout), which the dev verify lane uses; the stage and
prod lanes re-render it from `WIRING_CLOUDFLARE_HYPERDRIVE_<ENV>` before they
build. On a push to main the four components converge in one run, per
environment, in the order `supabase → cloudflare-hyperdrive → db-migrate →
web`, each edge `mode: enforced` (advisory on a pull request).

## 5. The repository

```
apps/web the template + the Workers build
lib/kysely.ts upstream's Database types; `db` resolved per request (Hyperdrive first)
lib/seed.ts the three seed rows (no DDL)
scripts/migrate.mjs, app-migrations.mjs `pnpm db:migrate`: Kysely's Migrator over packages/db's files
app/api/health/route.ts the database check the smoke and probes read
wrangler.template.jsonc worker name, nodejs_compat, ASSETS, the HYPERDRIVE binding
packages/db the migrations and Lumen's runner (@saas/db)
infra/terraform/supabase the Supabase project per environment
infra/terraform/cloudflare-hyperdrive the Hyperdrive config per environment
infra/db-migrate applies packages/db's migrations per environment
tests/web vitest: the per-request client, timeAgo, the seeding branch, /api/health, the wrangler render
tests/db vitest: the manifest and the local migrator's list, the table and the racing seed, row-level security (PGlite)
```

## 6. Out of scope

Auth and RLS *policies* (the app does not use Supabase's Data API or Auth, so
RLS is enabled with none), a custom domain (the owner's to attach).
30 changes: 30 additions & 0 deletions specs/epics/postgres-kysely/epic.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# The epic's declaration. metadata.name equals the directory name; metadata.key
# is the task-key prefix this epic reserves (KY → KY-1, KY-2, …). Owner, target
# date and health are the platform's — never written here.
apiVersion: orun.io/v1
kind: Epic
metadata:
name: postgres-kysely
key: KY
spec:
title: "Vercel's Postgres + Kysely Next.js Starter on Cloudflare Workers and Supabase"
summary: "Vercel's Postgres + Kysely starter — one page that reads a profiles table through Kysely and seeds it on first use — runs on Cloudflare Workers + Static Assets with its Postgres a Supabase project reached through Hyperdrive, the table applied by db-migrate before the app serves, inside the Cirrus baseline's repository conventions, and becomes an Orun baseline that takes a new product from nothing to live on stage and prod in one landing."
state: started
milestones:
- name: "KY0 — the spec"
exitCriteria:
- "the repository is born with its intent, CI, tooling and spec index, and this doc set and the task contracts are on main"
tasks: [KY-1]
- name: "KY1 — the profiles table on Workers and Supabase"
exitCriteria:
- "apps/web is the upstream page on Next.js 16.3.8, built by @opennextjs/cloudflare into one Worker with Static Assets; lib/kysely.ts keeps upstream's `db` and `sql`, resolved to a Kysely client per request over the HYPERDRIVE binding"
- "the profiles table (upstream's Kysely schema) and row-level security are packages/db migrations that infra/db-migrate applies before the Worker deploys, after the Supabase project and the Hyperdrive config Terraform creates; the page seeds only the rows"
- "`pnpm typecheck`, `pnpm lint`, `pnpm test` and `pnpm build` are green; `wrangler dev` over the build seeds and lists the three profiles from a migrated database and says the migrations are pending on a blank one"
- "the README says how to run, test and deploy it, and how every Vercel piece maps to Cloudflare and Supabase"
tasks: [KY-2]
- name: "KY2 — a baseline"
exitCriteria:
- "blueprint.yaml (the console card) and repo-blueprint.yaml (the build) take a new product from nothing to live on stage and prod in one landing (supabase → cloudflare-hyperdrive → db-migrate → web), then record it"
- "a product built from it carries the product only, renamed throughout to its own name, repository, Worker, Supabase project and Hyperdrive config, with the upstream template's own directory and demo protected from the rename"
- "Baseline CI is green: contract tests, generated component docs, the blueprint read by the pinned orun, the leak gate, the offline bootstrap with the product's own plans, and the end-to-end tier — migrated into a real Postgres, built, dry-deployed and served, its first-request seed raced and its table shut to the Data API's roles"
tasks: [KY-3]
50 changes: 50 additions & 0 deletions specs/epics/postgres-kysely/implementation-plan.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# postgres-kysely — implementation plan

Three milestones, one pull request each, squash-merged when green.

## KY0 — the spec (KY-1)

The repository is born (intent with the placeholder workspace, Orun CI byte
for byte turso-starter's, the shared TypeScript and ESLint configuration, the
wrangler renderer, the migrations manifest tool, the spec index), then this
doc set and the three task contracts land.

**Done when** the epic and the contracts are on `main`.

## KY1 — the profiles table on Workers and Supabase (KY-2)

1. The template in `apps/web` on Next.js 16.3.8 with `@opennextjs/cloudflare`:
`output: standalone`, the monorepo tracing root, `images.remotePatterns`,
`initOpenNextCloudflareForDev()`.
2. `lib/kysely.ts`: upstream's types, and `db` resolved per request (a Proxy,
a WeakMap keyed by the request's ExecutionContext, Hyperdrive's
connection string, `POSTGRES_URL` without a context), postgres.js's type
fetch left on.
3. The table and row-level security as `packages/db` migrations (010, 020) with
their manifest; `infra/db-migrate` applies them; `lib/seed.ts` keeps only
the INSERTs; `components/table.tsx` seeds an empty table and reads the seed
back with a query Hyperdrive will not cache, and says when the migrations
have not run.
4. `pnpm db:migrate`: Kysely's `Migrator` over the same files.
5. `/api/health`: 200 only with the table migrated and RLS on.
6. `infra/terraform/supabase` and `infra/terraform/cloudflare-hyperdrive`, the
wiring template and its committed fixture render, `apps/web/component.yaml`.
7. `tests/web` and `tests/db` (PGlite).

**Done when** typecheck, lint, test and build are green and `wrangler dev`
over the build seeds and lists the profiles from a migrated database and
reports the migrations pending on a blank one.

## KY2 — a baseline (KY-3)

postgres-drizzle-starter's machinery on this tree: `blueprint.yaml` (the
console card: Cloudflare and Supabase, five brokered keys, the subdomain read
from the connection, no domain asked), `repo-blueprint.yaml` (one landing,
`01-product`, then the record, `02-docs`), `.baseline/` (identity, the
product's README, task contracts), the rename engine (with the upstream
template's directory and demo — which spell this slug — protected), the
bootstrap helpers, the deployment-record renderer, the phase pages, the
context pack, and the baseline's tests.

**Done when** Baseline CI is green on the pull request and on `main`, then
`baseline-v1` is tagged.
Loading
Loading