Skip to content

Implement thread and message read APIs - #6

Merged
KMKoushik merged 2 commits into
mainfrom
thread-message-read-apis
Mar 8, 2026
Merged

KMKoushik merged 2 commits into
mainfrom
thread-message-read-apis

Conversation

@KMKoushik

@KMKoushik KMKoushik commented Mar 8, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • add the Phase 5 read layer with threads.listByInbox, threads.listMessages, and messages.get
  • enforce inbox ownership on reads and load oversized message bodies from R2 when needed
  • add API coverage for pagination, ordering, ownership boundaries, inline D1 reads, and R2 fallback, and update mvp.md to reflect the completed read APIs

Validation

  • pnpm test
  • pnpm exec tsc --noEmit
  • pnpm build

Summary by CodeRabbit

  • New Features

    • List email threads by inbox with cursor-based pagination
    • List messages within threads with pagination
    • Retrieve individual messages with full details and body content, supporting inline and oversized/cloud bodies
  • Tests

    • Added comprehensive integration tests for thread/message reads, pagination, ownership enforcement, and body storage fallback
  • Documentation

    • MVP plan updated to reflect completed tasks, removals, and adjusted acceptance criteria
  • Chores

    • Test harness storage interface updated

@coderabbitai

coderabbitai Bot commented Mar 8, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

This 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

Cohort / File(s) Summary
Read API Layer
src/lib/email/read.ts
New module: Zod schemas, cursor pagination, serializers, helpers, and core functions listThreadsByInboxForUser, listThreadMessagesForUser, and getMessageForUser with inline/R2 body resolution and error handling.
API Routes
src/orpc/procedures/threads.ts, src/orpc/procedures/messages.ts
Populated threadRouter with listByInbox and listMessages; added GET /messages/{messageId} to messageRouter. Handlers validate auth, call read layer, and map missing results to NOT_FOUND.
Tests
src/orpc/procedures/thread-read.test.ts
New integration tests covering thread listing and pagination, message listing and pagination, ownership enforcement (404s), inline body reads, and R2 fallback for oversized bodies.
Test Harness
src/lib/email/test-harness.ts
Test environment type updated: EMAIL_STORAGE now uses concrete TestR2Bucket instead of Pick<R2Bucket, 'put'>.
Docs / Plan
mvp.md
MVP plan updated: several items toggled to completed or struck-through, reflecting implemented thread/message read work and test status.

Sequence Diagram

sequenceDiagram
    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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Possibly related PRs

Poem

🐰
I hopped through threads and chased each mail,
Paged through cursors down the trail,
From D1 nooks to R2 skies,
I fetched the body, what a prize!
Now read APIs bloom in the dale.

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Implement thread and message read APIs' directly and clearly describes the main change: adding read API implementations for threads and messages, matching the core work evident across multiple files.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch thread-message-read-apis

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (3)
src/orpc/procedures/thread-read.test.ts (1)

334-334: Consider typing the JSON response for better type safety.

The as any cast 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 by createdAt in addition to id for robustness.

Currently, pagination orders messages by id alone using asc(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 createdAt in the comparison, similar to how listThreadsByInboxForUser handles the composite cursor with lastMessageAt and id.

🤖 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

📥 Commits

Reviewing files that changed from the base of the PR and between 250a149 and 7097b4d.

📒 Files selected for processing (6)
  • mvp.md
  • src/lib/email/read.ts
  • src/lib/email/test-harness.ts
  • src/orpc/procedures/messages.ts
  • src/orpc/procedures/thread-read.test.ts
  • src/orpc/procedures/threads.ts

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
src/orpc/procedures/thread-read.test.ts (1)

43-43: Consider using import type for type-only imports.

EmailTestHarness is only used as a type annotation. Per coding guidelines, use import type for 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

📥 Commits

Reviewing files that changed from the base of the PR and between 7097b4d and 7bcf6ea.

📒 Files selected for processing (1)
  • src/orpc/procedures/thread-read.test.ts

@KMKoushik
KMKoushik merged commit afe114a into main Mar 8, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant