Skip to content

feat(messaging): messaging pipeline foundation (schema, domain, use cases, adapters) - #86

Merged
juancodedev merged 17 commits into
mainfrom
feature/messaging-pipeline
Nov 5, 2026
Merged

juancodedev merged 17 commits into
mainfrom
feature/messaging-pipeline

Conversation

@juancodedev

@juancodedev juancodedev commented Nov 4, 2026 •

Copy link
Copy Markdown
Owner

Summary

Foundation of the messaging-pipeline change: Instagram DMs move from activities rows (direction parsed from the title, no mid, no dedup) to dedicated messaging tables behind a MessagingChannel port. This PR holds tasks T1–T5 of 10 — schema, domain and use cases. Nothing is wired yet: no route, page or webhook uses this code, so merging it changes no runtime behaviour.

Design docs (included): openspec/changes/messaging-pipeline/ — proposal.md, specs/, design.md (12 ADRs) and judgment-day.md (dual adversarial review; 13 warnings incorporated).

What's in it

Area Change
supabase/migrations/20261103000000_messaging_tables.sql channel_accounts, conversations, messages, webhook_events; RLS with ownership WITH CHECK; partial unique index on messages.external_id; Realtime publication; atomic SQL functions (messaging_ingest_inbound, messaging_record_echo, messaging_mark_sent, messaging_claim_retry, messaging_set_conversations_read, messaging_sync_legacy_read)
src/infrastructure/database/database.types.ts Hand-maintained types for the new tables
src/modules/messaging/domain Entities, enums, InboundEvent, ports (MessagingChannel, repositories, LeadLookup)
src/modules/messaging/application/use-cases IngestInboundEvent (messages + echoes), DeliverMessage, ProcessWebhookEvent, SweepWebhookEvents, MarkConversationRead
src/modules/messaging/testing/InMemoryMessagingStore.ts In-memory model of the tables and SQL function semantics, shared by the use-case specs
src/modules/messaging/infrastructure MetaInstagramChannel, Supabase repositories, SQL executors (T5); GraphApiError, createAdminClient, channel_accounts sync on token store
src/lib/runtime runInBackground over getCloudflareContext().ctx.waitUntil
package.json, supabase/config.toml pnpm test:db script + local Supabase config for SQL behaviour tests

Notable fixes during implementation

  • 6dc8bfe: FOR UPDATE SKIP LOCKED only holds while messaging_claim_retry runs, so an overlapping sweep could reclaim an event still being processed. Added a webhook_events.last_attempt_at lease (reclaim only after 2 min without an attempt). Found by the overlapping-sweep use-case test.
  • DeliverMessage never downgrades a row an echo already made sent, and failed sends write no legacy activity (a code rollback would otherwise show them as sent).

Test plan

  • npx tsc --noEmit — 0 errors
  • npx eslint . --max-warnings 30 — 0 errors, 14 pre-existing warnings
  • pnpm test — 93 suites, 654 tests passed
  • All migrations applied on a clean local Postgres + psql smoke test of the messaging functions
  • pnpm test:db against a local Supabase stack — pending (T10); the SQL functions' atomicity and concurrency are only covered by static migration specs and the in-memory model so far

Not in this PR (remaining tasks)

T6 webhook rewrite + sweep endpoint · T7 endpoints/UI on the new tables + OpenAPI · T8 history backfill + rollout runbook · T9 Cron (worker.ts) · T10 test:db run.

Production DB: 20261103000000_messaging_tables.sql was applied on 2026-11-04 (additive only; tables are empty and unused until the webhook is switched). Prod schema_migrations had drifted (13 migrations applied by hand but unrecorded); they were verified against a schema dump and marked applied with supabase migration repair, and the 8-digit migrations were renamed to unique 14-digit versions (0354ce4).

🤖 Generated with Claude Code

Migration A (20261103000000_messaging_tables.sql):
- channel_accounts, conversations, messages, webhook_events tables
- RLS ownership on every referenced row (WITH CHECK on account/lead/conversation)
- webhook_events policy-free (service role only)
- Partial unique index on messages.external_id, FK indexes
- conversations + messages added to supabase_realtime publication
- ADR-10 SECURITY INVOKER functions: ingest_inbound, record_echo,
  mark_sent, claim_retry (FOR UPDATE SKIP LOCKED), set_conversations_read,
  sync_legacy_read
- database.types.ts updated for the four new tables
- Static migration spec (15 assertions)

Risk: item 1 (persisted format)
- supabase/config.toml: minimal local stack config (api, db, auth,
  storage, realtime, pooler) so  works with Docker
- package.json: add pnpm test:db script that starts the local Supabase
  stack and runs the SQL behaviour test suite (duplicate mid, echo
  adopt/insert/duplicate, mark-sent, claim-retry concurrency, backfill
  re-run). Falls back to manual run + verify report when Docker is not
  available in CI.

Risk: none
Regenerated from supabase init defaults with the correct v2.75.0 schema.
Previous config used invalid keys (hostname, exec_spawn_pool_size,
enabled on wrong sections). supabase start now parses the config and
pulls Docker images successfully.
- domain entities: Conversation, Message, ChannelAccount
- domain enums: Channel, MessageDirection, MessageStatus, MessageOrigin
- domain event: InboundEvent
- domain ports: MessagingChannel, ConversationRepository,
  MessageRepository, ChannelAccountRepository, WebhookEventRepository
- MessagingChannel re-exported from src/core/ports
- src/lib/runtime/background.ts: runInBackground via Cloudflare
  waitUntil (falls back to fire-and-forget with error logging)

Risk: none
FOR UPDATE SKIP LOCKED only holds while messaging_claim_retry runs, so a
second sweep could reclaim an event the first one was still processing.
Add webhook_events.last_attempt_at and only reclaim events with no
attempt in the last 2 minutes.
- IngestInboundEvent: inbound messages and echoes through the atomic SQL
  functions, race-safe conversation creation, lead linking by scoped id,
  attachment placeholders
- DeliverMessage: never downgrades an echo-adopted row and writes no legacy
  activity for failed sends
- ProcessWebhookEvent: bounded retries (failed after the 3rd attempt) and
  no double attempt count for sweep-claimed events
- SweepWebhookEvents: atomic claim of 5 events and 30-day purge
- In-memory store mirroring the SQL function semantics for tests
- GraphApiError keeps the previous send error messages for existing callers
- MetaInstagramChannel: HMAC verify, body-hash event id, parse of every
  entry/messaging item (messages, echoes, attachments), send that never
  throws with readable hints and a 15 s timeout
- Supabase repositories with explicit user ids, race-safe conversation
  findOrCreate and pending-only failure marking
- SQL executors, createAdminClient and messagingModule factory
- storeToken keeps channel_accounts in sync
- messaging_start_attempt takes the retry lease atomically; claim_retry
  fixed for the Postgres 42702 ambiguous column error
Two migrations shared version 20260723, so supabase db reset and db push
failed on schema_migrations_pkey. The renamed migrations were already
applied to production by hand; their history was repaired as applied.
@juancodedev juancodedev changed the title feat(messaging): messaging pipeline foundation (schema, domain, use cases) feat(messaging): messaging pipeline foundation (schema, domain, use cases, adapters) Nov 5, 2026
- Verify the HMAC before any database access; bad signature answers 401
- Claim each delivery by body hash: duplicates answer 200 without
  processing, a failed claim answers 500 so Meta retries
- Process new events in the background via ProcessWebhookEvent
- Add GET /api/webhook/instagram/sweep, guarded by a constant-time
  Bearer CRON_SECRET check
- Owner resolution keeps the several-users drop rule and the single
  connected account fallback
- Document CRON_SECRET and SUPABASE_SERVICE_ROLE_KEY
- Migration B defines messaging_backfill_instagram_history(): seeds
  channel_accounts from user_secrets, creates placeholder accounts, copies
  INSTAGRAM_MESSAGE activities into conversations and messages
- Additive and idempotent: never writes legacy tables, keyed on
  legacy_activity_id, counters only grow, advisory lock against
  concurrent runs; EXECUTE revoked from anon and authenticated
- psql behaviour test in supabase/tests for reuse by test:db
- Rollout runbook: apply B, backfill, verify, backfill again right
  before deploy, catch-up, rollback
- Ignore the Supabase CLI .branches directory
…ables

- Inbox, conversation and lead endpoints read conversations/messages;
  a key resolves to a set of conversations (lead:<id>, unlinked:<igsid>)
- New PATCH /api/messages/read; unread badge sums unread_count
- Sends and the auto trigger go through DeliverMessage (origin auto),
  502 responses add a hint
- Activity-level read/unread keeps the conversation badge in sync
- OpenAPI documents the messaging endpoints and schemas
- Remove the spec of the activities-based conversations count
… deleted

Conversations reference leads without ON DELETE, so deleting such a lead
fails with a foreign key violation that surfaced as a generic error.
Map it to a ConflictError (409) with the reason, show it as a warning
toast in the leads table, and document the 409 in OpenAPI.
…trigger

worker.ts re-exports the OpenNext worker and its Durable Objects and adds
a scheduled handler that calls /api/webhook/instagram/sweep through the
worker's own fetch with the CRON_SECRET bearer. wrangler.toml uses it as
the entry point and runs it every 5 minutes. Verified with a wrangler
dry-run bundle.
…base

- test:db now resets the local Supabase stack and runs psql suites for
  ingest, echoes, delivery, webhook events, read state and RLS, plus
  concurrency probes with parallel sessions; the runner refuses any
  non-local database URL
- Migration 20261105000000: activity-level read sync only adjusts the
  conversation badge for inbound messages
…forbid negative unread counts

Migration 20261105000001: messaging_record_echo returns outcome
'duplicate' when a concurrent insert of the same mid wins the unique
index, instead of raising and leaving the webhook event for a retry.
conversations.unread_count gets a validated CHECK (>= 0).
@juancodedev
juancodedev marked this pull request as ready for review November 5, 2026 13:01
@juancodedev
juancodedev merged commit fe53cd8 into main Nov 5, 2026
4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant