Skip to content

Canvix — Free & open-source graphic design tool. A community-built Canva alternative with a drag-and-drop editor, templates, shapes, text, images & one-click export. Works on desktop, tablet & mobile.

fix(v0.10.1): presence P2002 storm + 30s function hangs

Ashiq Hussain Mir734b666894dd
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1b04446..0b5f102 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -3,6 +3,46 @@
All notable changes to Canvix will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
+## [0.10.1] — 2026-10-29
+
+Production hotfix: the presence P2002 storm + 30-second function hangs.
+Full analysis: `research/PRESENCE-P2002-POSTMORTEM.md`.
+
+### Fixed
+- **Presence P2002 on every heartbeat** — `Presence` had a primary key
+ on the participant id alone, but identity is per-browser and shared
+ across designs; a second open design collided with the first on every
+ heartbeat (~15 s) and cursor update. Migration `0004` makes the PK
+ `(designId, id)` — one browser can now be present in many designs —
+ and the heartbeat route falls back to a plain update on a
+ concurrent-create P2002 instead of 502ing.
+- **Functions running to exactly 30,000 ms** — the pg pool had no
+ acquisition timeout and no keepAlive, so one stale pooled connection
+ (pooler idle-drop without FIN) hung every request sharing the instance
+ until the platform killed it at `maxDuration`. The pool now fails fast
+ (`connectionTimeoutMillis 10 s`, `idleTimeoutMillis 30 s`, TCP
+ keepAlive); the SSE stream closes cleanly when a tick wedges >8 s and
+ self-recycles at 240 s (< the 300 s ceiling); a `retry: 1500` hint
+ makes the client's reconnect invisible.
+- **Duplicate events on retried flushes** (latent) — the v0.10 client
+ retains and retries failed batches; a flush killed mid-batch could
+ re-insert its persisted prefix. `DesignEvent.eventId` is now stored
+ with a unique `(designId, eventId)` index and flushes insert via one
+ idempotent `createMany({ skipDuplicates: true })` — retries are exact
+ no-ops, and a flush costs one pooler round-trip instead of up to
+ twenty.
+
+### Verification
+- Migration 0004 applied to production (composite PK + eventId dedupe
+ verified in `information_schema`); 267/267 tests; tsc + eslint clean.
+- Live probe extended to **18 checks** — all green against the real
+ database, including the incident regressions (one pid heartbeating
+ into two designs; a replayed batch inserting zero duplicates; each
+ op streaming exactly once). Zero `[collab/presence]` errors in the
+ server log afterwards.
+- Cloudflare 2.14 MB gz / Netlify 19.6 MB zip — unchanged, within all
+ free-tier limits.
+
## [0.10.0] — 2026-10-29
The "no lost work, ever" release: offline and concurrent edits merge
diff --git a/package.json b/package.json
index 9dec303..571769d 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "canvix",
- "version": "0.10.0",
+ "version": "0.10.1",
"private": false,
"description": "Canvix — free & open-source graphic design tool. A community-built Canva alternative.",
"scripts": {
diff --git a/prisma/migrations/0004_presence_scope_event_dedup/migration.sql b/prisma/migrations/0004_presence_scope_event_dedup/migration.sql
new file mode 100644
index 0000000..e76a082
--- /dev/null
+++ b/prisma/migrations/0004_presence_scope_event_dedup/migration.sql
@@ -0,0 +1,20 @@
+-- v0.10.1 — production incident 2026-10-29 remediation.
+--
+-- 1) Presence: the primary key was (id) alone — the participant id — but
+-- participant identity is per-BROWSER and shared across every design
+-- that browser opens. Opening a second design made every heartbeat's
+-- upsert INSERT collide with the first design's row: P2002 on (id),
+-- every ~15 s per client. Presence is inherently per-(design,
+-- participant): make that the primary key and drop the now-redundant
+-- unique index from 0001.
+ALTER TABLE "Presence" DROP CONSTRAINT "Presence_pkey";
+ALTER TABLE "Presence" ADD PRIMARY KEY ("designId", "id");
+DROP INDEX IF EXISTS "Presence_designId_id_key";
+
+-- 2) DesignEvent: the v0.10 offline client RETRIES flushes that fail
+-- mid-request (network drop, function killed at its duration limit).
+-- Replays used to duplicate ops. Persist the client's eventId and
+-- enforce uniqueness per design — retried batches become no-ops.
+-- Nullable: legacy rows have none (Postgres unique indexes skip NULLs).
+ALTER TABLE "DesignEvent" ADD COLUMN "eventId" TEXT;
+CREATE UNIQUE INDEX IF NOT EXISTS "DesignEvent_designId_eventId_key" ON "DesignEvent"("designId", "eventId");
diff --git a/prisma/schema.prisma b/prisma/schema.prisma
index 78e4579..cf62dac 100644
--- a/prisma/schema.prisma
+++ b/prisma/schema.prisma
@@ -124,21 +124,33 @@ model DesignEvent {
actorId String // participant id (client-generated)
kind String // op name — see research/COLLABORATION-ARCHITECTURE.md §3
payload Json
+ // v0.10.1: the client's dedupe key for this op. Unique per design so a
+ // retried flush (network drop / function timeout mid-batch) is a no-op
+ // instead of a duplicate — at-least-once delivery becomes exactly-once.
+ // Nullable: rows written before v0.10.1 have none (Postgres unique
+ // indexes ignore NULLs, so legacy rows never conflict).
+ eventId String?
createdAt DateTime @default(now())
+ @@unique([designId, eventId])
@@index([designId, id(sort: Desc)])
}
// Live presence per participant per design (heartbeat-based).
+// v0.10.1: the primary key is (designId, id) — participant identity is
+// per-BROWSER (src/lib/collab/identity.ts) and one browser can edit two
+// designs at once (two tabs). The old single-column PK on id made presence
+// exclusive to one design: every heartbeat for a second design failed with
+// P2002 (production incident 2026-10-29).
model Presence {
- id String @id // = participant id
+ id String // = participant id
designId String
name String
color String
cursor Json? // { page: number, x: number, y: number, selection?: string[] }
lastSeen DateTime @default(now()) @updatedAt
- @@unique([designId, id])
+ @@id([designId, id])
@@index([designId, lastSeen])
}
diff --git a/research/PRESENCE-P2002-POSTMORTEM.md b/research/PRESENCE-P2002-POSTMORTEM.md
new file mode 100644
index 0000000..89602ba
--- /dev/null
+++ b/research/PRESENCE-P2002-POSTMORTEM.md
@@ -0,0 +1,99 @@
+# Postmortem — presence P2002 storm + 30 s function hangs
+
+Date: 2026-10-29 · Status: **fixed in v0.10.1, verified live (18/18 probe
+checks) against the production database.**
+
+## Symptoms (from Vercel logs)
+
+1. `prisma.presence.upsert()` failing repeatedly with
+ `P2002: Unique constraint failed on the fields: (id)`, logged under
+ `[collab/presence]`.
+2. Numerous serverless functions running to **exactly 30,000 ms** —
+ requests timing out / hanging until the platform killed them at the
+ `maxDuration` ceiling.
+3. Pooler detection working as designed (`sslmode=require`,
+ `pgbouncer=true`, `connection_limit=1` notes in logs).
+
+## Root cause 1 — the P2002 (primary bug)
+
+`Presence` had a **single-column primary key on `id`** — the participant
+id — plus a composite unique index `(designId, id)` that the upsert
+matched. But participant identity is **per browser**
+(`src/lib/collab/identity.ts`, localStorage) and is reused across every
+design that browser opens.
+
+So the moment one browser had presence in a second design (two tabs, or
+any second design within the 24 h presence window):
+
+```
+upsert where (designId=B, id=P) → no row (the row is (A, P))
+ → INSERT (B, P) → PK violation on id → P2002
+```
+
+Every heartbeat (15 s) and every cursor update for the second design
+failed — 502 responses and log spam, forever. Production forensics
+before the fix: 808 presence rows, all 808 ids globally distinct — the
+PK had been silently enforcing "one design per browser" by *failing*.
+
+## Root cause 2 — the 30 s hangs (amplifier)
+
+The pg pool (`src/lib/db.ts`) ran `max: 1` with **no
+`connectionTimeoutMillis`** (node-postgres default: wait forever). One
+stale pooled connection — Supabase's transaction pooler drops idle
+server connections, and without a clean FIN the client pool never learns
+— wedged the instance's only connection:
+
+- in-flight queries on the dead peer never resolve (no keepAlive either)
+- every other request on that instance (fluid compute shares the
+ instance) queues on the pool **forever**
+- the platform kills each at its `maxDuration` → the exactly-30,000 ms
+ signature (events/comments routes run `maxDuration = 30`)
+
+The P2002 storm amplified exposure: every failing heartbeat + cursor
+flush kept churning connections and pooler round-trips.
+
+## Root cause 3 — duplicate events on retry (latent data bug)
+
+The v0.10 offline client **retains** failed flush batches and retries
+them. A flush killed at 30 s mid-batch could have persisted a prefix of
+its ops (up to 20 sequential `designEvent.create` calls); the retry then
+re-inserted that prefix — duplicated ops in the replication log. The
+LWW stamps made duplicates harmless *no-ops* for state, but the log
+bloat and noise were real.
+
+## The fix (v0.10.1) — four layers, no behaviour change for healthy paths
+
+| Layer | Change |
+|---|---|
+| **Data model** (migration `0004_presence_scope_event_dedup`, applied to prod) | `Presence` PK → `(designId, id)` (presence is per-design by nature; the redundant composite unique index from 0001 dropped). `DesignEvent.eventId` column + unique `(designId, eventId)` — legacy NULL rows never conflict. |
+| **Events route** | one `createMany({ skipDuplicates: true })` per flush (was N sequential creates — also ~20× fewer pooler round-trips) → **idempotent retries**; the presence touch is P2002-safe and bounded by a 3 s race (best-effort, never holds the flush). |
+| **Presence route** | P2002 (concurrent-create race) falls back to a plain `update` — heartbeats never 502 on a benign race; genuinely unexpected errors still surface honestly. |
+| **Pool + stream lifecycle** (`db.ts`, `stream/route.ts`) | pool: `connectionTimeoutMillis 10 s` (fail fast → 502 → client retries, now idempotent), `idleTimeoutMillis 30 s`, TCP keepAlive. Stream: a tick wedging >8 s ends the invocation **cleanly** (client reconnects in ~1.5 s via the `retry:` hint, replays gap-free via `?since`); streams self-recycle at 240 s < the 300 s ceiling (`CANVIX_STREAM_TTL_MS` to tune). |
+
+## Verification
+
+- 267/267 unit tests, tsc + eslint clean, Node build clean.
+- `scripts/verify-offline-merge.ts` extended to **18 checks** against the
+ live database, including the incident regressions:
+ - **cross-design presence**: one pid heartbeating into two designs —
+ all 200, no P2002 (the exact production repro)
+ - **idempotent flush**: the same batch POSTed twice → `accepted: 0`
+ the second time; SSE shows each op **exactly once**
+ - SSE `retry:` reconnect hint present
+ - Run: **18/18 green**, zero `[collab/presence]` errors in the server log.
+- Migration 0004 applied via `scripts/apply-migration.ts` (WASM client;
+ the classic engine hangs in some sandboxed environments) with a
+ checksum-correct `_prisma_migrations` row — later
+ `prisma migrate deploy` runs see it as applied.
+- Deploy matrix intact: Cloudflare 2.14 MB gz (limit 3), Netlify
+ 19.6 MB zip (limit 50).
+
+## Operator notes
+
+- Deployments that already ran 0004 (production) need nothing; new
+ self-hosters get it from `prisma migrate deploy` as usual.
+- `CANVIX_STREAM_TTL_MS` (default 240,000) tunes the SSE self-recycle
+ interval; keep it comfortably under the platform's function-duration
+ ceiling.
+- The 30 s `maxDuration` values are now ceilings that should never be
+ reached: pool waits fail at 10 s, wedged stream ticks close at 8 s.
diff --git a/scripts/apply-migration.ts b/scripts/apply-migration.ts
new file mode 100644
index 0000000..6e29e1b
--- /dev/null
+++ b/scripts/apply-migration.ts
@@ -0,0 +1,82 @@
+// scripts/apply-migration.ts — apply a Prisma migration through the WASM
+// client (the classic CLI engine hangs in some sandboxed environments).
+// Records a checksum-correct _prisma_migrations row so a later
+// `prisma migrate deploy` sees the migration as applied and skips it.
+//
+// Usage: npx tsx scripts/apply-migration.ts <migration-name> <DATABASE_URL>
+// e.g. npx tsx scripts/apply-migration.ts 0004_presence_scope_event_dedup "$DATABASE_URL"
+import { createHash, randomUUID } from 'node:crypto'
+import { readFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { createScriptClient } from '../src/lib/db-script'
+
+function statementsOf(sql: string): string[] {
+ // split on statement-terminating semicolons at end-of-line; this repo's
+ // migrations contain no semicolons inside string literals. Comment lines
+ // are stripped WITHIN each statement (a statement may carry a leading
+ // comment block — the SQL itself still has to run).
+ return sql
+ .split(/;\s*\n/)
+ .map((s) =>
+ s
+ .split('\n')
+ .filter((l) => !l.trim().startsWith('--'))
+ .join('\n')
+ .replace(/\n{2,}/g, '\n')
+ .trim(),
+ )
+ .filter((s) => s.length > 0)
+}
+
+async function main() {
+ const name = process.argv[2]
+ const url = process.argv[3] ?? process.env.DATABASE_URL
+ if (!name || !url) {
+ console.error('usage: tsx scripts/apply-migration.ts <migration-name> <DATABASE_URL>')
+ process.exit(1)
+ }
+ const file = join(process.cwd(), 'prisma', 'migrations', name, 'migration.sql')
+ const sql = readFileSync(file, 'utf8')
+ const checksum = createHash('sha256').update(sql, 'utf8').digest('hex')
+
+ const db = createScriptClient(url)
+ try {
+ const already = await db.$queryRawUnsafe(
+ `SELECT COUNT(*)::int AS n FROM "_prisma_migrations" WHERE migration_name = $1`,
+ name,
+ ) as Array<{ n: number }>
+ if (already[0].n > 0) {
+ console.log(`= ${name} already recorded in _prisma_migrations — nothing to do`)
+ return
+ }
+
+ const stmts = statementsOf(sql)
+ console.log(`→ applying ${name} (${stmts.length} statements)`)
+ for (const stmt of stmts) {
+ const first = stmt.split('\n').find((l) => !l.trim().startsWith('--')) ?? stmt
+ await db.$executeRawUnsafe(stmt)
+ console.log(` ✓ ${first.slice(0, 72)}${first.length > 72 ? '…' : ''}`)
+ }
+
+ // record exactly as `prisma migrate deploy` would (checksum = sha256
+ // of migration.sql — verified against the 0001–0003 rows)
+ await db.$executeRawUnsafe(
+ `INSERT INTO "_prisma_migrations" (id, checksum, finished_at, migration_name, logs, rolled_back_at, started_at, applied_steps_count)
+ VALUES ($1, $2, NOW(), $3, NULL, NULL, NOW(), 1)`,
+ randomUUID(),
+ checksum,
+ name,
+ )
+ console.log(`✓ ${name} applied + recorded (checksum ${checksum.slice(0, 16)}…)`)
+ } catch (e) {
+ console.error(`✗ ${name} failed:`, (e as Error).message)
+ process.exit(1)
+ } finally {
+ await db.$disconnect()
+ }
+}
+
+main().catch((e) => {
+ console.error('apply-migration crashed:', e)
+ process.exit(1)
+})
diff --git a/scripts/inspect-presence-constraints.ts b/scripts/inspect-presence-constraints.ts
new file mode 100644
index 0000000..75d3df0
--- /dev/null
+++ b/scripts/inspect-presence-constraints.ts
@@ -0,0 +1,50 @@
+// scripts/inspect-presence-constraints.ts — pre-migration forensics for 0004
+// Usage: npx tsx scripts/inspect-presence-constraints.ts <DATABASE_URL>
+import { createScriptClient } from '../src/lib/db-script'
+
+async function main() {
+ const url = process.argv[2] ?? process.env.DATABASE_URL
+ if (!url) {
+ console.error('✗ no DATABASE_URL given')
+ process.exit(1)
+ }
+ const db = createScriptClient(url)
+ try {
+ const cons = await db.$queryRawUnsafe(`
+ SELECT conname::text, pg_get_constraintdef(oid) AS def
+ FROM pg_constraint
+ WHERE conrelid = '"Presence"'::regclass
+ ORDER BY conname`) as Array<{ conname: string; def: string }>
+ console.log('— Presence constraints —')
+ for (const c of cons) console.log(` ${c.conname}: ${c.def}`)
+
+ const cols = await db.$queryRawUnsafe(`
+ SELECT column_name::text, data_type::text, is_nullable::text
+ FROM information_schema.columns
+ WHERE table_name = 'Presence' ORDER BY ordinal_position`) as Array<Record<string, string>>
+ console.log('— Presence columns —')
+ for (const c of cols) console.log(` ${c.column_name} ${c.data_type} nullable=${c.is_nullable}`)
+
+ const evCols = await db.$queryRawUnsafe(`
+ SELECT column_name::text, data_type::text
+ FROM information_schema.columns
+ WHERE table_name = 'DesignEvent' ORDER BY ordinal_position`) as Array<Record<string, string>>
+ console.log('— DesignEvent columns —')
+ for (const c of evCols) console.log(` ${c.column_name} ${c.data_type}`)
+
+ const rows = await db.$queryRawUnsafe(`SELECT COUNT(*)::int AS n, COUNT(DISTINCT id)::int AS ids, COUNT(DISTINCT (\"designId\", id))::int AS pairs FROM "Presence"`) as Array<{ n: number; ids: number; pairs: number }>
+ console.log(`— Presence rows: ${rows[0].n} (distinct id ${rows[0].ids}, distinct (designId,id) ${rows[0].pairs})`)
+
+ const mig = await db.$queryRawUnsafe(`
+ SELECT migration_name::text, checksum::text FROM "_prisma_migrations" ORDER BY finished_at`) as Array<{ migration_name: string; checksum: string }>
+ console.log('— applied migrations —')
+ for (const m of mig) console.log(` ${m.migration_name} checksum=${m.checksum.slice(0, 16)}…`)
+ } finally {
+ await db.$disconnect()
+ }
+}
+
+main().catch((e) => {
+ console.error('inspect failed:', (e as Error).message)
+ process.exit(1)
+})
diff --git a/scripts/verify-offline-merge.ts b/scripts/verify-offline-merge.ts
index 5dcd99f..7eaa9ba 100644
--- a/scripts/verify-offline-merge.ts
+++ b/scripts/verify-offline-merge.ts
@@ -153,23 +153,53 @@ async function main() {
}
// 6. collab events — client hlc preserved, legacy gets a server stamp
- const ev = await api('POST', `/api/collab/${designId}/events`, {
+ const batch = {
pid: 'probe-pid',
events: [
{ eventId: 'probe-ev-1', hlc: '00000012y0:00009:probe-b', op: { kind: 'elements:update', pageId, ids: ['E1'], patch: { text: 'via-sse' } } },
{ eventId: 'probe-ev-2', op: { kind: 'elements:update', pageId, ids: ['E2'], patch: { text: 'legacy-client' } } }, // NO hlc → server stamps
],
- })
+ }
+ const ev = await api('POST', `/api/collab/${designId}/events`, batch)
if (ev.status === 200 && ev.json?.accepted === 2) pass('events POST', '2 ops accepted')
else fail('events POST', `status ${ev.status} body=${JSON.stringify(ev.json).slice(0, 120)}`)
- // 7. SSE replay — both events stream back with `_h` in the payload
+ // 6b. v0.10.1 idempotent flush — the exact retry the client performs
+ // after a request dies mid-batch (30 s function kill): the SAME batch
+ // must re-insert nothing ((designId, eventId) unique)
+ const dup = await api('POST', `/api/collab/${designId}/events`, batch)
+ if (dup.status === 200 && dup.json?.accepted === 0) pass('idempotent flush', 'replayed batch inserted 0 duplicates')
+ else fail('idempotent flush', `status ${dup.status} accepted=${dup.json?.accepted}`)
+
+ // 6c. v0.10.1 cross-design presence — the exact P2002 repro: ONE
+ // browser identity heartbeating into TWO designs (the old PK on id
+ // alone made the second design's upsert fail every 15 s)
+ const second = await api('POST', '/api/designs', { name: 'offline-merge-probe-2', width: 800, height: 600 })
+ if (second.status === 201) {
+ const design2 = second.json.id
+ try {
+ const hb1 = await api('POST', `/api/collab/${designId}/presence`, { pid: 'probe-pid', name: 'Probe', color: '#7630D7', cursor: { page: 0, x: 10, y: 20 } })
+ const hb2 = await api('POST', `/api/collab/${design2}/presence`, { pid: 'probe-pid', name: 'Probe', color: '#7630D7', cursor: { page: 0, x: 30, y: 40 } })
+ const hb1b = await api('POST', `/api/collab/${designId}/presence`, { pid: 'probe-pid', name: 'Probe', color: '#7630D7' })
+ if (hb1.status === 200 && hb2.status === 200 && hb1b.status === 200)
+ pass('cross-design presence', 'same pid live in two designs, no P2002')
+ else
+ fail('cross-design presence', `heartbeat statuses ${hb1.status}/${hb2.status}/${hb1b.status}`)
+ } finally {
+ await api('DELETE', `/api/designs/${design2}?permanent=1`)
+ }
+ } else {
+ fail('cross-design presence', `second design create → ${second.status}`)
+ }
+
+ // 7. SSE replay — both events stream back with `_h` in the payload,
+ // EXACTLY ONCE each (duplicates would show the dedupe index failing)
const ac = new AbortController()
const sse = await fetch(`${BASE}/api/collab/${designId}/stream?since=0&pid=probe-pid`, {
headers: cookies ? { cookie: cookies } : {},
signal: ac.signal,
})
- const found = { client: false, server: false }
+ const found = { client: 0, server: 0, retryHint: false }
if (sse.ok && sse.body) {
const reader = sse.body.getReader()
const dec = new TextDecoder()
@@ -182,16 +212,16 @@ async function main() {
const lines = buf.split('\n')
buf = lines.pop() ?? ''
for (const line of lines) {
+ if (line.startsWith('retry:')) found.retryHint = true
if (!line.startsWith('data:')) continue
try {
const frame = JSON.parse(line.slice(5).trim())
for (const e of frame.events ?? []) {
- // stream ids are DB row ids (client eventIds aren't persisted)
- // → match ops by their patch payload
+ // stream ids are DB row ids — match ops by their patch payload
const h = e.payload?._h
const texts = JSON.stringify(e.payload?.patch ?? {})
- if (texts.includes('via-sse') && h === '00000012y0:00009:probe-b') found.client = true
- if (texts.includes('legacy-client') && typeof h === 'string' && h.endsWith(':srv')) found.server = true
+ if (texts.includes('via-sse') && h === '00000012y0:00009:probe-b') found.client++
+ if (texts.includes('legacy-client') && typeof h === 'string' && h.endsWith(':srv')) found.server++
}
} catch {
/* keep-alive / partial */
@@ -200,10 +230,12 @@ async function main() {
}
ac.abort()
}
- if (found.client) pass('SSE client hlc', 'payload._h preserved verbatim')
- else fail('SSE client hlc', 'probe-ev-1 not observed with its stamp')
- if (found.server) pass('SSE server stamp', 'legacy op stamped …:srv:')
- else fail('SSE server stamp', 'probe-ev-2 not observed with a server stamp')
+ if (found.client === 1) pass('SSE client hlc', 'payload._h preserved verbatim, exactly once')
+ else fail('SSE client hlc', `probe-ev-1 observed ${found.client}× (want exactly 1)`)
+ if (found.server === 1) pass('SSE server stamp', 'legacy op stamped …:srv, exactly once')
+ else fail('SSE server stamp', `probe-ev-2 observed ${found.server}× (want exactly 1)`)
+ if (found.retryHint) pass('SSE retry hint', 'reconnect hint present for clean recycles')
+ else fail('SSE retry hint', 'retry: field not observed')
} finally {
// 8. cleanup — permanent delete
const del = await api('DELETE', `/api/designs/${designId}?permanent=1`)
diff --git a/src/app/api/collab/[designId]/events/route.ts b/src/app/api/collab/[designId]/events/route.ts
index 280b614..a9e7d87 100644
--- a/src/app/api/collab/[designId]/events/route.ts
+++ b/src/app/api/collab/[designId]/events/route.ts
@@ -1,5 +1,6 @@
import { NextRequest, NextResponse } from 'next/server'
import { db } from '@/lib/db'
+import { Prisma } from '@/generated/prisma/client'
import {
MAX_EVENTS_PER_FLUSH,
OP_KINDS,
@@ -68,8 +69,8 @@ export async function POST(req: NextRequest, { params }: { params: Promise<{ des
}
const seenEventIds = new Set<string>()
- const accepted: string[] = []
const rejected: string[] = []
+ const rows: Prisma.DesignEventCreateManyInput[] = []
for (const env of events) {
if (!env || typeof env !== 'object' || !env.op || typeof env.eventId !== 'string') {
@@ -106,27 +107,55 @@ export async function POST(req: NextRequest, { params }: { params: Promise<{ des
// v0.10: embed the HLC stamp (client's if present, else the server's)
payload._h = typeof env.hlc === 'string' && env.hlc.length <= 80 ? env.hlc : serverHlc()
- await db.designEvent.create({
- data: {
- designId,
- actorId: pid,
- kind: op.kind,
- payload: payload as object,
- },
+ rows.push({
+ designId,
+ actorId: pid,
+ kind: op.kind,
+ payload: payload as Prisma.InputJsonValue,
+ eventId: env.eventId,
})
- accepted.push(env.eventId)
}
- // touch presence so an active editor stays "online" even between heartbeats
+ // v0.10.1: one round-trip for the whole batch (was N sequential creates —
+ // up to 20 pooler round-trips per flush) and IDEMPOTENT: (designId,
+ // eventId) is unique, so a retried flush (network drop, or the function
+ // killed at its duration limit mid-batch — exactly the 30 s-timeout
+ // incident) re-inserts nothing instead of duplicating ops. The v0.10
+ // client RETAINS failed batches, so this is what makes retries safe.
+ let accepted = 0
+ if (rows.length) {
+ const r = await db.designEvent.createMany({ data: rows, skipDuplicates: true })
+ accepted = r.count
+ }
+
+ // touch presence so an active editor stays "online" even between heartbeats.
+ // v0.10.1: bounded (3 s) — presence is best-effort and must never hold the
+ // flush hostage — and P2002-safe (a concurrent create raced us → the row
+ // exists by now → a plain update lands the touch anyway).
const name = (body.name ?? '').replace(/[^\p{L}\p{N} ._-]/gu, '').slice(0, 40) || 'Guest'
const color = HEX_COLOR.test(body.color ?? '') ? body.color! : '#7630D7'
- await db.presence.upsert({
- where: { designId_id: { designId, id: pid } },
- create: { designId, id: pid, name, color },
- update: { lastSeen: new Date(), name, color },
- }).catch(() => { /* presence is best-effort */ })
+ await Promise.race([
+ db.presence
+ .upsert({
+ where: { designId_id: { designId, id: pid } },
+ create: { designId, id: pid, name, color },
+ update: { lastSeen: new Date(), name, color },
+ })
+ .catch(async (err) => {
+ if ((err as { code?: string }).code === 'P2002') {
+ await db.presence
+ .update({
+ where: { designId_id: { designId, id: pid } },
+ data: { lastSeen: new Date(), name, color },
+ })
+ .catch(() => { /* row vanished (GC) — next heartbeat recreates */ })
+ }
+ /* other errors: presence is best-effort */
+ }),
+ new Promise<void>((resolve) => setTimeout(resolve, 3_000)),
+ ])
- return NextResponse.json({ ok: true, accepted: accepted.length, rejected })
+ return NextResponse.json({ ok: true, accepted, rejected })
} catch (err) {
console.error('[collab/events]', err)
return NextResponse.json({ error: 'Could not persist collaboration events.' }, { status: 502 })
diff --git a/src/app/api/collab/[designId]/presence/route.ts b/src/app/api/collab/[designId]/presence/route.ts
index 75962c7..522386e 100644
--- a/src/app/api/collab/[designId]/presence/route.ts
+++ b/src/app/api/collab/[designId]/presence/route.ts
@@ -42,11 +42,30 @@ export async function POST(req: NextRequest, { params }: { params: Promise<{ des
}
const { Prisma } = await import('@/generated/prisma/client')
- await db.presence.upsert({
- where: { designId_id: { designId, id: pid } },
- create: { designId, id: pid, name, color, cursor: (cursor ?? undefined) as object },
- update: { name, color, cursor: (cursor ?? Prisma.JsonNull) as object, lastSeen: new Date() },
- })
+ // v0.10.1 (incident 2026-10-29): this upsert used to 502 with P2002
+ // every heartbeat when one browser had presence in a second design
+ // (participant identity is per-browser; the PK used to be id alone —
+ // fixed by migration 0004). Belt-and-braces: a concurrent create race
+ // can still P2002 on the composite key — fall back to a plain update
+ // so the heartbeat lands and the route never 502s on a benign race.
+ try {
+ await db.presence.upsert({
+ where: { designId_id: { designId, id: pid } },
+ create: { designId, id: pid, name, color, cursor: (cursor ?? undefined) as object },
+ update: { name, color, cursor: (cursor ?? Prisma.JsonNull) as object, lastSeen: new Date() },
+ })
+ } catch (err) {
+ if ((err as { code?: string }).code === 'P2002') {
+ await db.presence
+ .update({
+ where: { designId_id: { designId, id: pid } },
+ data: { name, color, cursor: (cursor ?? Prisma.JsonNull) as object, lastSeen: new Date() },
+ })
+ .catch(() => { /* row vanished (24 h GC) — next heartbeat recreates */ })
+ } else {
+ throw err // unexpected (pool timeout, DB down) — honest 502 below
+ }
+ }
return NextResponse.json({ ok: true })
} catch (err) {
diff --git a/src/app/api/collab/[designId]/stream/route.ts b/src/app/api/collab/[designId]/stream/route.ts
index 3c7e3f7..5507c98 100644
--- a/src/app/api/collab/[designId]/stream/route.ts
+++ b/src/app/api/collab/[designId]/stream/route.ts
@@ -5,6 +5,19 @@ export const runtime = 'nodejs'
export const dynamic = 'force-dynamic'
export const maxDuration = 300 // Vercel-friendly bounded stream duration
+// ── v0.10.1 lifecycle bounds (production incident 2026-10-29) ──
+// A tick could wedge forever on a stale pooled connection (pooler idle
+// drop with no FIN): the stream then hung silently until the platform
+// killed the function at its duration limit, and every request sharing
+// that instance's single connection queued behind it. Bounds now:
+// - PUMP_TIMEOUT_MS: one tick wedging past this ends the invocation
+// CLEANLY — the client reconnects within ~1.5 s and replays gap-free
+// - MAX_STREAM_AGE_MS: self-recycle well under maxDuration so the
+// platform never kills us mid-frame (fresh connection per cycle is
+// also the cheapest pool hygiene there is)
+const PUMP_TIMEOUT_MS = 8_000
+const MAX_STREAM_AGE_MS = Number(process.env.CANVIX_STREAM_TTL_MS ?? 240_000)
+
/**
* GET /api/collab/[designId]/stream?since=<seq>&pid=<participantId>
*
@@ -40,6 +53,8 @@ export async function GET(req: NextRequest, { params }: { params: Promise<{ desi
const encoder = new TextEncoder()
let closed = false
let timer: ReturnType<typeof setTimeout> | null = null
+ let pumpTimeout: ReturnType<typeof setTimeout> | null = null
+ const born = Date.now()
const stream = new ReadableStream<Uint8Array>({
async start(controller) {
@@ -68,6 +83,7 @@ export async function GET(req: NextRequest, { params }: { params: Promise<{ desi
if (closed) return
closed = true
if (timer) clearTimeout(timer)
+ if (pumpTimeout) clearTimeout(pumpTimeout)
try {
controller.close()
} catch {
@@ -117,6 +133,7 @@ export async function GET(req: NextRequest, { params }: { params: Promise<{ desi
events: events.map((e) => ({
seq: Number(e.id),
id: e.id.toString(),
+ eventId: e.eventId ?? undefined, // v0.10.1: client dedupe key
designId: e.designId,
actorId: e.actorId,
kind: e.kind,
@@ -157,10 +174,37 @@ export async function GET(req: NextRequest, { params }: { params: Promise<{ desi
// v0.9.2: adaptive self-scheduling pump — backs off to 3.2 s when the
// design is quiet, returns to 800 ms the moment anything happens.
+ const PUMP_WEDGED = Symbol('pump-wedged')
const scheduleNext = async () => {
if (closed) return
- const hadEvents = await pump()
- delay = hadEvents ? 800 : Math.min(Math.round(delay * 1.5), 3200)
+ // v0.10.1: self-recycle under the maxDuration ceiling — the client
+ // reconnects (retry hint below) and replays gap-free via ?since
+ if (Date.now() - born > MAX_STREAM_AGE_MS) {
+ comment('recycle')
+ close()
+ return
+ }
+ const result = await Promise.race([
+ pump(),
+ new Promise<typeof PUMP_WEDGED>((resolve) => {
+ pumpTimeout = setTimeout(() => resolve(PUMP_WEDGED), PUMP_TIMEOUT_MS)
+ }),
+ ])
+ if (pumpTimeout) {
+ clearTimeout(pumpTimeout)
+ pumpTimeout = null
+ }
+ if (closed) return
+ if (result === PUMP_WEDGED) {
+ // v0.10.1: a tick wedged past PUMP_TIMEOUT_MS (stale pooled
+ // connection / pooler hiccup) — end this invocation cleanly
+ // instead of hanging to maxDuration; the client reconnects
+ // within ~1.5 s and replays gap-free
+ comment('db-timeout')
+ close()
+ return
+ }
+ delay = result ? 800 : Math.min(Math.round(delay * 1.5), 3200)
if (closed) return
timer = setTimeout(() => void scheduleNext(), delay)
}
@@ -169,6 +213,14 @@ export async function GET(req: NextRequest, { params }: { params: Promise<{ desi
// initial frame immediately (replay from `since`)
comment(`open design=${designId} since=${since}`)
+ // v0.10.1: reconnect hint — after our clean close (recycle /
+ // db-timeout) the browser reconnects in 1.5 s instead of the ~3 s
+ // default, keeping the gap invisible to the user
+ try {
+ controller.enqueue(encoder.encode('retry: 1500\n\n'))
+ } catch {
+ /* client already gone */
+ }
await scheduleNext()
},
})
diff --git a/src/lib/collab/protocol.ts b/src/lib/collab/protocol.ts
index b9cf23d..c4104dc 100644
--- a/src/lib/collab/protocol.ts
+++ b/src/lib/collab/protocol.ts
@@ -39,6 +39,8 @@ export interface OpEnvelope {
export interface DesignEventRow {
seq: number
id: string
+ /** v0.10.1: the emitting client's dedupe key (absent on legacy rows) */
+ eventId?: string
designId: string
actorId: string
kind: string
diff --git a/src/lib/db.ts b/src/lib/db.ts
index 9e61638..b331dc4 100644
--- a/src/lib/db.ts
+++ b/src/lib/db.ts
@@ -25,6 +25,20 @@ function createDb(): PrismaClient {
const adapter = new PrismaPg({
connectionString: driverConnectionString(process.env.DATABASE_URL),
max: 1,
+ // ── v0.10.1 pool hardening (production incident 2026-10-29) ──
+ // Symptom: functions running to exactly their duration limit (30 s)
+ // with requests never resolving. Cause: one stale pooled connection
+ // (pooler idle-drop without a FIN) wedged the instance's single
+ // connection — waiters queued forever because the pool had NO
+ // acquisition timeout. Bounds now make every failure fast instead of
+ // hanging: a timed-out request 502s, the v0.10 client retains + retries
+ // it, and retries are idempotent (DesignEvent (designId, eventId)
+ // unique). keepAlive lets the OS detect dead peers instead of parking
+ // queries on them forever.
+ connectionTimeoutMillis: 10_000, // pool-wait cap → error, never hang
+ idleTimeoutMillis: 30_000, // drop idle conns before the pooler does it dirty
+ keepAlive: true,
+ keepAliveInitialDelayMillis: 10_000,
})
return new PrismaClient({
adapter,