Skip to content

fix: isolate tRPC procedures in scoped DI context - #1762

Merged
kang-heewon merged 3 commits into
trunkfrom
fix/1677-trpc-request-context
Aug 7, 2026
Merged

fix: isolate tRPC procedures in scoped DI context#1762
kang-heewon merged 3 commits into
trunkfrom
fix/1677-trpc-request-context

Conversation

@kang-heewon

@kang-heewon kang-heewon commented Aug 5, 2026

Copy link
Copy Markdown
Member

Outcome

  • Each tRPC procedure now establishes an isolated Croco request context before guards, filters, interceptors, controller resolution, and handler execution.
  • Registered controllers and lifecycle providers resolve through Croco DI inside that boundary, enabling constructor injection and request-scoped providers.
  • Request and trace metadata propagate from direct tRPC context fields, runtime metadata, or HTTP headers, with an optional explicit context mapper.

Verification

  • pnpm --filter @croco/protocols-trpc test — 26/26 passed
  • pnpm typecheck — 233/233 tasks passed
  • pnpm public-api:check — 115 snapshots matched
  • pnpm problem-registry:check — 576/576 codes passed
  • Pre-push pnpm test — 234/234 tasks passed
  • Independent adversarial review — approved after HTTP batch and trace validation coverage was added

Review gates

  • Correctness/regression: covers constructor injection, overlapping caller and real HTTP batch isolation, metadata propagation, and cleanup after success and failure.
  • API/security/compatibility: adds only the optional createRequestContext mapper; preserves the existing custom-container and no-argument fallback paths; validates supported traceparent versions.
  • Maintainability/minimality: confines runtime behavior to the tRPC adapter and synchronizes its README, API docs, generated Problem locations, and changeset.

Residual risk

pnpm check passed 23/25 repository checks locally. The verification runner timed out while asserting its own timeout-output capture (the isolated test passed immediately afterward), and the gitleaks smoke environment produced malformed temporary SARIF. Neither failure touched the changed package.

Fixes #1677

Summary by CodeRabbit

  • 새로운 기능

    • tRPC 요청이 격리된 요청 컨텍스트에서 실행됩니다.
    • 요청별 의존성 주입과 수명 주기 관리를 지원합니다.
    • 요청 ID, 테넌트, 사용자 및 추적 메타데이터를 자동으로 전달합니다.
    • 요청 헤더 기반 메타데이터와 사용자 정의 컨텍스트 설정을 지원합니다.
    • 동시 요청 간 컨텍스트가 안전하게 분리됩니다.
  • 문서

    • 요청 컨텍스트 처리 방식과 사용자 정의 설정 예시를 추가했습니다.
    • 문제 복구 문서의 참조 정보를 최신화했습니다.
  • 버그 수정

    • 컨테이너 의존성 오류가 실제 요청 처리 시 일관된 tRPC 오류로 반환됩니다.
    • 선택적 검증 항목이 없는 경우에도 스모크 검증이 올바르게 완료됩니다.

@coderabbitai

coderabbitai Bot commented Aug 5, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@kang-heewon, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 11 minutes

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 99170113-804a-4f17-b9f5-aeadfb2353e8

📥 Commits

Reviewing files that changed from the base of the PR and between 1814f81 and 38beba1.

⛔ Files ignored due to path filters (1)
  • packages/problems-core/src/generated/problem-code-registry.ts is excluded by !**/generated/**
📒 Files selected for processing (4)
  • docs/problem-code-registry.json
  • packages/docs/src/content/docs/en/reference/problem-recovery-cookbook.md
  • packages/protocols-trpc/src/libs/createTrpcRouter.ts
  • packages/protocols-trpc/src/tests/TrpcExecutionPipeline.spec.ts
📝 Walkthrough

Walkthrough

tRPC 프로시저가 요청별 RequestContext에서 실행됩니다. 컨트롤러와 provider는 resolver 실행 시 Croco DI로 생성됩니다. 생성 앱 스모크의 journey bundle 검증은 실행 프로필에 따라 선택적으로 수행됩니다.

Changes

tRPC 요청 컨텍스트 및 의존성 주입

Layer / File(s) Summary
요청 컨텍스트 생성과 메타데이터 변환
packages/protocols-trpc/src/libs/createTrpcRouter.ts
createRequestContext 옵션을 추가했습니다. tRPC 컨텍스트, 요청 헤더, traceparent에서 RequestContext를 구성합니다.
요청 범위 프로시저 실행과 provider 해석
packages/protocols-trpc/src/libs/createTrpcRouter.ts
Context.run 안에서 프로시저를 실행합니다. resolver 시점에 컨트롤러를 생성하고 Croco 컨테이너에서 provider를 조회합니다.
통합 검증과 공개 계약 갱신
packages/protocols-trpc/src/tests/*, packages/protocols-trpc/README.md, packages/docs/src/content/docs/api/protocols-trpc/src/type-aliases/TrpcRouterOptions.md, docs/problem-code-registry.json, packages/docs/src/content/docs/en/reference/problem-recovery-cookbook.md, .changeset/trpc-request-context.md
요청 범위 격리, HTTP 배치, 헤더 전달, 사용자 정의 매핑, 성공·실패 후 정리를 검증했습니다. 문서, 문제 출처, changeset을 갱신했습니다.

생성 앱 스모크 릴리스 증거

Layer / File(s) Summary
선택적 journey bundle 검증
scripts/verification-manifest.mts, scripts/release-spine-evidence.mts, scripts/tests/*
spine-blocking-journeys artifact의 필수 여부를 generatedAppSmokeFullTier에 따라 결정합니다. 선택적 bundle이 없으면 해당 상태를 기록하고 검증을 계속합니다.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Client as tRPC client
  participant Router as createTrpcRouter
  participant Context as Croco Context
  participant Container as Croco Container
  participant Controller as Controller resolver

  Client->>Router: procedure 호출
  Router->>Context: RequestContext 생성 및 Context.run 실행
  Context->>Container: 컨트롤러와 provider 해석
  Container-->>Controller: 요청 범위 인스턴스 반환
  Controller-->>Router: procedure 결과 또는 오류
  Router-->>Client: tRPC 응답
Loading

Possibly related PRs

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Out of Scope Changes check ⚠️ Warning tRPC 변경 외에 release spine 검증 및 verification manifest 동작을 수정한 변경이 [#1677]의 범위를 벗어납니다. release spine 검증 및 verification manifest 변경을 별도 PR로 분리하거나 해당 변경을 정당화하는 연결 이슈를 추가하세요.
Docstring Coverage ⚠️ Warning Docstring coverage is 6.25% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed 제목은 tRPC 프로시저를 범위가 지정된 DI 컨텍스트에서 실행하는 주요 변경을 정확하고 간결하게 설명합니다.
Linked Issues check ✅ Passed tRPC 요청 컨텍스트, scoped DI, 생성자 주입, 동시성 격리, 정리 동작을 구현하고 관련 통합 테스트를 추가하여 [#1677]의 요구사항을 충족합니다.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/1677-trpc-request-context

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@github-actions

github-actions Bot commented Aug 5, 2026

Copy link
Copy Markdown

📊 Benchmark Results

✅ All benchmarks passed

Benchmark p75 Threshold Baseline vs Baseline Status Notes
CrocoApp constructor 45.5μs 30.0ms 8.2μs +456.4% -
CrocoApp lambdaHandler (10 controllers) 2.3ms 50.0ms 258.4μs +807.0% -
Lambda cold-start simulation 1.9ms 80.0ms 418.1μs +350.8% -
Lambda cold-start with headers 1.5ms 80.0ms 369.7μs +313.4% -
Lambda cold-start with binary body 1.5ms 80.0ms 339.1μs +353.0% -
Lambda cold-start with query params 1.5ms 80.0ms 301.3μs +399.4% -
Lambda cold-start with authorizer context 1.5ms 80.0ms 299.8μs +402.7% -
Lambda cold-start realistic scenario 1.5ms 80.0ms 299.2μs +398.7% -
EventBusConfig.start (10 handlers) 1.7μs 10.0ms 1.4μs +16.1% -
EventPublisher.publishNow single event 1.9μs 2.0ms 1.7μs +13.1% -
DefaultHandlerResolver.resolve × 10 0.1μs 5.0ms 0.1μs +0.0% -
Container.get singleton (cold) 87.7μs 5.0ms 70.3μs +24.9% -
Container.register × 50 components 3.3ms 10.0ms 3.2ms +3.2% -
Container.validate (50 components) 3.8ms 20.0ms 3.4ms +11.3% -
Container.get singleton (warm) 1.8μs 500.0μs 1.6μs +7.3% -
TelemetryRuntime.init (lambda preset) 2.2μs 200.0ms 1.1ms -99.8% -
lambdaPreset config creation 1.5μs 2.0ms 1.4μs +3.6% -

Updated: 2026-08-07T15:14:44.275Z · Commit: cb98250

@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.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/protocols-trpc/src/libs/createTrpcRouter.ts`:
- Around line 294-295: Update the header lookup in the visible value-reading
logic so ordinary object headers are resolved case-insensitively, including keys
such as Traceparent and X-Request-Id. Normalize the requested name or search
available keys without case sensitivity, while preserving array handling and
readString conversion.
- Around line 305-309: Update parseTraceparent() after regex matching to return
undefined when traceId is all zeros or spanId is all zeros, while preserving
valid identifier parsing; add tests covering all-zero traceparent identifiers.

In `@packages/protocols-trpc/src/tests/TrpcExecutionPipeline.spec.ts`:
- Around line 383-392: Update the rejection assertion in the test “requires a
container for providers with constructor dependencies” to call rejects.toThrow()
before the existing rejects.toMatchObject(...) check, preserving the current
cause-code validation and matching the async error assertion convention used in
the file.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: a8ae5873-fb10-42f8-a03c-692f16a5f5f7

📥 Commits

Reviewing files that changed from the base of the PR and between 20c8b4a and 0a42c95.

⛔ Files ignored due to path filters (1)
  • packages/problems-core/src/generated/problem-code-registry.ts is excluded by !**/generated/**
📒 Files selected for processing (8)
  • .changeset/trpc-request-context.md
  • docs/problem-code-registry.json
  • packages/docs/src/content/docs/api/protocols-trpc/src/type-aliases/TrpcRouterOptions.md
  • packages/docs/src/content/docs/en/reference/problem-recovery-cookbook.md
  • packages/protocols-trpc/README.md
  • packages/protocols-trpc/src/libs/createTrpcRouter.ts
  • packages/protocols-trpc/src/tests/TrpcExecutionPipeline.spec.ts
  • packages/protocols-trpc/src/tests/createTrpcRouter.spec.ts

Comment thread packages/protocols-trpc/src/libs/createTrpcRouter.ts Outdated
Comment thread packages/protocols-trpc/src/libs/createTrpcRouter.ts Outdated
Comment thread packages/protocols-trpc/src/tests/TrpcExecutionPipeline.spec.ts
@kang-heewon

Copy link
Copy Markdown
Member Author

@coderabbitai resolve

@coderabbitai

coderabbitai Bot commented Aug 5, 2026

Copy link
Copy Markdown
✅ Action performed

Comments resolved and changes approved.

@kang-heewon
kang-heewon force-pushed the fix/1677-trpc-request-context branch from 1814f81 to 38beba1 Compare August 7, 2026 15:04
@kang-heewon
kang-heewon merged commit 51d2d51 into trunk Aug 7, 2026
12 checks passed
@kang-heewon
kang-heewon deleted the fix/1677-trpc-request-context branch August 7, 2026 16:57
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.

[protocols-trpc] Resolve controllers through Croco DI and request context

1 participant