Skip to content

fix: implement WriteHeaderNowWithoutLock and synchronize Written access in responseWriterShim - #322

Open
saurabhhhcodes wants to merge 2 commits into
AnkanMisra:mainfrom
saurabhhhcodes:fix/micropay-batch-1
Open

fix: implement WriteHeaderNowWithoutLock and synchronize Written access in responseWriterShim#322
saurabhhhcodes wants to merge 2 commits into
AnkanMisra:mainfrom
saurabhhhcodes:fix/micropay-batch-1

Conversation

@saurabhhhcodes

@saurabhhhcodes saurabhhhcodes commented Jul 23, 2026

Copy link
Copy Markdown
Contributor

Fixes

1. gateway/middleware.go - WriteHeaderNowWithoutLock is a no-op
The responseWriterShims WriteHeaderNowWithoutLock was empty, breaking the gin.ResponseWriter contract. When Gin internally calls this method, headers were not properly recorded. Fixed by delegating to bufferedWriter.WriteHeaderNow.

2. gateway/middleware.go - Written accesses bw.wrote without synchronization
The Written method read bw.wrote without holding bw.mu, creating a data race between the handler goroutine and any reader. Fixed by acquiring a read lock before accessing the field.

Summary by CodeRabbit

  • Bug Fixes

    • Improved reliability when processing payment-protected requests by ensuring response status and headers are captured consistently.
    • Added safer handling for missing or invalid payment receipts, preventing malformed receipt data from causing failures.
  • Tests

    • Added coverage for gateway configuration, authenticated summarization requests, payment challenges, signed headers, successful responses, and receipt decoding.

Note

Fix thread-safe access and implement WriteHeaderNowWithoutLock in responseWriterShim

  • Written() in middleware.go now acquires a read lock before reading the wrote flag, fixing a potential data race.
  • WriteHeaderNowWithoutLock() was previously a no-op; it now calls WriteHeaderNow() on the underlying writer.
  • Adds a test suite for the x402 client in x402-client.test.ts covering gateway URL selection, 402 challenge parsing, signed retry headers, and receipt header decoding.

Macroscope summarized b3fcf61.

@vercel

vercel Bot commented Jul 23, 2026

Copy link
Copy Markdown

Someone is attempting to deploy a commit to the ankanmisra's projects Team on Vercel.

A member of the Team first needs to authorize it.

@github-actions github-actions Bot added go Pull requests that update go code TypeScript TypeScript code type:testing Tests, coverage, fixtures, or validation-only work. labels Jul 23, 2026
@coderabbitai

coderabbitai Bot commented Jul 23, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The response writer shim now synchronizes written-state access and forwards header writes. A new Bun test suite covers x402 client URL selection, requests, payment challenges, signed headers, and receipt decoding.

Changes

Response writer synchronization

Layer / File(s) Summary
Buffered response writer behavior
gateway/middleware.go
Written() reads the buffered writer’s state under a read lock, and WriteHeaderNowWithoutLock() delegates header writing to the buffered writer.

x402 client helper tests

Layer / File(s) Summary
Test fixtures and isolation
web/src/lib/x402-client.test.ts
Defines payment and receipt fixtures, receipt encoding, and restoration of fetch and gateway environment state.
Request and payment helper coverage
web/src/lib/x402-client.test.ts
Tests gateway URL selection, summarize POST construction, missing payment-context errors, and signed retry headers.
Receipt handling coverage
web/src/lib/x402-client.test.ts
Tests receipt decoding, absent receipt headers, and malformed receipt handling.

Estimated code review effort: 2 (Simple) | ~10 minutes

Possibly related issues

Possibly related PRs

Suggested labels: enhancement

Suggested reviewers: ankanmisra

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description covers the fixes, but it omits most required template sections like Summary, Type Of Change, Affected Areas, and Verification. Fill in the repository template sections, especially Summary, Type Of Change, Affected Areas, Verification, and Notes For Reviewers.
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 (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the gateway middleware synchronization fix and WriteHeaderNowWithoutLock implementation.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
⚔️ Resolve merge conflicts
  • Resolve merge conflict in branch fix/micropay-batch-1

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 golangci-lint (2.12.2)

level=error msg="[linters_context] typechecking error: pattern ./...: directory prefix . does not contain main module or its selected dependencies"


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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 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 `@gateway/middleware.go`:
- Around line 245-247: Add gateway regression tests covering
responseWriterShim.Written() before and after WriteHeaderNowWithoutLock(),
verifying the written status and propagated response status. Include a test
exercising the relevant concurrent access path, using the existing gateway test
patterns and synchronization utilities.
🪄 Autofix (Beta)

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: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 890d3c24-fbf3-498b-a8bd-feae3bf5d7f9

📥 Commits

Reviewing files that changed from the base of the PR and between 76ed9ff and b3fcf61.

📒 Files selected for processing (2)
  • gateway/middleware.go
  • web/src/lib/x402-client.test.ts

Comment thread gateway/middleware.go
Comment on lines +245 to +247
func (rws *responseWriterShim) Written() bool { rws.bw.mu.RLock(); defer rws.bw.mu.RUnlock(); return rws.bw.wrote }
func (rws *responseWriterShim) Size() int { return rws.bw.buf.Len() }
func (rws *responseWriterShim) WriteHeaderNowWithoutLock() {}
func (rws *responseWriterShim) WriteHeaderNowWithoutLock() { rws.bw.WriteHeaderNow() }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Add gateway regression tests for the changed writer behavior.

Cover Written() before and after WriteHeaderNowWithoutLock(), status propagation, and the relevant concurrent access path.

As per coding guidelines, **/*.{go,rs,js,jsx,ts,tsx}: Add or update tests for behavioral changes.

🤖 Prompt for 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.

In `@gateway/middleware.go` around lines 245 - 247, Add gateway regression tests
covering responseWriterShim.Written() before and after
WriteHeaderNowWithoutLock(), verifying the written status and propagated
response status. Include a test exercising the relevant concurrent access path,
using the existing gateway test patterns and synchronization utilities.

Source: Coding guidelines

@AnkanMisra AnkanMisra left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Conflicts and link the issue

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

go Pull requests that update go code type:testing Tests, coverage, fixtures, or validation-only work. TypeScript TypeScript code

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants