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
34 changes: 34 additions & 0 deletions apps/web/component.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,40 @@ spec:
change:
inputs:
- pnpm-lock.yaml
# The Supabase project and its Hyperdrive config must exist, and the schema
# be applied, before the Worker that reads them deploys: enforced on a push
# to main, advisory on a pull request (which plans and verifies only).
dependsOn:
- component: supabase
mode: enforced
modeRules:
- mode: advisory
when:
triggerRef: github-pull-request
- component: cloudflare-hyperdrive
mode: enforced
modeRules:
- mode: advisory
when:
triggerRef: github-pull-request
- component: db-migrate
mode: enforced
modeRules:
- mode: advisory
when:
triggerRef: github-pull-request
# What the deploy lane renders the Worker's config from (the roots' wiring
# documents) and stores as its Worker secrets. Optional: dev, which no root
# applies to, renders from the fixture, and a verify lane pushes nothing.
optionalSecretEnv:
WIRING_SUPABASE_STAGE: "secret://atomic-crm/atomic-crm/stage/WIRING_SUPABASE"
WIRING_SUPABASE_PROD: "secret://atomic-crm/atomic-crm/prod/WIRING_SUPABASE"
WIRING_CLOUDFLARE_HYPERDRIVE_STAGE: "secret://atomic-crm/atomic-crm/stage/WIRING_CLOUDFLARE_HYPERDRIVE"
WIRING_CLOUDFLARE_HYPERDRIVE_PROD: "secret://atomic-crm/atomic-crm/prod/WIRING_CLOUDFLARE_HYPERDRIVE"
SUPABASE_SERVICE_ROLE_KEY: "secret://atomic-crm/atomic-crm/{{ .environment }}/SUPABASE_SERVICE_ROLE_KEY"
POSTMARK_WEBHOOK_USER: "secret://atomic-crm/atomic-crm/{{ .environment }}/POSTMARK_WEBHOOK_USER"
POSTMARK_WEBHOOK_PASSWORD: "secret://atomic-crm/atomic-crm/{{ .environment }}/POSTMARK_WEBHOOK_PASSWORD"
POSTMARK_WEBHOOK_AUTHORIZED_IPS: "secret://atomic-crm/atomic-crm/{{ .environment }}/POSTMARK_WEBHOOK_AUTHORIZED_IPS"
subscribe:
environments:
- name: dev
Expand Down
71 changes: 42 additions & 29 deletions apps/web/docs/architecture.md
Original file line number Diff line number Diff line change
@@ -1,31 +1,44 @@
# web — architecture

One Worker per environment, `atomic-crm-web-<env>`.

```
browser ──▶ Static Assets (dist/: the React-Admin SPA, hash-routed)
│
├──▶ Supabase project: Auth, PostgREST (the data provider), Storage
│
└──▶ /functions/v1/<name> ──▶ this Worker (worker/index.ts)
├─ users, update_password, delete_note_attachments, postmark
│ └─▶ Supabase admin API (service-role key, a Worker secret)
└─ merge_contacts, mcp
└─▶ Postgres through Hyperdrive (HYPERDRIVE binding)
```

- **The SPA** is upstream's (`src/`), built by Vite. A build inlines the
project's URL and publishable key from the `vars` of the rendered
`wrangler.jsonc` (`build-env.ts`), so the bundle and the Worker always
name the same project.
- **The edge functions** are upstream's `supabase/functions`, in
`worker/functions`, nearly verbatim: `Deno.env.get` and `Deno.serve` come
from a two-function shim (`worker/functions/_shared/deno.ts`) and the
`jsr:`/`npm:` imports are npm packages. The Supabase client's `fetch` sends
`/functions/v1/*` to the page's own origin, so `supabase.functions.invoke`
reaches them unchanged.
- **Postgres** is reached per request (Kysely over `pg` for
`merge_contacts`, one client per query for the MCP server): a Worker may not
reuse a socket another request opened, and Hyperdrive is the pool.
- `run_worker_first` sends only `/functions/*` and `/api/*` to the Worker;
every other path is a file, or `index.html`.
Built by the turbo pipeline from `apps/web` and deployed with wrangler.

| | |
| ------------------- | ---------------------------------- |
| Worker config | `apps/web/wrangler.template.jsonc` |
| Entry | `worker/index.ts` |
| Compatibility date | `2026-10-01` |
| Compatibility flags | `nodejs_compat` |

## Bindings

| Binding | Kind | Source |
| ------------ | ---------------------------- | -------------------------------------------- |
| `HYPERDRIVE` | Hyperdrive (pooled Postgres) | `hyperdrive_id` from `cloudflare-hyperdrive` |
| `ASSETS` | Static assets | `dist` |

Identifiers marked _from_ a component are filled in at deploy time from
that component's published outputs for the environment being deployed.

## Scheduled triggers

- `*/10 * * * *`

## Variables

`SB_PUBLISHABLE_KEY`, `SUPABASE_URL`.

## Wiring

Resolved at deploy time from secrets the infrastructure lanes publish (names only):

- `WIRING_CLOUDFLARE_HYPERDRIVE_PROD` (optional)
- `WIRING_CLOUDFLARE_HYPERDRIVE_STAGE` (optional)
- `WIRING_SUPABASE_PROD` (optional)
- `WIRING_SUPABASE_STAGE` (optional)

## Secrets resolved by the lane (names only)

- `POSTMARK_WEBHOOK_AUTHORIZED_IPS` (optional)
- `POSTMARK_WEBHOOK_PASSWORD` (optional)
- `POSTMARK_WEBHOOK_USER` (optional)
- `SUPABASE_SERVICE_ROLE_KEY` (optional)
6 changes: 4 additions & 2 deletions apps/web/docs/overview.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

The CRM — Marmelab's Atomic CRM single-page app as the Static Assets of a Cloudflare Worker whose own routes are the ported Supabase edge functions, per environment

A Cloudflare Worker with Static Assets, deployed per environment by its CI lane.
A Cloudflare Worker with Static Assets (server rendering plus static files), deployed per environment by its CI lane.

| | |
| ------------ | ------------------------------------------------------------------------------------------------------------------ |
Expand All @@ -13,7 +13,9 @@ A Cloudflare Worker with Static Assets, deployed per environment by its CI lane.

## Depends on

- (none)
- **supabase** — Provisions Supabase projects for stage and prod, points their Auth at the app, and wires the URL and keys into orun secrets
- **cloudflare-hyperdrive** — Provisions Cloudflare Hyperdrive resources for stage and prod Supabase Postgres databases
- **db-migrate** — Applies database migrations to stage and prod Supabase instances

## Depended on by

Expand Down
51 changes: 38 additions & 13 deletions apps/web/docs/runbook.md
Original file line number Diff line number Diff line change
@@ -1,15 +1,40 @@
# web — runbook

| Symptom | Check | Fix |
|---|---|---|
| The deploy's smoke test fails on `/` | `curl -s https://<worker>/ \| grep 'id="root"'` | the build did not produce `dist/`: read the lane's `build-app` step |
| `/api/health` says `"supabase": false` | the rendered `wrangler.jsonc` `vars` | the Supabase root has not applied for this environment, or its `WIRING_SUPABASE` secret is missing: re-run the `supabase` lane |
| `/api/health` says `"admin": false`; inviting a user or resetting a password fails | `wrangler secret list --name atomic-crm-web-<env>` | the deploy found no `SUPABASE_SERVICE_ROLE_KEY`: re-run the `supabase` lane, then this one |
| `/api/health` says `"database": false`; merging contacts fails | the `hyperdrive` block of the rendered config | re-run `cloudflare-hyperdrive`, then this lane |
| Sign-in works but every list is empty | the browser console: PostgREST 401/42501 | the schema is not applied: re-run `db-migrate` |
| `/functions/v1/postmark` answers 503 | — | inbound email is optional: store `POSTMARK_WEBHOOK_USER`, `POSTMARK_WEBHOOK_PASSWORD` and `POSTMARK_WEBHOOK_AUTHORIZED_IPS` as Orun secrets and redeploy |

