Repository navigation
feat(messaging): messaging pipeline foundation (schema, domain, use cases, adapters) - #86
Merged
Merged
Conversation
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.
- 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
marked this pull request as ready for review
November 5, 2026 13:01
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Foundation of the
messaging-pipelinechange: Instagram DMs move fromactivitiesrows (direction parsed from the title, nomid, no dedup) to dedicated messaging tables behind aMessagingChannelport. 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) andjudgment-day.md(dual adversarial review; 13 warnings incorporated).What's in it
supabase/migrations/20261103000000_messaging_tables.sqlchannel_accounts,conversations,messages,webhook_events; RLS with ownershipWITH CHECK; partial unique index onmessages.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.tssrc/modules/messaging/domainInboundEvent, ports (MessagingChannel, repositories,LeadLookup)src/modules/messaging/application/use-casesIngestInboundEvent(messages + echoes),DeliverMessage,ProcessWebhookEvent,SweepWebhookEvents,MarkConversationReadsrc/modules/messaging/testing/InMemoryMessagingStore.tssrc/modules/messaging/infrastructureMetaInstagramChannel, Supabase repositories, SQL executors (T5);GraphApiError,createAdminClient,channel_accountssync on token storesrc/lib/runtimerunInBackgroundovergetCloudflareContext().ctx.waitUntilpackage.json,supabase/config.tomlpnpm test:dbscript + local Supabase config for SQL behaviour testsNotable fixes during implementation
6dc8bfe:FOR UPDATE SKIP LOCKEDonly holds whilemessaging_claim_retryruns, so an overlapping sweep could reclaim an event still being processed. Added awebhook_events.last_attempt_atlease (reclaim only after 2 min without an attempt). Found by the overlapping-sweep use-case test.DeliverMessagenever downgrades a row an echo already madesent, and failed sends write no legacy activity (a code rollback would otherwise show them as sent).Test plan
npx tsc --noEmit— 0 errorsnpx eslint . --max-warnings 30— 0 errors, 14 pre-existing warningspnpm test— 93 suites, 654 tests passedpnpm test:dbagainst 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 farNot 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) · T10test:dbrun.Production DB:
20261103000000_messaging_tables.sqlwas applied on 2026-11-04 (additive only; tables are empty and unused until the webhook is switched). Prodschema_migrationshad drifted (13 migrations applied by hand but unrecorded); they were verified against a schema dump and marked applied withsupabase migration repair, and the 8-digit migrations were renamed to unique 14-digit versions (0354ce4).🤖 Generated with Claude Code