Files
collective-lists/packages/test-utils/tests/realtime-postgres-changes.test.ts
Oier Bravo Urtasun cb07f67a69 feat(realtime): full Fase 2b.0 test suite + infra hardening
Extend the 2b.0 red-phase coverage: presence, RLS isolation, offline-queue
contract, and Playwright scaffolds for the shopping-session UX. Only the
presence test is blocked on an upstream Realtime bug (documented below); all
other Realtime paths are proven end-to-end.

Tests
- realtime-postgres-changes.test.ts: now uses afterEach socket disconnect
  (Vitest singleFork kept Phoenix sockets alive between files, leaking state)
- realtime-isolation.test.ts (new): R-I-01 David (guest, same collective)
  receives events; R-I-02 Eva (non-member) receives NONE — RLS is enforced
  server-side per subscribed JWT
- realtime-presence.test.ts (new, describe.skip): two-client roster + leave
  assertions ready, gated on upstream bug
- sync-queue.test.ts (new, describe.skip): 7 placeholders pinning the
  apps/web/src/lib/sync/queue.ts contract (Q-01..Q-04 enqueue / in-order
  flush / retry; F-01..F-03 online-event flush + last-write-wins)
- apps/web/tests/e2e/{session,realtime,offline}.test.ts (new, describe.skip):
  S-01..S-03, R-E-01, R-E-02, O-01, O-02 pinning the Modo Compra UI contract
- vitest.config.ts: fileParallelism=false, drop singleFork so each file gets
  a fresh worker fork — prevents RealtimeClient singleton leakage

Infra
- db-init/00-role-passwords.sh: pre-create `realtime` schema with
  AUTHORIZATION supabase_admin. Realtime's per-tenant migrator creates tables
  INSIDE the schema but does not create the schema itself; without this the
  first tenant connect fails with "schema realtime does not exist"
- docker-compose.dev.yml: adopt the upstream supabase/supabase Realtime env
  shape — SEED_SELF_HOST=true + RUN_JANITOR=true + RLIMIT_NOFILE=10000 +
  drop the custom `command: eval seeds` (that bypasses the normal supervisor
  startup and was observed to cause GenServer crashes under load).
  Version pinned to v2.76.5 to match the official docker-compose.

Known upstream bug
- Realtime v2.76.5 and v2.83.0 both crash on presence_diff:
  `(UndefinedFunctionError) RealtimeChannel.handle_out/3 is undefined`.
  postgres_changes + isolation unaffected (they don't traverse handle_out).
  Presence tests stay `describe.skip` until a fixed upstream is released.

Totals: 59 Vitest passed (+ 9 skipped awaiting implementation/upstream),
16 pgTAP, 15 Playwright (+ 7 E2E scaffolded for 2b UI) = 90 green.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 02:55:55 +02:00

173 lines
5.5 KiB
TypeScript

/**
* R-series: Supabase Realtime `postgres_changes` over `shopping_items`.
*
* Verifies the end-to-end path: mutation in Postgres → WAL → supabase_realtime
* publication → Realtime service → WebSocket → subscribed client.
*
* Migration 007 adds shopping_items to the publication and sets REPLICA
* IDENTITY FULL. Without either, these tests fail with timeouts.
*/
import { describe, it, expect, afterAll, afterEach } from 'vitest';
import { createClientAs, createAdminClient } from '../src/supabase-clients.js';
import { subscribePostgresChanges } from '../src/realtime-helpers.js';
import {
ANA_ID,
BORJA_ID,
SEED_LIST_ID,
COLLECTIVE_ID
} from '../src/seed-constants.js';
import type { SupabaseClient } from '@supabase/supabase-js';
const admin = createAdminClient();
const createdItemIds: string[] = [];
// See realtime-presence.test.ts for rationale: Vitest's singleFork means Phoenix
// sockets leak between test files unless we force-disconnect them per test.
const activeClients: SupabaseClient[] = [];
function track(c: SupabaseClient): SupabaseClient {
activeClients.push(c);
return c;
}
afterEach(async () => {
for (const c of activeClients.splice(0)) {
await c.removeAllChannels();
await c.realtime.disconnect();
}
});
afterAll(async () => {
if (createdItemIds.length > 0) {
await admin.from('shopping_items').delete().in('id', createdItemIds);
}
});
describe('Realtime postgres_changes — shopping_items', () => {
it('R-01: INSERT made by Ana reaches Borja subscribed to the same list', async () => {
const borja = track(await createClientAs(BORJA_ID));
const ana = track(await createClientAs(ANA_ID));
const sub = await subscribePostgresChanges<{ id: string; list_id: string; name: string }>(
borja,
{
table: 'shopping_items',
event: 'INSERT',
filter: `list_id=eq.${SEED_LIST_ID}`
}
);
try {
const itemName = `R-01-item-${Date.now()}`;
const { data, error } = await ana
.from('shopping_items')
.insert({ list_id: SEED_LIST_ID, name: itemName, sort_order: 900, created_by: ANA_ID })
.select('id')
.single();
expect(error).toBeNull();
if (data?.id) createdItemIds.push(data.id);
const evt = await sub.waitFor((e) => e.eventType === 'INSERT' && e.new.name === itemName);
expect(evt.new.list_id).toBe(SEED_LIST_ID);
expect(evt.new.name).toBe(itemName);
} finally {
await sub.unsubscribe();
await borja.removeAllChannels();
await ana.removeAllChannels();
}
});
it('R-02: UPDATE broadcasts include the full row (REPLICA IDENTITY FULL)', async () => {
const ana = track(await createClientAs(ANA_ID));
const borja = track(await createClientAs(BORJA_ID));
// Seed an item owned by Ana to mutate
const { data: item } = await admin
.from('shopping_items')
.insert({ list_id: SEED_LIST_ID, name: 'R-02-seed', sort_order: 901, created_by: ANA_ID })
.select('id')
.single();
createdItemIds.push(item!.id);
const sub = await subscribePostgresChanges<{
id: string;
list_id: string;
name: string;
is_checked: boolean;
}>(borja, {
table: 'shopping_items',
event: 'UPDATE',
filter: `list_id=eq.${SEED_LIST_ID}`
});
try {
await ana
.from('shopping_items')
.update({ is_checked: true, checked_by: ANA_ID, checked_at: new Date().toISOString() })
.eq('id', item!.id);
const evt = await sub.waitFor((e) => e.eventType === 'UPDATE' && e.new.id === item!.id);
// With REPLICA IDENTITY FULL, `new` carries the full row including list_id
expect(evt.new.list_id).toBe(SEED_LIST_ID);
expect(evt.new.is_checked).toBe(true);
expect(evt.new.name).toBe('R-02-seed');
} finally {
await sub.unsubscribe();
await ana.removeAllChannels();
await borja.removeAllChannels();
}
});
it('R-03: filter on list_id excludes events from other lists', async () => {
// Create a second list in the same collective
const { data: otherList } = await admin
.from('shopping_lists')
.insert({ collective_id: COLLECTIVE_ID, name: 'R-03 other list', created_by: ANA_ID })
.select('id')
.single();
const otherListId = otherList!.id;
const borja = track(await createClientAs(BORJA_ID));
const ana = track(await createClientAs(ANA_ID));
// Borja subscribes to SEED_LIST_ID only
const sub = await subscribePostgresChanges<{ id: string; list_id: string; name: string }>(
borja,
{
table: 'shopping_items',
event: 'INSERT',
filter: `list_id=eq.${SEED_LIST_ID}`
}
);
try {
// Insert into the OTHER list — Borja should NOT receive this event
const noiseName = `R-03-noise-${Date.now()}`;
const { data: noise } = await ana
.from('shopping_items')
.insert({ list_id: otherListId, name: noiseName, sort_order: 902, created_by: ANA_ID })
.select('id')
.single();
createdItemIds.push(noise!.id);
// Insert into SEED_LIST_ID — Borja SHOULD receive this
const signalName = `R-03-signal-${Date.now()}`;
const { data: signal } = await ana
.from('shopping_items')
.insert({ list_id: SEED_LIST_ID, name: signalName, sort_order: 903, created_by: ANA_ID })
.select('id')
.single();
createdItemIds.push(signal!.id);
// Wait for the signal event
await sub.waitFor((e) => e.new.name === signalName);
// The noise event should not be present
const noiseEvt = sub.events.find((e) => (e.new as { name: string }).name === noiseName);
expect(noiseEvt).toBeUndefined();
} finally {
await sub.unsubscribe();
await ana.removeAllChannels();
await borja.removeAllChannels();
await admin.from('shopping_lists').delete().eq('id', otherListId);
}
});
});