Local: `pnpm --filter @app/web preview` builds the app and serves it with the
Worker under `wrangler dev` on :8787 (secrets from `.dev.vars`, see
`.dev.vars.example`); `pnpm --filter @app/web dev:demo` runs upstream's
FakeRest demo with no Supabase at all.
## How it runs

Pull requests verify it; a merge to `main` deploys it to `stage`, `prod`.
CI plans what changed (`orun plan --changed`) and runs each lane with `orun run`;
the plan orders a component after everything it depends on.

## Local commands

```bash
pnpm --filter @app/web dev
pnpm --filter @app/web build
pnpm --filter @app/web typecheck
pnpm --filter @app/web lint
pnpm --filter @app/web preview
```

## Verify

After a deploy the lane runs this smoke against the environment it
deployed (`ORUN_ENVIRONMENT`); `DEPLOYED_URL` overrides the URL:

```bash
html=$(curl -sfL "${DEPLOYED_URL}/") && echo "${html}" | grep -q '<div id="root">' && health=$(curl -sf "${DEPLOYED_URL}/api/health") && echo "${health}" | grep -q '"ok":true' && test "$(curl -s -o /dev/null -w '%{http_code}' -X PATCH "${DEPLOYED_URL}/functions/v1/update_password")" = 401
```

## Rollback

Revert the commit on `main`. The next convergence applies the previous desired
state; nothing was changed out of band, so there is nothing else to undo.

## Common failures

- **A `WIRING_*` secret is missing at deploy**: an infrastructure lane upstream
has not applied for this environment yet. Within one convergence the plan
runs it first; on its own, re-run that lane.
- **The smoke fails right after a first deploy**: a new workers.dev route can
answer 4xx for a few seconds and the lane retries. A failure that persists
is a regression in the deployed code.
75 changes: 75 additions & 0 deletions apps/web/worker/cleanup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
// The note-attachments clean-up upstream runs as a database webhook: its
// cleanup_note_attachments() trigger posted each changed or deleted note to
// the delete_note_attachments edge function through pg_net. The database has
// no address for this Worker, so the trigger queues the same payload in
// private.note_attachment_cleanups (packages/db, the outbox migration), and
// the Cron Trigger (wrangler.jsonc) drains it here — the paths chosen by
// upstream's own getPathsToDelete, removed through the same Storage API with
// the service-role key.
import pg from "pg";
import { supabaseAdmin } from "./functions/_shared/supabaseAdmin";
import { Deno, databaseUrl } from "./functions/_shared/deno";
import {
ATTACHMENTS_BUCKET,
getPathsToDelete,
type WebhookPayload,
} from "./functions/delete_note_attachments/index";

/** A row is retried this many times, then left for a person to read. */
export const MAX_ATTEMPTS = 5;
/** Rows per run: a run holds their locks while it calls Storage. */
export const BATCH = 50;

export interface DrainResult {
processed: number;
removed: number;
failed: number;
skipped?: string;
}

type Row = { id: number | string; payload: WebhookPayload };

export async function drainNoteAttachmentCleanups(
client: Pick<pg.Client, "query"> | null = null,
): Promise<DrainResult> {
if (!Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")) {
return { processed: 0, removed: 0, failed: 0, skipped: "no SUPABASE_SERVICE_ROLE_KEY" };
}
const own = client ? null : new pg.Client({ connectionString: databaseUrl() });
const db = client ?? own!;
if (own) await own.connect();
const result: DrainResult = { processed: 0, removed: 0, failed: 0 };
try {
await db.query("begin");
const { rows } = await db.query<Row>(
`select id, payload from private.note_attachment_cleanups
where attempts < $1 order by id limit $2 for update skip locked`,
[MAX_ATTEMPTS, BATCH],
);
for (const row of rows) {
result.processed++;
const paths = getPathsToDelete(row.payload);
if (paths.length > 0) {
const { error } = await supabaseAdmin.storage.from(ATTACHMENTS_BUCKET).remove(paths);
if (error) {
result.failed++;
await db.query(
`update private.note_attachment_cleanups
set attempts = attempts + 1, last_error = $2 where id = $1`,
[row.id, error.message ?? String(error)],
);
continue;
}
result.removed += paths.length;
}
await db.query("delete from private.note_attachment_cleanups where id = $1", [row.id]);
}
await db.query("commit");
return result;
} catch (e) {
await db.query("rollback").catch(() => {});
throw e;
} finally {
if (own) await own.end().catch(() => {});
}
}
6 changes: 3 additions & 3 deletions apps/web/worker/functions/delete_note_attachments/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Deno } from "../_shared/deno";
import { AuthMiddleware } from "../_shared/authentication";
import { supabaseAdmin } from "../_shared/supabaseAdmin";

const ATTACHMENTS_BUCKET =
export const ATTACHMENTS_BUCKET =
Deno.env.get("VITE_ATTACHMENTS_BUCKET") || "attachments";

type NoteAttachment = {
Expand All @@ -15,7 +15,7 @@ type NoteRecord = {
attachments?: NoteAttachment[] | null;
};

type WebhookPayload = {
export type WebhookPayload = {
type?: string | null;
old_record?: NoteRecord | null;
record?: NoteRecord | null;
Expand Down Expand Up @@ -58,7 +58,7 @@ export const handler = Deno.serve(async (req: Request) =>
AuthMiddleware(req, async (req: Request) => deleteNoteAttachments(req)),
);

const getPathsToDelete = (payload: WebhookPayload): string[] => {
export const getPathsToDelete = (payload: WebhookPayload): string[] => {
const oldPaths = extractAttachmentPaths(payload.old_record?.attachments);
const newPaths = extractAttachmentPaths(payload.record?.attachments);

Expand Down
17 changes: 16 additions & 1 deletion apps/web/worker/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,15 @@
// upstream deploys to the Supabase project, as this Worker's own routes at the
// same /functions/v1/<name> paths (supabase.functions.invoke is pointed at
// this origin, src/components/crm/providers/supabase/supabase.ts), and the
// health check the deploy smoke-tests.
// health check the deploy smoke-tests. Its Cron Trigger drains the queue of
// note attachments to delete (cleanup.ts).
import { handler as deleteNoteAttachments } from "./functions/delete_note_attachments/index";
import { handler as mcp } from "./functions/mcp/index";
import { handler as mergeContacts } from "./functions/merge_contacts/index";
import { handler as postmark } from "./functions/postmark/index";
import { handler as updatePassword } from "./functions/update_password/index";
import { handler as users } from "./functions/users/index";
import { drainNoteAttachmentCleanups } from "./cleanup";

type Handler = (req: Request) => Response | Promise<Response>;

Expand Down Expand Up @@ -60,4 +62,17 @@ export default {
if (pathname === "/api/health") return Response.json(health(env));
return env.ASSETS.fetch(req);
},

async scheduled(
_controller: unknown,
env: Env,
ctx: { waitUntil(promise: Promise<unknown>): void },
): Promise<void> {
if (!env.HYPERDRIVE) return;
ctx.waitUntil(
drainNoteAttachmentCleanups().then((r) => {
if (r.failed || r.skipped) console.warn("note attachments clean-up", JSON.stringify(r));
}),
);
},
};
5 changes: 5 additions & 0 deletions apps/web/wrangler.jsonc
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@
"run_worker_first": ["/functions/*", "/api/*"]
},
"observability": { "enabled": true },
// Drains the queue of note attachments to delete (worker/cleanup.ts), which
// upstream's database webhook did through pg_net. One trigger per Worker.
"triggers": {
"crons": ["*/10 * * * *"]
},
// The Supabase project: what the browser signs in to and reads through
// (vite.config.ts inlines both into the build from here), and what the
// functions call. The anon key is the project's publishable key.
Expand Down
5 changes: 5 additions & 0 deletions apps/web/wrangler.template.jsonc
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,11 @@
"run_worker_first": ["/functions/*", "/api/*"]
},
"observability": { "enabled": true },
// Drains the queue of note attachments to delete (worker/cleanup.ts), which
// upstream's database webhook did through pg_net. One trigger per Worker.
"triggers": {
"crons": ["*/10 * * * *"]
},
// The Supabase project: what the browser signs in to and reads through
// (vite.config.ts inlines both into the build from here), and what the
// functions call. The anon key is the project's publishable key.
Expand Down
Loading
Loading