Repository navigation
Conversation
📝 WalkthroughWalkthroughThis PR introduces API key authentication infrastructure, centralizes database/environment access through a new runtime module, implements comprehensive email sending and reading capabilities with pagination, and refactors database access patterns across multiple modules to eliminate explicit DB parameters. Includes new oRPC endpoints and GitHub Actions CI workflow. Changes
Sequence DiagramssequenceDiagram
actor Client
participant API as API Handler
participant AuthMod as Auth Module
participant DB as Database
Client->>API: POST /api-keys with name, expiry
API->>AuthMod: createApiKeyForUser(userId, name, expiresAt)
AuthMod->>AuthMod: Generate secret, compute hash, create prefix/lastFour
AuthMod->>DB: Insert into api_keys table
DB-->>AuthMod: Row stored
AuthMod-->>API: Return raw key + metadata
API-->>Client: 200 with key, metadata
Client->>API: GET /api/inboxes with Authorization: Bearer {apiKey}
API->>AuthMod: extractApiKey(request)
AuthMod-->>API: Raw API key
API->>AuthMod: authenticateApiKey(rawKey)
AuthMod->>AuthMod: Parse, hash, validate expiry/revocation
AuthMod->>DB: Fetch by key_prefix, check revoked_at
DB-->>AuthMod: api_key row
AuthMod->>DB: Update last_used_at timestamp
AuthMod-->>API: { id, userId, name }
API->>API: Route as authenticated user
API-->>Client: 200 with user inboxes
sequenceDiagram
actor User
participant API as API Handler
participant OutboundMod as Outbound Module
participant InboxDB as Inbox DB
participant ThreadDB as Thread DB
participant EmailProvider as Email Provider
participant Storage as R2 Storage
participant EventQueue as Event Queue
User->>API: POST /messages/send (inboxId, recipient, body)
API->>OutboundMod: sendMessage(userId, input)
OutboundMod->>InboxDB: Verify inbox ownership
InboxDB-->>OutboundMod: Inbox confirmed
OutboundMod->>ThreadDB: Ensure thread exists, get reply context
ThreadDB-->>OutboundMod: Thread, headers (In-Reply-To, References)
OutboundMod->>OutboundMod: Normalize body, store inline or check size
alt Body > MAX_SIZE
OutboundMod->>Storage: PUT large body to R2
Storage-->>OutboundMod: URL
end
OutboundMod->>OutboundMod: Build MIME headers, create Message-ID
OutboundMod->>EmailProvider: send(to, from, subject, headers, body)
alt Provider accepts
EmailProvider-->>OutboundMod: Success
OutboundMod->>ThreadDB: Update message status=sent
OutboundMod->>EventQueue: Emit message.sent.accepted event
else Provider rejects
EmailProvider-->>OutboundMod: Error
OutboundMod->>ThreadDB: Update message status=failed, error_code
OutboundMod->>EventQueue: Emit message.sent.failed event
end
OutboundMod-->>API: SendMessageResult
API-->>User: 200 with message metadata
sequenceDiagram
actor User
participant API as API Handler
participant ReadMod as Read Module
participant DB as Database
participant Storage as R2 Storage
User->>API: GET /inboxes/{inboxId}/threads?limit=10
API->>ReadMod: listThreadsByInboxForUser(userId, inboxId)
ReadMod->>DB: Validate inbox ownership
DB-->>ReadMod: Confirmed
ReadMod->>DB: Query threads, count messages per thread, fetch latest message
DB-->>ReadMod: Thread list with counts, cursors
ReadMod-->>API: ThreadListResult with nextCursor
API-->>User: 200 with thread summaries
User->>API: GET /messages/{messageId}
API->>ReadMod: getMessageForUser(userId, inboxId, messageId)
ReadMod->>DB: Fetch message row, validate ownership
DB-->>ReadMod: Message row
ReadMod->>ReadMod: Check body storage mode (inline/missing/oversized)
alt Inline body
ReadMod-->>API: Message with body
else Missing or oversized
ReadMod->>Storage: GET from R2
Storage-->>ReadMod: Body bytes
ReadMod-->>API: Message with fetched body
end
API-->>User: 200 with message detail
Estimated code review effort🎯 4 (Complex) | ⏱️ ~50 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 7
🧹 Nitpick comments (6)
src/lib/runtime.ts (1)
1-8: Consider lazy-initializing the Workers DB binding to reduce import-time coupling.
createDb(env.APP_DB)runs during module evaluation, causing any code path that imports#/lib/runtime(directly or indirectly) before mocking it to fail at import time. The repeatedvi.mock('#/lib/runtime')calls in test files confirm this brittleness. Whiledbis currently exported and re-exported via#/db/client, most code already usesgetDb()instead. Moving DB creation behindgetDb()and deprecating the directdbexport keeps Workers-only dependencies at the edge without breaking existing patterns.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/lib/runtime.ts` around lines 1 - 8, The module currently instantiates the Workers DB at import time via createDb(env.APP_DB) and exports db, which breaks tests that mock this module; change to lazy-initialize by removing the top-level createDb call and instead create and cache the DB inside getDb() (e.g., if cachedDb return it else set cachedDb = createDb(env.APP_DB) and return), keep exporting getDb() as the primary accessor, keep or mark the direct db export deprecated (do not instantiate it at module load) so imports that want the binding still work but tests can mock getDb() without import-time side effects; update references to use getDb() where feasible.src/lib/email/read.test.ts (1)
47-112: Add a same-timestamp pagination case.Both cursor tests use strictly increasing timestamps, but
src/lib/email/read.tsbreaks ties withidin both the query and cursor predicate. Without a fixture where multiple rows share the same timestamp, these tests won't catch duplicate/skip bugs in the tie-break path.Also applies to: 133-195
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/lib/email/read.test.ts` around lines 47 - 112, Add a test case that inserts at least two threads/messages with identical createdAt timestamps (use insertThreadWithMessage and the same createdAt value for two different threadId/messageId pairs) and then call listThreadsByInboxForUser to exercise cursor pagination; assert ordering uses the tie-break (id) consistently by checking the exact thread id sequence across pages and that nextCursor does not cause duplicates or skips. Ensure the duplicate-timestamp fixtures appear in the same test (or a new test) near the existing cursor pagination assertions so the tie-break path in listThreadsByInboxForUser is executed and validated.src/lib/api-keys.test.ts (1)
66-91: Consider adding test coverage for expired API keys.The
authenticateApiKeyfunction checksexpiresAt(persrc/lib/api-keys.tsLines 157-159), but there's no test verifying that expired keys are rejected. This edge case is worth covering.📝 Suggested additional test case
it('rejects expired api keys', async () => { const userId = await createUserRecord(harness.db, { id: 'user_api_keys_03', }) const created = await createApiKeyForUser({ name: 'Expiring key', userId, expiresAt: new Date(Date.now() - 1000).toISOString(), // Already expired }) await expect(authenticateApiKey(created.apiKey)).resolves.toBeNull() })🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/lib/api-keys.test.ts` around lines 66 - 91, Add a test that verifies authenticateApiKey rejects keys whose expiresAt is in the past: use createApiKeyForUser to create a key with expiresAt set to a timestamp before now (e.g. Date.now() - 1000), then call authenticateApiKey(created.apiKey) and assert it resolves to null; place this alongside the existing tests for valid/revoked keys in the same suite so expiresAt handling is covered.src/orpc/context.ts (1)
65-73: Consider more robust Bearer token case handling.The current implementation handles
Bearerandbearer, but RFC 7235 specifies the scheme is case-insensitive. Other variations likeBEARERorBeArErwould not be matched.♻️ Suggested case-insensitive check
function extractApiKey(request: Request) { const authorization = request.headers.get('authorization') - const bearerToken = authorization?.startsWith('Bearer ') - ? authorization.slice('Bearer '.length).trim() - : authorization?.startsWith('bearer ') - ? authorization.slice('bearer '.length).trim() - : null + const bearerToken = authorization?.toLowerCase().startsWith('bearer ') + ? authorization.slice('Bearer '.length).trim() + : null return bearerToken || request.headers.get('x-api-key')?.trim() || null }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/orpc/context.ts` around lines 65 - 73, The extractApiKey function currently only matches "Bearer " and "bearer " exactly; make the Bearer-scheme check case-insensitive per RFC 7235 by normalizing the authorization scheme (e.g., convert authorization to lowercase or use a case-insensitive regex) before slicing the token, or by splitting on whitespace and comparing the first token case-insensitively; update extractApiKey so it returns the token when the scheme equals "bearer" in any casing, falling back to x-api-key as before.src/orpc/procedures/threads.ts (1)
54-56: Redundant schema transformation can be simplified.The
.omit({ threadId: true }).extend({ threadId: threadMessageListInputSchema.shape.threadId })pattern produces an identical schema tothreadMessageListInputSchemadirectly. Since oRPC automatically merges path parameters into the input object with compact input structure (the default), the explicit re-declaration is unnecessary.♻️ Simplified schema usage
- .input(threadMessageListInputSchema.omit({ threadId: true }).extend({ - threadId: threadMessageListInputSchema.shape.threadId, - })) + .input(threadMessageListInputSchema)🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/orpc/procedures/threads.ts` around lines 54 - 56, The input schema for the procedure is redundantly rebuilt by omitting and then re-extending threadId; replace the .input call that uses threadMessageListInputSchema.omit({ threadId: true }).extend({ threadId: threadMessageListInputSchema.shape.threadId }) with the original threadMessageListInputSchema directly (remove the omit/extend pattern) so the procedure's .input uses threadMessageListInputSchema; update the .input invocation in the procedure definition in threads.ts where threadMessageListInputSchema is referenced.src/orpc/api-keys.test.ts (1)
96-131: Cover thex-api-keyauth path in this E2E test.This only exercises the Bearer branch, so the alternate header in the public contract can regress without this test noticing.
Suggested test addition
expect(inboxResponse.status).toBe(200) await expect(inboxResponse.json()).resolves.toMatchObject([ { id: inboxId, userId, }, ]) + + const headerResponse = await sendOpenApiRequest( + new Request('https://clankr.test/api/inboxes', { + headers: { + 'x-api-key': createdKey.apiKey, + }, + }), + ) + + expect(headerResponse.status).toBe(200)🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/orpc/api-keys.test.ts` around lines 96 - 131, Add assertions exercising the alternate API-key header path: use sendOpenApiRequest to call the inboxes endpoint with header 'x-api-key' set to createdKey.apiKey (in addition to the existing Bearer requests), assert status 200 and the expected JSON matches the inbox, then after calling the revoke endpoint (API key id from createdKey.metadata.id) repeat the inbox request with 'x-api-key' and assert a 401 unauthorized response; update src/orpc/api-keys.test.ts around the existing sendOpenApiRequest/inboxes and revoke blocks to include these 'x-api-key' checks so both auth branches are covered.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@src/lib/api-keys.ts`:
- Around line 169-177: The current auth flow updates lastUsedAt synchronously
using database.update(apiKeys).set({...}).where(eq(apiKeys.id, storedApiKey.id))
which can cause valid requests to fail if that write errors; make this update
best-effort by not letting write errors block auth: either fire-and-forget the
update (do not await the promise) or await it inside a try/catch and swallow/log
errors (use processLogger.warn or similar) so authentication returns success
regardless of the update outcome. Locate the update call in src/lib/api-keys.ts
(references: storedApiKey, lastUsedAt, apiKeys, database.update) and change it
to a non-fatal, best-effort write with errors handled but not propagated.
In `@src/lib/email/outbound.ts`:
- Around line 334-374: The ensureThread function races between
findExistingThreadId and insert: replace the read-then-insert with an atomic
upsert using emailThreads' dedupe key (subjectNormalized + inboxId +
participantHash) so concurrent sends cannot create multiple threadId rows; add a
unique constraint for that key in the DB schema (update src/db/schema.ts) and
change ensureThread to attempt an insert of a generated createThreadId() with
subjectNormalized, inboxId, participantHash and lastMessageAt, using your DB
client's upsert/ON CONFLICT...DO UPDATE (or equivalent) to return the canonical
threadId and update lastMessageAt, falling back to findExistingThreadId only if
necessary.
- Around line 153-231: The current flow calls env.EMAIL.send() after inserting a
pending row, but if updateOutboundMessageStatus() fails the send can be accepted
twice on retry; fix by using the persisted message row as the idempotency
source: before calling env.EMAIL.send() read the pending message (by
messageId/internetMessageId/threadId) and only call env.EMAIL.send() if its
status is still 'pending' (or providerMessageId is null), otherwise treat it as
already accepted and reuse the stored providerMessageId/sentAt; ensure
updateOutboundMessageStatus(messageId, ...) and emitSendEvent(...) operate on
that same persisted row; use pendingMessage.id or internetMessageId as the
stable idempotency key and add the status check/early-return around
env.EMAIL.send()/statusUpdate to avoid duplicate sends.
In `@src/lib/email/read.test.ts`:
- Around line 359-360: The fixture currently uses the nullish coalescing
operator on params.textBody and params.htmlBody which treats explicit null as
"use default"; change the defaults to only apply when the param is undefined so
explicit null stays null: replace uses of params.textBody ?? 'Hello world' and
params.htmlBody ?? null with undefined checks (e.g., params.textBody !==
undefined ? params.textBody : 'Hello world' and params.htmlBody !== undefined ?
params.htmlBody : null) in the fixture construction (refer to the
textBody/htmlBody fields where params is used in the test).
In `@src/lib/email/read.ts`:
- Around line 155-217: The thread previews and pagination currently pick and
sort messages by createdAt (see latestMessages query, the
orderBy(desc(emailMessages.createdAt), desc(emailMessages.id)) and nextCursor
construction using pageRows.at(-1)?.lastMessageAt); change both the selection
and ordering to use the same chronology key the thread uses (lastMessageAt which
is derived from receivedAt/sentAt) so you pick the true latest message and page
consistently: update the latestMessages query orderBy to
desc(emailMessages.lastMessageAt), desc(emailMessages.id) (and any other
selection that currently uses createdAt for chronology), ensure
latestMessageByThreadId population remains but keyed by threadId, and build
nextCursor using pageRows.at(-1)?.lastMessageAt (ISO string) so previews,
sorting and cursor paging all use lastMessageAt instead of createdAt (also apply
the same change in the other read path noted around lines 231-258).
- Around line 365-390: The current code calls
env.EMAIL_STORAGE.get(message.oversizedBodyR2Key) outside the try block so
transient R2 errors cause a 500; wrap the storage fetch in the same try that
parses the body so any error from EMAIL_STORAGE.get or from
oversizedBodySchema.parse is caught and returns the missing-body shape
(textBody: null, htmlBody: null, source: 'missing'). Locate the getWorkerEnv()
call and the EMAIL_STORAGE.get(...) invocation and move the fetch into the
try/catch (or add a surrounding try) that currently runs
oversizedBodySchema.parse to ensure both fetch and parse failures fall back to
the missing source.
In `@src/lib/email/test-harness.ts`:
- Around line 38-52: The send() method currently guards on this.nextError's
truthiness and will skip throwing scheduled falsy values (e.g., '', 0, false);
update the guard to explicitly check for null (e.g., this.nextError !== null) so
that any value set by failWith(error) (which accepts unknown) is thrown; adjust
the send() method’s conditional and keep clearing this.nextError after capturing
it, referencing the nextError property, failWith(), and send() methods.
---
Nitpick comments:
In `@src/lib/api-keys.test.ts`:
- Around line 66-91: Add a test that verifies authenticateApiKey rejects keys
whose expiresAt is in the past: use createApiKeyForUser to create a key with
expiresAt set to a timestamp before now (e.g. Date.now() - 1000), then call
authenticateApiKey(created.apiKey) and assert it resolves to null; place this
alongside the existing tests for valid/revoked keys in the same suite so
expiresAt handling is covered.
In `@src/lib/email/read.test.ts`:
- Around line 47-112: Add a test case that inserts at least two threads/messages
with identical createdAt timestamps (use insertThreadWithMessage and the same
createdAt value for two different threadId/messageId pairs) and then call
listThreadsByInboxForUser to exercise cursor pagination; assert ordering uses
the tie-break (id) consistently by checking the exact thread id sequence across
pages and that nextCursor does not cause duplicates or skips. Ensure the
duplicate-timestamp fixtures appear in the same test (or a new test) near the
existing cursor pagination assertions so the tie-break path in
listThreadsByInboxForUser is executed and validated.
In `@src/lib/runtime.ts`:
- Around line 1-8: The module currently instantiates the Workers DB at import
time via createDb(env.APP_DB) and exports db, which breaks tests that mock this
module; change to lazy-initialize by removing the top-level createDb call and
instead create and cache the DB inside getDb() (e.g., if cachedDb return it else
set cachedDb = createDb(env.APP_DB) and return), keep exporting getDb() as the
primary accessor, keep or mark the direct db export deprecated (do not
instantiate it at module load) so imports that want the binding still work but
tests can mock getDb() without import-time side effects; update references to
use getDb() where feasible.
In `@src/orpc/api-keys.test.ts`:
- Around line 96-131: Add assertions exercising the alternate API-key header
path: use sendOpenApiRequest to call the inboxes endpoint with header
'x-api-key' set to createdKey.apiKey (in addition to the existing Bearer
requests), assert status 200 and the expected JSON matches the inbox, then after
calling the revoke endpoint (API key id from createdKey.metadata.id) repeat the
inbox request with 'x-api-key' and assert a 401 unauthorized response; update
src/orpc/api-keys.test.ts around the existing sendOpenApiRequest/inboxes and
revoke blocks to include these 'x-api-key' checks so both auth branches are
covered.
In `@src/orpc/context.ts`:
- Around line 65-73: The extractApiKey function currently only matches "Bearer "
and "bearer " exactly; make the Bearer-scheme check case-insensitive per RFC
7235 by normalizing the authorization scheme (e.g., convert authorization to
lowercase or use a case-insensitive regex) before slicing the token, or by
splitting on whitespace and comparing the first token case-insensitively; update
extractApiKey so it returns the token when the scheme equals "bearer" in any
casing, falling back to x-api-key as before.
In `@src/orpc/procedures/threads.ts`:
- Around line 54-56: The input schema for the procedure is redundantly rebuilt
by omitting and then re-extending threadId; replace the .input call that uses
threadMessageListInputSchema.omit({ threadId: true }).extend({ threadId:
threadMessageListInputSchema.shape.threadId }) with the original
threadMessageListInputSchema directly (remove the omit/extend pattern) so the
procedure's .input uses threadMessageListInputSchema; update the .input
invocation in the procedure definition in threads.ts where
threadMessageListInputSchema is referenced.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 6c6a1896-43bc-47c3-bd8e-dd0ae0633906
📒 Files selected for processing (32)
.github/workflows/ci.ymldrizzle/0003_sweet_microchip.sqldrizzle/meta/0003_snapshot.jsondrizzle/meta/_journal.jsonmvp.mdsrc/db/client.tssrc/db/schema.tssrc/lib/api-keys.test.tssrc/lib/api-keys.tssrc/lib/auth.tssrc/lib/email/events.tssrc/lib/email/ids.test.tssrc/lib/email/ids.tssrc/lib/email/inbound.test.tssrc/lib/email/inbound.tssrc/lib/email/inboxes.test.tssrc/lib/email/inboxes.tssrc/lib/email/outbound.test.tssrc/lib/email/outbound.tssrc/lib/email/read.test.tssrc/lib/email/read.tssrc/lib/email/test-harness.test.tssrc/lib/email/test-harness.tssrc/lib/runtime.tssrc/orpc/api-keys.test.tssrc/orpc/context.tssrc/orpc/procedures/api-keys.tssrc/orpc/procedures/inboxes.tssrc/orpc/procedures/messages.tssrc/orpc/procedures/threads.tssrc/orpc/router.tssrc/worker.ts
| const now = new Date() | ||
|
|
||
| await database | ||
| .update(apiKeys) | ||
| .set({ | ||
| lastUsedAt: now, | ||
| updatedAt: now, | ||
| }) | ||
| .where(eq(apiKeys.id, storedApiKey.id)) |
There was a problem hiding this comment.
Don't fail auth when the usage timestamp write fails.
This adds a write to every authenticated request, and any transient update error here will reject an otherwise valid API key. lastUsedAt should be best-effort (or deferred) so auth availability doesn't depend on a secondary metadata write.
Suggested change
- await database
- .update(apiKeys)
- .set({
- lastUsedAt: now,
- updatedAt: now,
- })
- .where(eq(apiKeys.id, storedApiKey.id))
+ try {
+ await database
+ .update(apiKeys)
+ .set({
+ lastUsedAt: now,
+ updatedAt: now,
+ })
+ .where(eq(apiKeys.id, storedApiKey.id))
+ } catch (error) {
+ console.warn('Failed to update API key usage metadata.', {
+ apiKeyId: storedApiKey.id,
+ error,
+ })
+ }📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| const now = new Date() | |
| await database | |
| .update(apiKeys) | |
| .set({ | |
| lastUsedAt: now, | |
| updatedAt: now, | |
| }) | |
| .where(eq(apiKeys.id, storedApiKey.id)) | |
| const now = new Date() | |
| try { | |
| await database | |
| .update(apiKeys) | |
| .set({ | |
| lastUsedAt: now, | |
| updatedAt: now, | |
| }) | |
| .where(eq(apiKeys.id, storedApiKey.id)) | |
| } catch (error) { | |
| console.warn('Failed to update API key usage metadata.', { | |
| apiKeyId: storedApiKey.id, | |
| error, | |
| }) | |
| } |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/lib/api-keys.ts` around lines 169 - 177, The current auth flow updates
lastUsedAt synchronously using
database.update(apiKeys).set({...}).where(eq(apiKeys.id, storedApiKey.id)) which
can cause valid requests to fail if that write errors; make this update
best-effort by not letting write errors block auth: either fire-and-forget the
update (do not await the promise) or await it inside a try/catch and swallow/log
errors (use processLogger.warn or similar) so authentication returns success
regardless of the update outcome. Locate the update call in src/lib/api-keys.ts
(references: storedApiKey, lastUsedAt, apiKeys, database.update) and change it
to a non-fatal, best-effort write with errors handled but not propagated.
| const pendingMessage = await database.transaction(async (tx) => { | ||
| const threadId = await ensureThread(tx, { | ||
| inboxId: input.inboxId, | ||
| participantHash, | ||
| replyContext, | ||
| sentAt, | ||
| subject: input.subject, | ||
| }) | ||
|
|
||
| await tx.insert(emailMessages).values({ | ||
| id: messageId, | ||
| inboxId: input.inboxId, | ||
| threadId, | ||
| direction: 'outbound', | ||
| providerMessageId: null, | ||
| internetMessageId, | ||
| fromEmail, | ||
| toEmailsJson: JSON.stringify(input.to), | ||
| ccEmailsJson: JSON.stringify(input.cc), | ||
| bccEmailsJson: JSON.stringify(input.bcc), | ||
| subject: input.subject, | ||
| snippet: createSnippet(input.text, input.html), | ||
| textBody: bodyStorage.textBody, | ||
| htmlBody: bodyStorage.htmlBody, | ||
| bodyStorageMode: bodyStorage.mode, | ||
| rawMimeR2Key: null, | ||
| oversizedBodyR2Key: bodyStorage.oversizedBodyR2Key, | ||
| bodySizeBytes: bodyStorage.bodySizeBytes, | ||
| status: 'pending', | ||
| errorCode: null, | ||
| errorMessage: null, | ||
| sentAt: null, | ||
| receivedAt: null, | ||
| }) | ||
|
|
||
| return { | ||
| id: messageId, | ||
| inboxId: input.inboxId, | ||
| threadId, | ||
| internetMessageId, | ||
| } | ||
| }) | ||
|
|
||
| let statusUpdate: SendMessageStatusUpdate | ||
|
|
||
| try { | ||
| const result = await env.EMAIL.send({ | ||
| from: fromEmail, | ||
| to: input.to, | ||
| cc: input.cc.length > 0 ? input.cc : undefined, | ||
| bcc: input.bcc.length > 0 ? input.bcc : undefined, | ||
| subject: input.subject, | ||
| text: input.text, | ||
| html: input.html, | ||
| headers: buildOutboundHeaders(pendingMessage.internetMessageId, replyContext), | ||
| }) | ||
|
|
||
| statusUpdate = { | ||
| providerMessageId: result.messageId, | ||
| status: 'accepted', | ||
| errorCode: null, | ||
| errorMessage: null, | ||
| sentAt, | ||
| } | ||
| } catch (error) { | ||
| const mappedError = mapSendProviderError(error) | ||
|
|
||
| statusUpdate = { | ||
| providerMessageId: null, | ||
| status: 'failed', | ||
| errorCode: mappedError.code, | ||
| errorMessage: mappedError.message, | ||
| sentAt: null, | ||
| } | ||
| } | ||
|
|
||
| await updateOutboundMessageStatus(database, pendingMessage.id, statusUpdate) | ||
|
|
||
| await emitSendEvent(env, pendingMessage, statusUpdate) |
There was a problem hiding this comment.
Make provider acceptance retry-safe.
If env.EMAIL.send() succeeds and updateOutboundMessageStatus() throws, this call fails after a non-idempotent send has already been accepted. A client retry will create a fresh pending row and send the same email again. This flow needs a stable idempotency key or recovery path that resumes the existing send instead of calling EMAIL.send() twice.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/lib/email/outbound.ts` around lines 153 - 231, The current flow calls
env.EMAIL.send() after inserting a pending row, but if
updateOutboundMessageStatus() fails the send can be accepted twice on retry; fix
by using the persisted message row as the idempotency source: before calling
env.EMAIL.send() read the pending message (by
messageId/internetMessageId/threadId) and only call env.EMAIL.send() if its
status is still 'pending' (or providerMessageId is null), otherwise treat it as
already accepted and reuse the stored providerMessageId/sentAt; ensure
updateOutboundMessageStatus(messageId, ...) and emitSendEvent(...) operate on
that same persisted row; use pendingMessage.id or internetMessageId as the
stable idempotency key and add the status check/early-return around
env.EMAIL.send()/statusUpdate to avoid duplicate sends.
| async function ensureThread( | ||
| database: ThreadDatabase, | ||
| params: { | ||
| inboxId: string | ||
| participantHash: string | ||
| replyContext: ReplyContext | null | ||
| sentAt: Date | ||
| subject: string | ||
| }, | ||
| ) { | ||
| const threadId = params.replyContext?.threadId | ||
| ?? (await findExistingThreadId(database, { | ||
| inboxId: params.inboxId, | ||
| participantHash: params.participantHash, | ||
| subjectNormalized: normalizeThreadSubject(params.subject), | ||
| })) | ||
| ?? createThreadId() | ||
|
|
||
| const [existingThread] = await database | ||
| .select({ id: emailThreads.id }) | ||
| .from(emailThreads) | ||
| .where(eq(emailThreads.id, threadId)) | ||
| .limit(1) | ||
|
|
||
| if (existingThread) { | ||
| await database | ||
| .update(emailThreads) | ||
| .set({ lastMessageAt: params.sentAt }) | ||
| .where(eq(emailThreads.id, threadId)) | ||
| } else { | ||
| await database.insert(emailThreads).values({ | ||
| id: threadId, | ||
| inboxId: params.inboxId, | ||
| subjectNormalized: normalizeThreadSubject(params.subject), | ||
| participantHash: params.participantHash, | ||
| lastMessageAt: params.sentAt, | ||
| }) | ||
| } | ||
|
|
||
| return threadId | ||
| } |
There was a problem hiding this comment.
Thread creation can split one conversation into multiple rows.
findExistingThreadId() and the insert happen as separate steps with no DB uniqueness backing them. Two concurrent sends with the same inbox/participants/subject can both see “no thread” and insert different threadIds. If subject+participant hashing is the dedupe key, enforce it with a unique constraint/upsert instead of read-then-insert logic.
Based on learnings, keep DB schema updates in src/db/schema.ts and run drizzle commands.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/lib/email/outbound.ts` around lines 334 - 374, The ensureThread function
races between findExistingThreadId and insert: replace the read-then-insert with
an atomic upsert using emailThreads' dedupe key (subjectNormalized + inboxId +
participantHash) so concurrent sends cannot create multiple threadId rows; add a
unique constraint for that key in the DB schema (update src/db/schema.ts) and
change ensureThread to attempt an insert of a generated createThreadId() with
subjectNormalized, inboxId, participantHash and lastMessageAt, using your DB
client's upsert/ON CONFLICT...DO UPDATE (or equivalent) to return the canonical
threadId and update lastMessageAt, falling back to findExistingThreadId only if
necessary.
| textBody: params.textBody ?? 'Hello world', | ||
| htmlBody: params.htmlBody ?? null, |
There was a problem hiding this comment.
Keep explicit null bodies null in the fixture.
Using ?? here turns the R2 fallback seed data back into an inline text body when the caller passes textBody: null. That makes the oversized-body fixture less realistic and weakens the assertion around storage-mode behavior.
Suggested fix
- textBody: params.textBody ?? 'Hello world',
- htmlBody: params.htmlBody ?? null,
+ textBody: params.textBody === undefined ? 'Hello world' : params.textBody,
+ htmlBody: params.htmlBody === undefined ? null : params.htmlBody,📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| textBody: params.textBody ?? 'Hello world', | |
| htmlBody: params.htmlBody ?? null, | |
| textBody: params.textBody === undefined ? 'Hello world' : params.textBody, | |
| htmlBody: params.htmlBody === undefined ? null : params.htmlBody, |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/lib/email/read.test.ts` around lines 359 - 360, The fixture currently
uses the nullish coalescing operator on params.textBody and params.htmlBody
which treats explicit null as "use default"; change the defaults to only apply
when the param is undefined so explicit null stays null: replace uses of
params.textBody ?? 'Hello world' and params.htmlBody ?? null with undefined
checks (e.g., params.textBody !== undefined ? params.textBody : 'Hello world'
and params.htmlBody !== undefined ? params.htmlBody : null) in the fixture
construction (refer to the textBody/htmlBody fields where params is used in the
test).
| threadIds.length > 0 | ||
| ? database | ||
| .select({ | ||
| id: emailMessages.id, | ||
| threadId: emailMessages.threadId, | ||
| direction: emailMessages.direction, | ||
| fromEmail: emailMessages.fromEmail, | ||
| subject: emailMessages.subject, | ||
| snippet: emailMessages.snippet, | ||
| status: emailMessages.status, | ||
| sentAt: emailMessages.sentAt, | ||
| receivedAt: emailMessages.receivedAt, | ||
| createdAt: emailMessages.createdAt, | ||
| }) | ||
| .from(emailMessages) | ||
| .where(inArray(emailMessages.threadId, threadIds)) | ||
| .orderBy(desc(emailMessages.createdAt), desc(emailMessages.id)) | ||
| : Promise.resolve([]), | ||
| ]) | ||
|
|
||
| const countByThreadId = new Map(messageCounts.map((row) => [row.threadId, Number(row.count)])) | ||
| const latestMessageByThreadId = new Map<string, (typeof latestMessages)[number]>() | ||
|
|
||
| for (const message of latestMessages) { | ||
| if (!latestMessageByThreadId.has(message.threadId)) { | ||
| latestMessageByThreadId.set(message.threadId, message) | ||
| } | ||
| } | ||
|
|
||
| return { | ||
| nextCursor: rows.length > input.limit | ||
| ? encodeCursor({ | ||
| id: pageRows.at(-1)?.id ?? '', | ||
| lastMessageAt: pageRows.at(-1)?.lastMessageAt.toISOString() ?? '', | ||
| }) | ||
| : null, | ||
| threads: pageRows.map((thread) => { | ||
| const latestMessage = latestMessageByThreadId.get(thread.id) | ||
|
|
||
| return { | ||
| id: thread.id, | ||
| inboxId: thread.inboxId, | ||
| subject: latestMessage?.subject ?? thread.subjectNormalized, | ||
| subjectNormalized: thread.subjectNormalized, | ||
| messageCount: countByThreadId.get(thread.id) ?? 0, | ||
| lastMessageAt: thread.lastMessageAt.toISOString(), | ||
| createdAt: thread.createdAt.toISOString(), | ||
| updatedAt: thread.updatedAt.toISOString(), | ||
| latestMessage: latestMessage | ||
| ? { | ||
| id: latestMessage.id, | ||
| direction: latestMessage.direction as 'inbound' | 'outbound', | ||
| fromEmail: latestMessage.fromEmail, | ||
| subject: latestMessage.subject, | ||
| snippet: latestMessage.snippet, | ||
| status: latestMessage.status as z.infer<typeof messageStatusSchema>, | ||
| sentAt: latestMessage.sentAt?.toISOString() ?? null, | ||
| receivedAt: latestMessage.receivedAt?.toISOString() ?? null, | ||
| createdAt: latestMessage.createdAt.toISOString(), | ||
| } | ||
| : null, | ||
| } | ||
| }), |
There was a problem hiding this comment.
Use message chronology for previews and pagination.
Both read paths sort on createdAt, but the thread model itself uses receivedAt/sentAt via lastMessageAt. Backfilled or delayed mail will show the wrong latestMessage preview and can appear out of order inside a thread. Pick and page messages with the same chronology key the thread uses.
Also applies to: 231-258
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/lib/email/read.ts` around lines 155 - 217, The thread previews and
pagination currently pick and sort messages by createdAt (see latestMessages
query, the orderBy(desc(emailMessages.createdAt), desc(emailMessages.id)) and
nextCursor construction using pageRows.at(-1)?.lastMessageAt); change both the
selection and ordering to use the same chronology key the thread uses
(lastMessageAt which is derived from receivedAt/sentAt) so you pick the true
latest message and page consistently: update the latestMessages query orderBy to
desc(emailMessages.lastMessageAt), desc(emailMessages.id) (and any other
selection that currently uses createdAt for chronology), ensure
latestMessageByThreadId population remains but keyed by threadId, and build
nextCursor using pageRows.at(-1)?.lastMessageAt (ISO string) so previews,
sorting and cursor paging all use lastMessageAt instead of createdAt (also apply
the same change in the other read path noted around lines 231-258).
| const env = getWorkerEnv() as Pick<Env, 'EMAIL_STORAGE'> | ||
| const bodyObject = await env.EMAIL_STORAGE.get(message.oversizedBodyR2Key) | ||
|
|
||
| if (!bodyObject) { | ||
| return { | ||
| textBody: null, | ||
| htmlBody: null, | ||
| source: 'missing' as const, | ||
| } | ||
| } | ||
|
|
||
| try { | ||
| const parsedBody = oversizedBodySchema.parse(JSON.parse(await bodyObject.text())) | ||
|
|
||
| return { | ||
| textBody: parsedBody.textBody, | ||
| htmlBody: parsedBody.htmlBody, | ||
| source: 'r2' as const, | ||
| } | ||
| } catch { | ||
| return { | ||
| textBody: null, | ||
| htmlBody: null, | ||
| source: 'missing' as const, | ||
| } | ||
| } |
There was a problem hiding this comment.
Handle storage read failures as a missing body.
EMAIL_STORAGE.get() is outside the try, so a transient R2 error turns messages.get into a 500 even though this API already models bodySource: 'missing'. Wrap the fetch itself and fall back to the missing-body shape.
Suggested change
- const env = getWorkerEnv() as Pick<Env, 'EMAIL_STORAGE'>
- const bodyObject = await env.EMAIL_STORAGE.get(message.oversizedBodyR2Key)
-
- if (!bodyObject) {
- return {
- textBody: null,
- htmlBody: null,
- source: 'missing' as const,
- }
- }
-
- try {
+ const env = getWorkerEnv() as Pick<Env, 'EMAIL_STORAGE'>
+
+ try {
+ const bodyObject = await env.EMAIL_STORAGE.get(message.oversizedBodyR2Key)
+
+ if (!bodyObject) {
+ return {
+ textBody: null,
+ htmlBody: null,
+ source: 'missing' as const,
+ }
+ }
+
const parsedBody = oversizedBodySchema.parse(JSON.parse(await bodyObject.text()))
return {
textBody: parsedBody.textBody,
htmlBody: parsedBody.htmlBody,🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/lib/email/read.ts` around lines 365 - 390, The current code calls
env.EMAIL_STORAGE.get(message.oversizedBodyR2Key) outside the try block so
transient R2 errors cause a 500; wrap the storage fetch in the same try that
parses the body so any error from EMAIL_STORAGE.get or from
oversizedBodySchema.parse is caught and returns the missing-body shape
(textBody: null, htmlBody: null, source: 'missing'). Locate the getWorkerEnv()
call and the EMAIL_STORAGE.get(...) invocation and move the fetch into the
try/catch (or add a surrounding try) that currently runs
oversizedBodySchema.parse to ensure both fetch and parse failures fall back to
the missing source.
| private nextError: unknown | null = null | ||
|
|
||
| failWith(error: unknown) { | ||
| this.nextError = error | ||
| } | ||
|
|
||
| async send(message: unknown) { | ||
| this.sent.push(message) | ||
|
|
||
| if (this.nextError) { | ||
| const error = this.nextError | ||
| this.nextError = null | ||
|
|
||
| throw error | ||
| } |
There was a problem hiding this comment.
Check nextError against null, not truthiness.
failWith() accepts unknown, but send() skips throwing for scheduled values like '', 0, or false. If this test double is meant to mirror “throw whatever was scheduled,” the guard should be explicit.
🛠️ Proposed fix
- if (this.nextError) {
+ if (this.nextError !== null) {
const error = this.nextError
this.nextError = null
throw error
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| private nextError: unknown | null = null | |
| failWith(error: unknown) { | |
| this.nextError = error | |
| } | |
| async send(message: unknown) { | |
| this.sent.push(message) | |
| if (this.nextError) { | |
| const error = this.nextError | |
| this.nextError = null | |
| throw error | |
| } | |
| private nextError: unknown | null = null | |
| failWith(error: unknown) { | |
| this.nextError = error | |
| } | |
| async send(message: unknown) { | |
| this.sent.push(message) | |
| if (this.nextError !== null) { | |
| const error = this.nextError | |
| this.nextError = null | |
| throw error | |
| } |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/lib/email/test-harness.ts` around lines 38 - 52, The send() method
currently guards on this.nextError's truthiness and will skip throwing scheduled
falsy values (e.g., '', 0, false); update the guard to explicitly check for null
(e.g., this.nextError !== null) so that any value set by failWith(error) (which
accepts unknown) is thrown; adjust the send() method’s conditional and keep
clearing this.nextError after capturing it, referencing the nextError property,
failWith(), and send() methods.
* Implement thread and message read APIs (#5) * Tighten thread read test typing
Summary
threads.listByInbox,threads.listMessages, andmessages.getwith D1 reads and R2 oversized-body fallbackx-api-keyauth for protected oRPC endpointsValidation
pnpm testpnpm exec tsc --noEmitpnpm buildSummary by CodeRabbit
New Features
Infrastructure