Repository navigation
Implement thread and message read APIs - #6
Conversation
📝 WalkthroughWalkthroughThis PR adds a read layer for email threads and messages with cursor-based pagination, message detail retrieval (including inline and oversized R2 body resolution), exposes GET routes for threads/messages, updates the test harness R2 type, and adds comprehensive integration tests and MVP doc updates. Changes
Sequence DiagramsequenceDiagram
participant Client
participant API as API Handler
participant Auth as Auth Check
participant DB as Database (D1)
participant R2 as R2 Storage
Client->>API: GET /messages/{messageId}
API->>Auth: validate session
Auth-->>API: userId
API->>DB: query message by id + inbox ownership
DB-->>API: message record (includes bodyStorageMode)
alt bodyStorageMode == "inline"
API->>DB: read textBody/htmlBody
DB-->>API: body content
else bodyStorageMode == "oversized"
API->>DB: get oversizedBodyR2Key
DB-->>API: R2 key
API->>R2: fetch object by key
R2-->>API: body bytes
end
API->>API: serialize messageDetail
API-->>Client: 200 OK with messageDetail
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.
🧹 Nitpick comments (3)
src/orpc/procedures/thread-read.test.ts (1)
334-334: Consider typing the JSON response for better type safety.The
as anycast works but could be improved by defining a generic or specific response type. Since this is narrowly scoped to test assertions, this is acceptable but could be refined.♻️ Optional improvement
-async function requestJson(path: string) { +async function requestJson<T = unknown>(path: string) { const request = new Request(`http://localhost${path}`) const result = await apiHandler.handle(request, { context: { request, }, prefix: '/api', }) if (!result.matched) { throw new Error(`Request did not match any route: ${path}`) } return { response: result.response, - json: await result.response.json() as any, + json: await result.response.json() as T, } }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/orpc/procedures/thread-read.test.ts` at line 334, The test currently casts the HTTP JSON body with a broad "as any" (the line using "json: await result.response.json() as any") which loses type safety; replace that cast with a concrete test-specific type or generic (e.g., define an interface like ExpectedThreadReadResponse or use unknown + validation) and cast/parse via "await result.response.json()" to that type so assertions are typed against the response shape; update the place where "json" is referenced in the test to use the new type (referencing the result.response.json() call and the local "json" variable) to ensure compile-time checks.src/lib/email/read.ts (2)
336-344: Errors thrown here will surface as 500 Internal Server Error.The errors thrown when the oversized body key is missing or the R2 object is not found are appropriate data integrity checks. These will bubble up as unhandled errors (500s) to the API layer rather than 404s.
If this is intentional (treating missing R2 data as a server-side data corruption issue), this is fine. If you'd prefer these to be user-facing errors, consider returning a specific error type that the handler can catch.
🤖 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 336 - 344, The two checks in src/lib/email/read.ts that currently throw generic Errors when message.oversizedBodyR2Key is missing or env.EMAIL_STORAGE.get(...) returns null should be changed to return or throw a specific, catchable user-facing error type (for example EmailNotFoundError or NotFoundError) instead of a bare Error so the API handler can map it to a 404; update the code paths around message.oversizedBodyR2Key and the result of env.EMAIL_STORAGE.get(...) (using getWorkerEnv and EMAIL_STORAGE) to create and throw/return the new typed error, and ensure the higher-level request handler recognizes that error class and converts it to a 404 response.
252-256: Consider ordering messages bycreatedAtin addition toidfor robustness.Currently, pagination orders messages by
idalone usingasc(emailMessages.id). While ULIDs are time-sortable, relying solely on ID ordering could produce unexpected results if messages are created in quick succession or if IDs are generated out of order for any reason.♻️ Suggested improvement
const rows = await database .select() .from(emailMessages) .where(whereClause) - .orderBy(asc(emailMessages.id)) + .orderBy(asc(emailMessages.createdAt), asc(emailMessages.id)) .limit(input.limit + 1)This would also require updating the cursor logic in lines 241-250 to include
createdAtin the comparison, similar to howlistThreadsByInboxForUserhandles the composite cursor withlastMessageAtandid.🤖 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 252 - 256, The query currently orders email messages only by asc(emailMessages.id); update the query to order by createdAt then id (e.g., asc(emailMessages.createdAt), asc(emailMessages.id)) and update the cursor/comparison logic that builds whereClause and the cursor handling in the same function (the block that inspects the incoming cursor and sets conditions) to use a composite cursor (createdAt plus id)—follow the same pattern used in listThreadsByInboxForUser for lastMessageAt and id so comparisons use (createdAt < cursor.createdAt) OR (createdAt = cursor.createdAt AND id < cursor.id) for pagination.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@src/lib/email/read.ts`:
- Around line 336-344: The two checks in src/lib/email/read.ts that currently
throw generic Errors when message.oversizedBodyR2Key is missing or
env.EMAIL_STORAGE.get(...) returns null should be changed to return or throw a
specific, catchable user-facing error type (for example EmailNotFoundError or
NotFoundError) instead of a bare Error so the API handler can map it to a 404;
update the code paths around message.oversizedBodyR2Key and the result of
env.EMAIL_STORAGE.get(...) (using getWorkerEnv and EMAIL_STORAGE) to create and
throw/return the new typed error, and ensure the higher-level request handler
recognizes that error class and converts it to a 404 response.
- Around line 252-256: The query currently orders email messages only by
asc(emailMessages.id); update the query to order by createdAt then id (e.g.,
asc(emailMessages.createdAt), asc(emailMessages.id)) and update the
cursor/comparison logic that builds whereClause and the cursor handling in the
same function (the block that inspects the incoming cursor and sets conditions)
to use a composite cursor (createdAt plus id)—follow the same pattern used in
listThreadsByInboxForUser for lastMessageAt and id so comparisons use (createdAt
< cursor.createdAt) OR (createdAt = cursor.createdAt AND id < cursor.id) for
pagination.
In `@src/orpc/procedures/thread-read.test.ts`:
- Line 334: The test currently casts the HTTP JSON body with a broad "as any"
(the line using "json: await result.response.json() as any") which loses type
safety; replace that cast with a concrete test-specific type or generic (e.g.,
define an interface like ExpectedThreadReadResponse or use unknown + validation)
and cast/parse via "await result.response.json()" to that type so assertions are
typed against the response shape; update the place where "json" is referenced in
the test to use the new type (referencing the result.response.json() call and
the local "json" variable) to ensure compile-time checks.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: d8bc43b1-f880-49f1-a494-795c822bd111
📒 Files selected for processing (6)
mvp.mdsrc/lib/email/read.tssrc/lib/email/test-harness.tssrc/orpc/procedures/messages.tssrc/orpc/procedures/thread-read.test.tssrc/orpc/procedures/threads.ts
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/orpc/procedures/thread-read.test.ts (1)
43-43: Consider usingimport typefor type-only imports.
EmailTestHarnessis only used as a type annotation. Per coding guidelines, useimport typefor type-only imports.Suggested change
-import { createMessageId, createThreadId } from '#/lib/email/ids' -import { createEmailTestHarness, createInboxRecord, createUserRecord, type EmailTestHarness } from '#/lib/email/test-harness' +import { createMessageId, createThreadId } from '#/lib/email/ids' +import type { EmailTestHarness } from '#/lib/email/test-harness' +import { createEmailTestHarness, createInboxRecord, createUserRecord } from '#/lib/email/test-harness'🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/orpc/procedures/thread-read.test.ts` at line 43, The import statement currently brings in EmailTestHarness as a value but it is only used as a type; change the import to use a type-only import for EmailTestHarness (e.g., use "import type { EmailTestHarness } from '#/lib/email/test-harness'") while keeping createEmailTestHarness, createInboxRecord, and createUserRecord as value imports so the tests still run; update the single import line to separate the type import from the runtime imports accordingly.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@src/orpc/procedures/thread-read.test.ts`:
- Line 43: The import statement currently brings in EmailTestHarness as a value
but it is only used as a type; change the import to use a type-only import for
EmailTestHarness (e.g., use "import type { EmailTestHarness } from
'#/lib/email/test-harness'") while keeping createEmailTestHarness,
createInboxRecord, and createUserRecord as value imports so the tests still run;
update the single import line to separate the type import from the runtime
imports accordingly.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: fe9d00ff-488b-4915-8704-8a36338ed86c
📒 Files selected for processing (1)
src/orpc/procedures/thread-read.test.ts
Summary
threads.listByInbox,threads.listMessages, andmessages.getmvp.mdto reflect the completed read APIsValidation
Summary by CodeRabbit
New Features
Tests
Documentation
Chores