Skip to content

feat(gateway): make request body size limit configurable via MAX_REQUEST_BODY_BYTES#253

Open
tlnarayana005 wants to merge 1 commit into
AnkanMisra:mainfrom
tlnarayana005:fix-issue-252
Open

feat(gateway): make request body size limit configurable via MAX_REQUEST_BODY_BYTES#253
tlnarayana005 wants to merge 1 commit into
AnkanMisra:mainfrom
tlnarayana005:fix-issue-252

Conversation

@tlnarayana005

@tlnarayana005 tlnarayana005 commented Jul 6, 2026

Copy link
Copy Markdown

Summary

  • Replaced the hardcoded 10MB payload size limit in handleSummarize and CacheMiddleware with a configurable MAX_REQUEST_BODY_BYTES environment variable (default: 10485760 bytes / 10MB).
  • Added a formatBytes() helper function to return clean, human-readable strings (e.g. "10MB", "512KB") for dynamic and accurate 413 Payload Too Large error responses.
  • Added comprehensive unit tests in config_test.go covering default values, custom limits, non-positive bounds, formatting strings, and invalid values.
  • Updated .env.example and the config table in README.md to document the new variable.

Type Of Change

  • Bug fix
  • Feature
  • Documentation
  • Tests
  • Refactor
  • Deployment/config

Affected Areas

  • Gateway (gateway/)
  • Verifier (verifier/)
  • Web (web/)
  • E2E/tests (tests/, run_e2e.sh)
  • Benchmarks (bench/)
  • Deployment/config (deploy/, Docker, env, workflows)
  • Documentation/community files

Contributor Checklist

  • I kept the change focused and avoided unrelated refactors.
  • I updated README/service docs/OpenAPI/env examples when behavior, config, headers, status codes, or public APIs changed.
  • I did not commit secrets, private keys, funded wallets, API keys, or real production URLs.
  • I checked x402/EIP-712 field parity when touching payment context, signatures, timestamps, nonces, chain IDs, receipts, or wallet flow.
  • I checked Docker/Compose/Fly/Vercel docs when touching ports, service names, health checks, or environment variables.

Verification

List the exact commands you ran and their result.

cd gateway
go test -v ./...

# Results:
# === RUN   TestGetMaxRequestBodySize
# --- PASS: TestGetMaxRequestBodySize (0.00s)
# === RUN   TestFormatBytes
# --- PASS: TestFormatBytes (0.00s)
# PASS
# ok      gateway 10.540s


<!-- This is an auto-generated comment: release notes by coderabbit.ai -->

## Summary by CodeRabbit

* **New Features**
  * Added a configurable maximum request body size for AI summary requests, with a default of 10 MB.
  * Oversized requests now return clearer size-limit messages that reflect the configured limit.

* **Documentation**
  * Updated setup documentation and example environment settings to include the new request size limit option.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

…EST_BODY_BYTES

Replace hardcoded 10MB body size limit in handleSummarize and CacheMiddleware with a configurable MAX_REQUEST_BODY_BYTES env var (default 10485760). Add formatBytes() for dynamic 413 error messages, unit tests, .env.example entry, and README config table row.
@vercel

vercel Bot commented Jul 6, 2026

Copy link
Copy Markdown

@tlnarayana005 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 commented Jul 6, 2026

Copy link
Copy Markdown

Hi @tlnarayana005, thanks for opening this PR.

Every contribution helps MicroAI-Paygate grow. If you find the project useful, consider starring the repository — it helps others discover it.

Star MicroAI-Paygate on GitHub

Looking forward to reviewing this PR.

@github-actions github-actions Bot added documentation Improvements or additions to documentation go Pull requests that update go code type:docs Documentation, API docs, examples, or contributor docs. type:testing Tests, coverage, fixtures, or validation-only work. labels Jul 6, 2026
@coderabbitai

coderabbitai Bot commented Jul 6, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The hardcoded 10MB request body size limit in the gateway's summarize handler and cache middleware is replaced with a configurable MAX_REQUEST_BODY_BYTES environment variable, using new getMaxRequestBodySize() and formatBytes() helpers, with accompanying tests and documentation.

Changes

Configurable Max Request Body Size

Layer / File(s) Summary
Config helpers: getMaxRequestBodySize and formatBytes
gateway/config.go, gateway/config_test.go
Adds strconv import, defaultMaxRequestBodyBytes constant, getMaxRequestBodySize() with env parsing and fallback/warning logic, formatBytes() for human-readable output, and unit tests covering both functions.
Wiring into handler and cache middleware
gateway/main.go, gateway/cache.go
Updates handleSummarize and CacheMiddleware to use getMaxRequestBodySize() for MaxBytesReader limits and formatBytes() in 413 error responses instead of hardcoded "10MB" values.
Documentation updates
.env.example, README.md
Documents the new MAX_REQUEST_BODY_BYTES variable, its default (10MB), and its scope (handler and cache middleware for POST /api/ai/summarize).

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

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant CacheMiddleware
  participant Config
  participant handleSummarize
  Client->>CacheMiddleware: POST /api/ai/summarize
  CacheMiddleware->>Config: getMaxRequestBodySize()
  Config-->>CacheMiddleware: maxBody
  CacheMiddleware->>CacheMiddleware: MaxBytesReader(body, maxBody)
  alt body exceeds maxBody
    CacheMiddleware-->>Client: 413 Payload too large (formatBytes(maxBody))
  else within limit
    CacheMiddleware->>handleSummarize: forward request
    handleSummarize->>Config: getMaxRequestBodySize()
    handleSummarize-->>Client: process request
  end
Loading

Possibly related issues

Possibly related PRs

  • AnkanMisra/MicroAI-Paygate#108: Introduces the same MAX_REQUEST_BODY_BYTES environment variable for enforcing request-body size limits in a related verifier service.

Suggested reviewers: AnkanMisra

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly matches the main change: making the gateway request body size limit configurable.
Description check ✅ Passed The description covers summary, change type, affected areas, checklist, and verification, with only optional sections left out.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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

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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
gateway/main.go (1)

467-481: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Set Connection: close on the oversized-body 413 path.
http.MaxBytesReader with Gin’s wrapped writer won’t reliably trigger the server-side close signal here, so this branch should mirror CacheMiddleware and add the header before returning 413.

🤖 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/main.go` around lines 467 - 481, The oversized-body handling in the
request body read branch does not set Connection: close before returning 413.
Update the `requestBody == nil` / `io.ReadAll(c.Request.Body)` error path in
`gateway/main.go` so that when `errors.As(err, &maxBytesErr)` matches, the
response mirrors `CacheMiddleware` by explicitly adding the close header before
`c.JSON(413, ...)`. Use the existing `respondError`, `getMaxRequestBodySize`,
and oversized-body branch as the anchor for the fix.
🤖 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.

Outside diff comments:
In `@gateway/main.go`:
- Around line 467-481: The oversized-body handling in the request body read
branch does not set Connection: close before returning 413. Update the
`requestBody == nil` / `io.ReadAll(c.Request.Body)` error path in
`gateway/main.go` so that when `errors.As(err, &maxBytesErr)` matches, the
response mirrors `CacheMiddleware` by explicitly adding the close header before
`c.JSON(413, ...)`. Use the existing `respondError`, `getMaxRequestBodySize`,
and oversized-body branch as the anchor for the fix.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 8715b4b8-9d91-476a-b8bd-71ffccb2a801

📥 Commits

Reviewing files that changed from the base of the PR and between d8d9bb9 and 6f9374e.

📒 Files selected for processing (6)
  • .env.example
  • README.md
  • gateway/cache.go
  • gateway/config.go
  • gateway/config_test.go
  • gateway/main.go

@vercel

vercel Bot commented Jul 9, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
microai-paygate Ready Ready Preview, Comment Jul 9, 2026 12:33pm

@AnkanMisra

Copy link
Copy Markdown
Owner

@codex review

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 6f9374e503

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread .env.example
HEALTH_CHECK_TIMEOUT_SECONDS=2
# Maximum request body size in bytes (default: 10485760 = 10MB)
# Applies to POST /api/ai/summarize in both the handler and cache middleware.
# MAX_REQUEST_BODY_BYTES=10485760

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.

P2 Badge Pass MAX_REQUEST_BODY_BYTES through Compose

When users follow the documented Docker Compose flow and uncomment/set this value in the root .env, the gateway container still will not see it because the docker-compose.yml gateway environment list only passes selected variables and omits MAX_REQUEST_BODY_BYTES (checked docker-compose.yml lines 8-26). As a result Compose deployments keep using the 10MB default despite the new .env.example/README setting; add this variable to the gateway service environment so the advertised configuration works there too.

Useful? React with 👍 / 👎.

Comment thread gateway/config_test.go
})
}
}

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.

P3 Badge Remove the non-gofmt EOF blank line

The repository instructions require Go changes to be gofmt-clean, but this added trailing blank line makes gofmt -l gateway/config_test.go report the file and git diff --check flags new blank line at EOF. Removing the extra EOF blank line keeps the committed test file formatter-clean and avoids formatting-check churn.

Useful? React with 👍 / 👎.

Comment thread README.md
| `METRICS_PATH` | Gateway | Gateway metrics path. Default `/metrics`; values without a leading slash are normalized. |
| `ALLOWED_ORIGINS` | Gateway | Comma-separated CORS origins, no paths or query strings. |
| `TRUSTED_PROXIES` | Gateway | Comma-separated trusted proxy CIDRs for production IP handling. |
| `MAX_REQUEST_BODY_BYTES` | Gateway | Maximum request body size in bytes for `POST /api/ai/summarize`. Default `10485760` (10 MB). |

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.

P3 Badge Keep gateway-specific docs in sync

This new root README entry documents the knob, but the gateway service README still has its own environment table and does not mention MAX_REQUEST_BODY_BYTES (checked gateway/README.md around the config table). Contributors running or deploying only gateway/ from that service README will miss the new setting, so add the same variable there to keep the service docs aligned with the changed gateway behavior.

Useful? React with 👍 / 👎.

Comment thread README.md
| `METRICS_PATH` | Gateway | Gateway metrics path. Default `/metrics`; values without a leading slash are normalized. |
| `ALLOWED_ORIGINS` | Gateway | Comma-separated CORS origins, no paths or query strings. |
| `TRUSTED_PROXIES` | Gateway | Comma-separated trusted proxy CIDRs for production IP handling. |
| `MAX_REQUEST_BODY_BYTES` | Gateway | Maximum request body size in bytes for `POST /api/ai/summarize`. Default `10485760` (10 MB). |

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.

P2 Badge Add the new gateway limit to production env docs

The production path points operators at .env.production.example and the Render env block in DEPLOY.md, but this change only documents MAX_REQUEST_BODY_BYTES in the local example/root README. In production deployments that use those templates, raising or lowering the summarize payload limit remains undiscoverable and the gateway silently keeps the 10MB default; add the variable to the production env template/deploy block as well.

Useful? React with 👍 / 👎.

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

Labels

documentation Improvements or additions to documentation go Pull requests that update go code type:docs Documentation, API docs, examples, or contributor docs. type:testing Tests, coverage, fixtures, or validation-only work.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants