2. Database schema (Drizzle ORM)
One pg-core schema, used unchanged by drizzle-orm/node-postgres and drizzle-orm/pglite.
IDs are prefixed, time-sortable strings generated by newId() in db/src/ids.ts (ws_,
con_, msg_…, UUIDv7 body, D25, D27). Ids generated by one process in the same
millisecond stay in generation order (RFC 9562 method 1, a 42-bit counter seeded at random
on each new millisecond, D67). Every row below a workspace cascades on workspace
deletion, so deleting an expired ephemeral workspace is a single DELETE.
The snippets below are the design; the source of truth is packages/db/src/schema/ and its
generated migrations. JSON column shapes (RateLimitSettings, SimulationSettings,
SimulationSettingsPatch, OverrideConfig, Address) are the types inferred from the Zod
schemas of @mailsink/contracts (type-only imports: db has no runtime dependency on Zod).
They are the parsed outputs, so code writes values that went through the contract (defaults
applied). schema/json-types.ts only keeps the shapes the contracts do not describe (SMTP
transcript lines).
Drivers, migrations and tests
Section titled “Drivers, migrations and tests”createDb(url)returns{ db, driver, client, close }.postgres:///postgresql://open apg.Pool;pglite://<dir>a persistent PGlite,pglite://memoryan in-memory one (defaultpglite://./data). Repositories take the driver-agnosticDatabase(or a transaction) asExecutor.drizzle-kit generate(pnpm --filter @mailsink/db db:generate) writes numbered SQL migrations intopackages/db/migrations/.migrate(handle)applies them, idempotently; on Postgres it holds a session advisory lock so the boot andmailsink migratenever race. The built CLI ships a copy of the folder indist/migrations. A generated migration may get hand-written data statements appended (backfills); each journalwhenmust be strictly greater than the previous one, or the migrator skips the migration (checked bytest/journal.test.ts). Pending migrations run in one transaction, where a value added to an existing enum (ALTER TYPE … ADD VALUE) cannot be used yet: a migration that writes the new value recreates the type instead (migration 0004,webhook_event).describeDb()from@mailsink/db/testingdeclares each suite twice:[pglite]on a fresh in-memory instance,[postgres]on a throwaway database created onTEST_DATABASE_URL(skipped when unset). Every suite owns its database, so test files run in parallel.- Job claims (D5): on Postgres
FOR UPDATE SKIP LOCKEDlets concurrent claimers pass over rows another transaction holds. PGlite has a single connection: statements are serialized, so claims never overlap and SKIP LOCKED never has anything to skip; the result (no job claimed twice) is the same.
Relations at a glance
Section titled “Relations at a glance”erDiagram
workspaces ||--o{ connections : has
workspaces ||--o{ api_keys : has
connections ||--o{ api_keys : has
workspaces ||--o{ overrides : has
connections ||--o{ overrides : scopes
workspaces ||--o{ templates : has
workspaces ||--o{ messages : has
connections ||--o{ messages : "sent via"
messages ||--o{ message_recipients : has
messages ||--o{ attachments : has
messages ||--o{ message_events : has
attachments }o--|| blobs : stores
messages }o--o| blobs : "raw EML"
workspaces ||--o{ suppressions : has
workspaces ||--o{ webhook_endpoints : has
connections ||--o{ webhook_endpoints : scopes
webhook_endpoints ||--o{ webhook_deliveries : has
message_events ||--o{ webhook_deliveries : triggers
webhook_deliveries ||--o{ webhook_attempts : has
workspaces ||--o{ api_logs : has
workspaces ||--o{ smtp_sessions : has
workspaces ||--o{ idempotency_keys : hasschema/enums.ts
Section titled “schema/enums.ts”import { pgEnum } from 'drizzle-orm/pg-core'
export const connectionKind = pgEnum('connection_kind', ['resend', 'brevo', 'smtp'])export const messageSource = pgEnum('message_source', ['native', 'resend', 'brevo', 'smtp'])export const deliveryStatus = pgEnum('delivery_status', [ 'queued', 'sent', 'delivered', 'deferred', 'soft_bounce', 'hard_bounce', 'complained', 'failed', 'invalid', 'suppressed',])export const eventType = pgEnum('event_type', [ 'accepted', 'sent', 'delivered', 'deferred', 'soft_bounce', 'hard_bounce', 'complained', 'failed', 'invalid', 'suppressed', 'opened', 'clicked',])export const eventOrigin = pgEnum('event_origin', ['simulation', 'api', 'ui', 'mcp'])export const recipientKind = pgEnum('recipient_kind', ['to', 'cc', 'bcc'])export const apiKeyScope = pgEnum('api_key_scope', ['workspace', 'connection'])export const suppressionReason = pgEnum('suppression_reason', ['hard_bounce', 'complained', 'manual'])// Outgoing webhook dialect, decoupled from the ingestion channel (D20).export const payloadFormat = pgEnum('payload_format', ['unified', 'resend', 'brevo'])// Canonical webhook events, the only form stored (D22). Dialect names are mapped at the// edges (API, UI, emitted payload), see 03-contracts.md « Webhooks ».export const webhookEvent = pgEnum('webhook_event', [ 'email.sent', 'email.delivered', 'email.deferred', 'email.soft_bounced', 'email.hard_bounced', 'email.complained', 'email.opened', 'email.clicked', 'email.suppressed', 'email.failed', 'email.invalid',])export const brevoAuthType = pgEnum('brevo_auth_type', ['none', 'bearer', 'basic'])export const replayMode = pgEnum('replay_mode', ['exact', 'resign'])export const webhookDeliveryStatus = pgEnum('webhook_delivery_status', [ 'pending', 'retrying', 'succeeded', 'failed',])export const apiDialect = pgEnum('api_dialect', [ 'native', 'resend', 'brevo', 'admin', 'capture', 'mcp',])export const smtpOutcome = pgEnum('smtp_outcome', ['accepted', 'rejected', 'auth_failed', 'error'])schema/workspaces.ts
Section titled “schema/workspaces.ts”import { sql } from 'drizzle-orm'import { boolean, index, integer, jsonb, pgTable, text, timestamp } from 'drizzle-orm/pg-core'import type { RateLimitSettings, SimulationSettings } from '@mailsink/contracts'
export const workspaces = pgTable('workspaces', { id: text('id').primaryKey(), // ws_… slug: text('slug').notNull().unique(), // acme-studio-staging name: text('name').notNull(), description: text('description'), ephemeral: boolean('ephemeral').notNull().default(false), idleTtlSeconds: integer('idle_ttl_seconds'), // null when persistent lastActivityAt: timestamp('last_activity_at', { withTimezone: true }).notNull().defaultNow(), // Denormalized last_activity_at + idle_ttl_seconds, maintained by activity.ts, // so the GC query is an index range scan. expiresAt: timestamp('expires_at', { withTimezone: true }), retentionSeconds: integer('retention_seconds').notNull().default(7 * 86_400), maxMessages: integer('max_messages'), // null = unbounded rateLimit: jsonb('rate_limit').$type<RateLimitSettings>(), // null = unlimited simulation: jsonb('simulation').$type<SimulationSettings>().notNull() .default(DEFAULT_SIMULATION_SETTINGS), // complete, see below metadata: jsonb('metadata').$type<Record<string, string>>(), // e.g. CI run id timezone: text('timezone').notNull().default('UTC'), // Brevo webhook `date` (D23) createdVia: text('created_via', { enum: ['ui', 'admin_api'] }).notNull(), createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),}, (t) => [ index('workspaces_expiry_idx').on(t.expiresAt).where(sql`${t.ephemeral}`), index('workspaces_picker_idx').on(t.ephemeral, t.name),])DEFAULT_SIMULATION_SETTINGS (exported by schema/workspaces.ts) is
SimulationSettings.parse({}): { rates: { delivered: 100 }, rules: [], latency: { minMs: 0, maxMs: 0 }, openRate: 0, clickRate: 0 }, so a stored row always has every key the contract
type promises (a test compares both). Migration 0000 stored {"rates":{"delivered":100}}
only; 0001 completes such rows with defaults || simulation (shallow merge, stored keys
win). Connection settings and overrides stay partial by design (SimulationSettingsPatch,
OverrideConfig): the resolver below fills absent keys.
schema/connections.ts and schema/keys.ts
Section titled “schema/connections.ts and schema/keys.ts”import type { RateLimitSettings, SimulationSettingsPatch } from '@mailsink/contracts'
export const connections = pgTable('connections', { id: text('id').primaryKey(), // con_… workspaceId: text('workspace_id').notNull() .references(() => workspaces.id, { onDelete: 'cascade' }), name: text('name').notNull(), // "Brevo - Transactionnel" kind: connectionKind('kind').notNull(), smtpUsername: text('smtp_username').unique(), // kind = smtp only smtpPasswordHash: text('smtp_password_hash'), // scrypt (D11) // Per-connection overrides of workspace defaults; null = inherit. retentionSeconds: integer('retention_seconds'), rateLimit: jsonb('rate_limit').$type<RateLimitSettings>(), simulation: jsonb('simulation').$type<SimulationSettingsPatch>(), // absent keys inherit disabledAt: timestamp('disabled_at', { withTimezone: true }), createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),}, (t) => [ index('connections_workspace_idx').on(t.workspaceId), check('connections_smtp_creds', sql`(${t.kind} = 'smtp') = (${t.smtpUsername} is not null)`),])
export const apiKeys = pgTable('api_keys', { id: text('id').primaryKey(), // key_… workspaceId: text('workspace_id').notNull() .references(() => workspaces.id, { onDelete: 'cascade' }), connectionId: text('connection_id') .references(() => connections.id, { onDelete: 'cascade' }), scope: apiKeyScope('scope').notNull(), // D12 name: text('name'), displayPrefix: text('display_prefix').notNull(), // "msk_live_3f9a…" hash: text('hash').notNull().unique(), // sha256(key) (D11) lastUsedAt: timestamp('last_used_at', { withTimezone: true }), revokedAt: timestamp('revoked_at', { withTimezone: true }), createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),}, (t) => [ check('api_keys_scope', sql`(${t.scope} = 'connection') = (${t.connectionId} is not null)`),])schema/overrides.ts
Section titled “schema/overrides.ts”import type { OverrideConfig } from '@mailsink/contracts'
export const overrides = pgTable('overrides', { id: text('id').primaryKey(), // ovr_… workspaceId: text('workspace_id').notNull() .references(() => workspaces.id, { onDelete: 'cascade' }), connectionId: text('connection_id') // null = whole workspace .references(() => connections.id, { onDelete: 'cascade' }), config: jsonb('config').$type<OverrideConfig>().notNull(), // rates, rules, latency, // chaos, rateLimit activatedVia: eventOrigin('activated_via').notNull(), expiresAt: timestamp('expires_at', { withTimezone: true }), // optional auto-reset createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(), resetAt: timestamp('reset_at', { withTimezone: true }), // null = active}, (t) => [ // At most one active override per scope; history is kept for the logs. uniqueIndex('overrides_active_scope_uq') .on(t.workspaceId, sql`coalesce(${t.connectionId}, '')`) .where(sql`${t.resetAt} is null`),])Resolution order, computed by simulation/settings-resolver.ts, field by field:
connection override > workspace override > connection settings > workspace settings.
Expired overrides (expires_at < now) are ignored at read time and closed by the scheduler.
schema/templates.ts (Brevo templateId)
Section titled “schema/templates.ts (Brevo templateId)”export const templates = pgTable('templates', { id: text('id').primaryKey(), // tpl_… workspaceId: text('workspace_id').notNull() .references(() => workspaces.id, { onDelete: 'cascade' }), externalId: integer('external_id').notNull(), // Brevo numeric id name: text('name').notNull(), subject: text('subject').notNull(), // may contain {{ params.x }} html: text('html'), text: text('text'), sender: jsonb('sender').$type<Address>(), // contracts Address createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),}, (t) => [uniqueIndex('templates_external_uq').on(t.workspaceId, t.externalId)])schema/blobs.ts (D8)
Section titled “schema/blobs.ts (D8)”const bytea = customType<{ data: Uint8Array }>({ dataType: () => 'bytea' })
export const blobs = pgTable('blobs', { id: text('id').primaryKey(), // blob_… workspaceId: text('workspace_id').notNull() .references(() => workspaces.id, { onDelete: 'cascade' }), sha256: text('sha256').notNull(), sizeBytes: integer('size_bytes').notNull(), data: bytea('data').notNull(), createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),}, (t) => [uniqueIndex('blobs_dedup_uq').on(t.workspaceId, t.sha256)])Orphan blobs (after message purge) are removed by the retention job. References to a blob
use on delete cascade (attachments) and on delete set null (raw EML) rather than the
default no action (D26): with no action, Postgres checks the reference as soon as the
workspace cascade deletes the blob, before it has deleted the attachment rows, and the
whole DELETE FROM workspaces fails. The orphan-only blob GC never triggers these actions.
schema/messages.ts
Section titled “schema/messages.ts”import type { Address } from '@mailsink/contracts' // { email, name? }
export const messages = pgTable('messages', { id: text('id').primaryKey(), // msg_… workspaceId: text('workspace_id').notNull() .references(() => workspaces.id, { onDelete: 'cascade' }), connectionId: text('connection_id') .references(() => connections.id, { onDelete: 'set null' }), source: messageSource('source').notNull(), providerMessageId: text('provider_message_id').notNull(), // Resend uuid, Brevo <…@…> from: jsonb('from').$type<Address>().notNull(), replyTo: jsonb('reply_to').$type<Address[]>(), subject: text('subject').notNull().default(''), html: text('html'), text: text('text'), headers: jsonb('headers').$type<Record<string, string>>().notNull().default({}), tags: jsonb('tags').$type<{ name: string; value: string }[]>().notNull().default([]), metadata: jsonb('metadata').$type<Record<string, unknown>>(), templateRef: jsonb('template_ref') .$type<{ templateId: number; params: Record<string, unknown> }>(), links: jsonb('links').$type<{ url: string; text?: string }[]>().notNull().default([]), rawBlobId: text('raw_blob_id') // D9 .references(() => blobs.id, { onDelete: 'set null' }), // D26 sizeBytes: integer('size_bytes').notNull(), status: deliveryStatus('status').notNull().default('queued'), // aggregate of recipients // Snapshot of what the simulation decided: overrideId, rule matched, latencyMs… // Demo messages start with `{ rules }`, their own temporary rule set (D211). simulation: jsonb('simulation').$type<Record<string, unknown>>(), idempotencyKey: text('idempotency_key'), createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(), statusUpdatedAt: timestamp('status_updated_at', { withTimezone: true }).notNull().defaultNow(),}, (t) => [ index('messages_raw_blob_idx').on(t.rawBlobId), // blob GC, set null lookups // Keyset (created_at, id) of the capture listing and per-workspace retention range scans. // Ascending: scanned backward it serves `order by created_at desc, id desc` (D69). index('messages_ws_created_idx').on(t.workspaceId, t.createdAt, t.id), index('messages_ws_status_idx').on(t.workspaceId, t.status), index('messages_ws_connection_idx').on(t.workspaceId, t.connectionId, t.createdAt.desc()), index('messages_tags_gin').using('gin', t.tags), // Capture full text: the very expression of search-document.ts (D69). index('messages_search_gin').using('gin', searchDocument(t)), uniqueIndex('messages_provider_id_uq').on(t.workspaceId, t.providerMessageId),])
export const messageRecipients = pgTable('message_recipients', { id: text('id').primaryKey(), // rcp_… messageId: text('message_id').notNull() .references(() => messages.id, { onDelete: 'cascade' }), workspaceId: text('workspace_id').notNull(), // denormalized for search kind: recipientKind('kind').notNull(), email: text('email').notNull(), // lower-cased name: text('name'), status: deliveryStatus('status').notNull().default('queued'), statusReason: text('status_reason'), // "rule *+bounce@*" updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),}, (t) => [ index('recipients_ws_email_idx').on(t.workspaceId, t.email), index('recipients_message_idx').on(t.messageId),])
export const attachments = pgTable('attachments', { id: text('id').primaryKey(), // att_… messageId: text('message_id').notNull() .references(() => messages.id, { onDelete: 'cascade' }), filename: text('filename'), contentType: text('content_type').notNull(), contentId: text('content_id'), // inline cid: disposition: text('disposition', { enum: ['attachment', 'inline'] }).notNull(), sizeBytes: integer('size_bytes').notNull(), blobId: text('blob_id').notNull() .references(() => blobs.id, { onDelete: 'cascade' }), // D26}, (t) => [ index('attachments_message_idx').on(t.messageId), index('attachments_blob_idx').on(t.blobId),])schema/events.ts and schema/suppressions.ts
Section titled “schema/events.ts and schema/suppressions.ts”export const messageEvents = pgTable('message_events', { id: text('id').primaryKey(), // evt_… (also SSE id) workspaceId: text('workspace_id').notNull() .references(() => workspaces.id, { onDelete: 'cascade' }), messageId: text('message_id').notNull() .references(() => messages.id, { onDelete: 'cascade' }), recipientEmail: text('recipient_email'), type: eventType('type').notNull(), origin: eventOrigin('origin').notNull(), data: jsonb('data').$type<{ url?: string; userAgent?: string; reason?: string; smtpCode?: number }>(), occurredAt: timestamp('occurred_at', { withTimezone: true }).notNull().defaultNow(),}, (t) => [ index('events_message_idx').on(t.messageId, t.occurredAt), index('events_ws_time_idx').on(t.workspaceId, t.occurredAt),])
export const suppressions = pgTable('suppressions', { id: text('id').primaryKey(), // sup_… workspaceId: text('workspace_id').notNull() .references(() => workspaces.id, { onDelete: 'cascade' }), email: text('email').notNull(), // lower-cased reason: suppressionReason('reason').notNull(), messageId: text('message_id').references(() => messages.id, { onDelete: 'set null' }), createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),}, (t) => [uniqueIndex('suppressions_ws_email_uq').on(t.workspaceId, t.email)])schema/webhooks.ts
Section titled “schema/webhooks.ts”export const webhookEndpoints = pgTable('webhook_endpoints', { id: text('id').primaryKey(), // whe_… // Numeric id required by the Brevo payload (`id` = webhook id). numericId: integer('numeric_id').generatedAlwaysAsIdentity().notNull().unique(), workspaceId: text('workspace_id').notNull() .references(() => workspaces.id, { onDelete: 'cascade' }), // Scope: a connection (only its emails) or null = Workspace (every connection). connectionId: text('connection_id') .references(() => connections.id, { onDelete: 'cascade' }), url: text('url').notNull(), // Default at creation: connection kind for resend/brevo, 'unified' for smtp or // workspace scope. Always explicitly settable (D20). payloadFormat: payloadFormat('payload_format').notNull(), events: webhookEvent('events').array().notNull(), // canonical only (D22) // unified: HMAC key; resend: whsec_<base64> Svix key; brevo: bearer token or // "user:password" for basic auth (D11: stored in clear because it signs/authenticates). secret: text('secret'), brevoAuth: brevoAuthType('brevo_auth').notNull().default('none'), customHeaders: jsonb('custom_headers').$type<{ key: string; value: string }[]>() .notNull().default([]), // Brevo `headers` parity description: text('description'), enabled: boolean('enabled').notNull().default(true), createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),}, (t) => [ index('webhook_endpoints_scope_idx').on(t.workspaceId, t.connectionId), check('webhook_secret_required', sql`${t.payloadFormat} = 'brevo' or ${t.secret} is not null`),])
export const webhookDeliveries = pgTable('webhook_deliveries', { id: text('id').primaryKey(), // whd_… (= svix-id, // X-Mailsink-Delivery-Id) workspaceId: text('workspace_id').notNull() .references(() => workspaces.id, { onDelete: 'cascade' }), endpointId: text('endpoint_id').notNull() .references(() => webhookEndpoints.id, { onDelete: 'cascade' }), eventId: text('event_id').references(() => messageEvents.id, { onDelete: 'set null' }), messageId: text('message_id').references(() => messages.id, { onDelete: 'set null' }), // Format snapshot: later endpoint edits never change what a delivery sends. payloadFormat: payloadFormat('payload_format').notNull(), canonicalEvent: webhookEvent('canonical_event').notNull(), // email.soft_bounced dialectEvent: text('dialect_event').notNull(), // email.delivery_delayed, // soft_bounce… recipient: text('recipient'), // Exact serialized bytes, signed and sent as is by every attempt and replay (D24). body: text('body').notNull(), contentType: text('content_type').notNull().default('application/json'), status: webhookDeliveryStatus('status').notNull().default('pending'), attemptCount: integer('attempt_count').notNull().default(0), nextAttemptAt: timestamp('next_attempt_at', { withTimezone: true }), lastStatusCode: integer('last_status_code'), replayOf: text('replay_of'), // whd_… of the original replayMode: replayMode('replay_mode'), // null unless a replay createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),}, (t) => [ index('deliveries_ws_time_idx').on(t.workspaceId, t.createdAt.desc()), index('deliveries_message_idx').on(t.messageId), index('deliveries_ws_format_idx').on(t.workspaceId, t.payloadFormat), // log facet])
export const webhookAttempts = pgTable('webhook_attempts', { id: text('id').primaryKey(), deliveryId: text('delivery_id').notNull() .references(() => webhookDeliveries.id, { onDelete: 'cascade' }), attemptNo: integer('attempt_no').notNull(), // Headers exactly as sent, signature headers included, unredacted: an `exact` replay // copies them byte for byte. The UI masks Authorization values behind a reveal toggle. requestHeaders: jsonb('request_headers').$type<Record<string, string>>().notNull(), signedAt: integer('signed_at'), // unix ts used to sign responseStatus: integer('response_status'), responseBody: text('response_body'), // truncated to 4 KB durationMs: integer('duration_ms').notNull(), error: text('error'), // DNS, timeout, TLS… createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),}, (t) => [index('attempts_delivery_idx').on(t.deliveryId)])How the webhook tables are written (#32, #33, D135 to D144, D152 to D155, no migration):
webhook_endpoints.eventsholds canonical events only, sorted in enum order. For the brevo formatsecretholds the bearer token oruser:password(null withbrevo_auth = 'none'); leaving brevo writes a freshwhsec_secret, so thewebhook_secret_requiredcheck always holds.- Migration 0004 (#153): adds the
invalidstatus and event type andemail.invalid; subscribes the Resend endpoints that receiveemail.failedtoemail.invalidtoo (emitted under that name, D280); moves credentials written in the URL of a brevo endpoint withbrevo_auth = 'none'(stored before D278) tobrevo_auth = 'basic', percent-decoded, a part that does not decode kept as written (D281). Other rows with credentials in their URL (other formats, explicit bearer or basic) keep the send-time fallback of D278. - A delivery row is inserted with its serialized
bodyin the same transaction as its firstdeliver_webhookjob (payload = { deliveryId, attemptNo: 1 }). Each attempt inserts onewebhook_attemptsrow (idwha_…) and updates the delivery (attempt_count,last_status_code,status,next_attempt_at) in one transaction, with the next attempt’s job when it is not final.attempt_count >= attemptNomakes a replayed job a no-op. replay_ofalways holds the first delivery of a replay chain (its id is the signing id of every replay). A test send (POST /capture/webhooks/:id/test) hasevent_idandmessage_idnull.- Nothing prevents two deliveries for one (endpoint, event) pair: the fan-out runs once,
in the transaction that writes the events (ingestion
suppressed, a simulation run, manual events; D152, D153), so a crash loses or keeps both together. - Retention (D154,
repositories/retention-webhooks.ts): the retention pass deletes thesucceededandfaileddeliveries older than the effective retention of their endpoint scope (connectionretention_secondswhen the endpoint has a connection that sets one, else the workspace’s); attempts cascade. One range scan per endpoint ondeliveries_ws_time_idxthrough alateral (… offset 0)subquery, as for messages.pendingandretryingdeliveries are kept until they finish.
schema/logs.ts
Section titled “schema/logs.ts”export const apiLogs = pgTable('api_logs', { id: text('id').primaryKey(), // req_… (X-Request-Id) workspaceId: text('workspace_id') // null on auth failure .references(() => workspaces.id, { onDelete: 'cascade' }), connectionId: text('connection_id').references(() => connections.id, { onDelete: 'set null' }), dialect: apiDialect('dialect').notNull(), method: text('method').notNull(), path: text('path').notNull(), statusCode: integer('status_code').notNull(), durationMs: integer('duration_ms').notNull(), requestHeaders: jsonb('request_headers').$type<Record<string, string>>(), // redacted requestBody: jsonb('request_body'), // attachments stripped responseHeaders: jsonb('response_headers') // redacted, migration 0003 .$type<Record<string, string>>(), responseBody: jsonb('response_body'), // both bodies truncated messageIds: text('message_ids').array(), errorCode: text('error_code'), // rate_limited, chaos_injected… ip: text('ip'), createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),}, (t) => [index('api_logs_ws_time_idx').on(t.workspaceId, t.createdAt.desc())])
export const smtpSessions = pgTable('smtp_sessions', { id: text('id').primaryKey(), // smtp_… workspaceId: text('workspace_id').references(() => workspaces.id, { onDelete: 'cascade' }), connectionId: text('connection_id').references(() => connections.id, { onDelete: 'set null' }), remoteAddress: text('remote_address').notNull(), clientHostname: text('client_hostname'), authUser: text('auth_user'), secure: boolean('secure').notNull().default(false), transcript: jsonb('transcript') // capped, AUTH redacted .$type<TranscriptLine[]>().notNull(), // { at, dir: 'C' | 'S', line } messageIds: text('message_ids').array(), outcome: smtpOutcome('outcome').notNull(), error: text('error'), startedAt: timestamp('started_at', { withTimezone: true }).notNull(), endedAt: timestamp('ended_at', { withTimezone: true }),}, (t) => [index('smtp_sessions_ws_time_idx').on(t.workspaceId, t.startedAt.desc())])Writers (#35, D145 to D147): core/logs/writer.ts (createLogWriter, one per runtime)
inserts both tables asynchronously, after the response left or the SMTP session ended;
a failed insert is logged, never raised (a row whose workspace or connection was deleted
meanwhile, foreign key violation, is dropped silently). What a row keeps:
request_headers: every header,Authorization,Proxy-Authorization,api-keyandx-api-keyreduced to their scheme and Mailsink key prefix (Bearer msk_[redacted]), cookies[redacted].response_headers(migration 0003, proposition D215): every header of the answer (X-Request-Id, rate limit headers,Retry-After,Content-Type…), reduced by the same rules; null on rows written before the migration (the API answers{}).request_body,response_body: parsed JSON (raw text otherwise), JSON and text bodies only (downloads and SSE givenull). Attachmentcontentbecomes[omitted: N chars](attachments, Brevoattachment, at any depth); values under secret-looking keys (password,apiKey,workspaceKey,secret,token) and Mailsink keys inside strings keep only their prefix. Beyond 32 768 characters of JSON the column holds{ truncated: true, size, preview }. A request body is read only once the caller is authenticated, and not when it exceedsMAILSINK_MAX_MESSAGE_BYTES.message_ids: themsg_…ids an ingestion response names (id,data[].id, BrevomessageId); empty for the other surfaces.error_code: theDomainErrorcode of a refused call (unauthorized,rate_limited,chaos_injected,validation_error…),internal_errorfor an unexpected failure.ip: the socket address when the server exposes it (srvxrequest.ip), elsenull.transcript: at most 1 000 lines (first and last halves around a[… N lines omitted]marker), 1 000 characters per line;AUTH <mechanism> <secret>and every client line answering a334challenge are[redacted].erroris capped at 2 000 characters.
Reads (repositories/logs-api.ts, logs-smtp.ts) are scoped to one workspace, filtered,
sorted (createdAt, durationMs, statusCode; sessions by startedAt, ties broken by
id) and paged by offset with a count(*) total: the UI pager needs page numbers, and the
retention keeps the tables small (D147). listApiLogs and findApiLog take a null
workspace for the rows without one (Admin calls, auth failures), read by
GET /admin/logs/api (D151, on api_logs_ws_time_idx, nulls included); SMTP sessions
without workspace are only reachable in the database. Both expire with the default
retention (D49).
schema/idempotency.ts and schema/jobs.ts
Section titled “schema/idempotency.ts and schema/jobs.ts”export const idempotencyKeys = pgTable('idempotency_keys', { workspaceId: text('workspace_id').notNull() .references(() => workspaces.id, { onDelete: 'cascade' }), key: text('key').notNull(), requestHash: text('request_hash').notNull(), // mismatch -> 409/422 responseStatus: integer('response_status').notNull(), responseBody: jsonb('response_body').notNull(), expiresAt: timestamp('expires_at', { withTimezone: true }).notNull(), // now + 24 h}, (t) => [primaryKey({ columns: [t.workspaceId, t.key] })])
export const jobs = pgTable('jobs', { // D5 id: bigserial('id', { mode: 'number' }).primaryKey(), kind: text('kind', { enum: ['simulate_delivery', 'deliver_webhook'] }).notNull(), workspaceId: text('workspace_id').notNull() .references(() => workspaces.id, { onDelete: 'cascade' }), payload: jsonb('payload').notNull(), runAt: timestamp('run_at', { withTimezone: true }).notNull().defaultNow(), attempts: integer('attempts').notNull().default(0), lockedUntil: timestamp('locked_until', { withTimezone: true }), lastError: text('last_error'), failedAt: timestamp('failed_at', { withTimezone: true }), // given up on (D65)}, (t) => [index('jobs_due_idx').on(t.runAt)])Periodic tasks (retention, ephemeral GC, override expiry, idempotency cleanup) are
in-process schedulers, not rows: they are idempotent DELETE … WHERE statements.
The jobs table only holds pending, leased or failed work: a job done is deleted, a job
given up on keeps its last_error with run_at = 9999-12-31 and failed_at set (D47,
D65). The retention pass (repositories/retention.ts, D49) deletes, in order: expired
messages (cascading to recipients, attachments, events), messages over max_messages
(oldest first), orphan blobs, expired idempotency keys, expired api_logs and
smtp_sessions, finished webhook deliveries past their retention (D154), then failed jobs
older than MAILSINK_JOBS_FAILED_RETENTION_SECONDS
(7 days by default). Migration 0002 sets failed_at = now() on jobs failed before it.
Migration 0003 adds api_logs.response_headers (nullable, no backfill).
A simulate_delivery run commits its writes and its follow-up job (D70) in one
transaction, but the claimed job is deleted afterwards, by a separate statement. A crash
between the two leaves the claimed job leased: once locked_until passes it runs again,
finds nothing queued nor due, so it writes no event and publishes nothing, yet it enqueues
a follow-up job again at the same pending decision when one remains. The message then has two
follow-up jobs for one decision; the first to run applies it, the second finds nothing due
and completes without effect (D99, known limit, no fix planned: a duplicate job costs one
idle run).
Retention statements are written as range scans per workspace or connection (D69): one
DELETE … USING connections c CROSS JOIN LATERAL (… OFFSET 0) for rows whose connection
sets retention_seconds, one over workspaces for the others (NOT EXISTS on a connection
override), and a plain one for rows without a workspace. The OFFSET 0 keeps the planner
from flattening the lateral subquery, which it would then estimate poorly and answer with a
full table scan. Measured on Postgres 17 with 470 000 messages, 50 workspaces and 200
connections (steady state, a handful of rows to purge): the former correlated subqueries
took 5 s per pass (sequential scan, two subplans per row), the range scans 20 ms + 30 ms on
messages_ws_connection_idx and messages_ws_created_idx. max_messages
(enforceMaxMessages) reads each bounded workspace backward on messages_ws_created_idx:
80 ms for five workspaces capped at 1 000; on Postgres 18, steady state with nothing to
purge, 35 ms for 200 workspaces capped at 1 000 (301 000 messages) and 240 ms for 1 000
such workspaces (1.1 M messages). A set-based rewrite (row_number() over (partition by workspace_id)) took 1.9 s on the second data set (it sorts every message of the bounded
workspaces), so the lateral form stays (#77).
Capture full text search (q) uses messages_search_gin, an expression index on
to_tsvector('simple', left(subject || ' ' || text || ' ' || html, 100000))
(search-document.ts). The query must reuse that expression unchanged to hit the index.
The left(…, 100000) bound is required: a tsvector is capped at 1 MB and one large body
would otherwise fail its insert (index maintenance) and every search of its workspace; only
the first 100 000 characters of a message are searchable (worst case measured: unique
two-character CJK words, 470 kB). Same data set: a two-word search of a workspace went from
69 ms (filter over every message of the workspace) to 5 ms; the keyset page from 39 ms to
0.2 ms (index-only backward scan instead of a sort).
Key queries
Section titled “Key queries”-- Ephemeral GC (every 30 s)DELETE FROM workspaces WHERE ephemeral AND expires_at < now() RETURNING id;
-- Activity touch (throttled, D16)UPDATE workspaces SET last_activity_at = now(), expires_at = CASE WHEN ephemeral THEN now() + make_interval(secs => idle_ttl_seconds) ENDWHERE id = $1;
-- Job claimUPDATE jobs SET locked_until = now() + interval '30 seconds', attempts = attempts + 1WHERE id IN (SELECT id FROM jobs WHERE run_at <= now() AND (locked_until IS NULL OR locked_until < now()) ORDER BY run_at LIMIT 20 FOR UPDATE SKIP LOCKED)RETURNING *;