Skip to content

Refactor request parsing helpers out of app.main#346

Open
tolga-tom-nook wants to merge 1 commit into
ramimbo:mainfrom
tolga-tom-nook:bounty/320-request-parsing-boundary
Open

Refactor request parsing helpers out of app.main#346
tolga-tom-nook wants to merge 1 commit into
ramimbo:mainfrom
tolga-tom-nook:bounty/320-request-parsing-boundary

Conversation

@tolga-tom-nook
Copy link
Copy Markdown
Contributor

@tolga-tom-nook tolga-tom-nook commented May 26, 2026

Summary

  • Extract request/body/path parsing helpers out of app/main.py into focused app/request_parsing.py
  • Keep the route layer using the same helper names via imports, preserving existing API, wallet, ledger, proof, and admin behavior
  • Add direct regression tests for positive id/sequence validation, proof-hash normalization, string field parsing, and integer field parsing/error messages

Refs #320

Complexity reduced

This moves JSON object parsing, required/optional field coercion, integer parsing, positive bounty/ledger path validation, proof hash normalization, and wallet-address HTTP error mapping behind one small request-parsing boundary. app/main.py keeps route wiring and auth/session helpers, while validation behavior can now be reviewed and tested independently.

Validation

  • ./.venv/bin/python -m pytest tests/test_request_parsing.py tests/test_security.py tests/test_wallet_api.py -q — 87 passed
  • ./.venv/bin/python -m pytest -q — 339 passed
  • ./.venv/bin/python scripts/docs_smoke.py — docs smoke ok
  • ./.venv/bin/python -m ruff format --check . — 50 files already formatted
  • ./.venv/bin/python -m ruff check . — all checks passed
  • ./.venv/bin/python -m mypy app — success
  • git diff --check — passed

No secrets, wallet private keys, payout credentials, private vulnerability details, deployment credentials, or MRWK price claims are included.

Summary by CodeRabbit

  • Refactor

    • Consolidated request validation logic into a dedicated module for improved code maintainability and organization.
  • Tests

    • Added comprehensive test coverage for request parsing and validation functions to enhance system reliability and reduce bugs.

Review Change Stack

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 26, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 93675a0e-7541-4b27-8293-0d4f2cd868f8

📥 Commits

Reviewing files that changed from the base of the PR and between ac99d79 and 115feca.

📒 Files selected for processing (3)
  • app/main.py
  • app/request_parsing.py
  • tests/test_request_parsing.py

📝 Walkthrough

Walkthrough

This PR refactors request parsing helpers from app/main.py into a new dedicated module app/request_parsing.py, improving code organization. The new module centralizes validators (bounty ID, ledger sequence, wallet address, proof hash), JSON/field extraction utilities, and error handling. main.py imports these utilities and removes local implementations. New tests validate all parsing functions.

Changes

Request Parsing Module Extraction

Layer / File(s) Summary
Request parsing validators and normalization
app/request_parsing.py
Module constants define SQLite bounds and 64-character hex regex. Functions positive_bounty_id and positive_ledger_sequence reject non-positive values; normalized_wallet_address wraps wallet normalization and converts WalletError to HTTPException(400); proof_hash_from_path validates and lowercases hex proof hashes or raises HTTP 400.
JSON and field extraction helpers
app/request_parsing.py
json_object asynchronously parses request JSON as dict or raises 400; required_str and optional_str extract string fields with type validation; parse_int, required_int, and optional_int parse integers from values or numeric strings, reject booleans, and raise HTTP 400 on invalid input.
Update main.py to use extracted helpers
app/main.py
New imports pull parsing utilities from app.request_parsing; removed WalletError and normalize_wallet_address imports from app.wallets; deleted local implementations of HEX_HASH_RE, validators (_positive_bounty_id, _positive_ledger_sequence, _normalized_wallet_address, _proof_hash_from_path), and field helpers (_json_object, _required_str, _optional_str, _parse_int, _required_int, _optional_int). All endpoint calls resolve to imported versions.
Test coverage for request parsing module
tests/test_request_parsing.py
Test helper _detail extracts exception messages. Tests validate validators accept positive inputs and reject non-positive values with exact error detail messages; proof_hash_from_path normalizes uppercase hex and rejects invalid length/characters; string helpers enforce required presence and optional defaults with type checking; integer helpers parse signed numeric strings, reject booleans, and report missing required fields.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 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 (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: extracting request parsing helpers from app.main into a separate module, which is the core refactoring described in the pull request.
Description check ✅ Passed The description includes a clear summary of changes, explains complexity reduction, provides comprehensive validation results across multiple test suites and linting checks, and references the related issue (#320), aligning with repository template requirements.
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.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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

Copy link
Copy Markdown
Contributor

@TateLyman TateLyman left a comment

Choose a reason for hiding this comment

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

No blockers from my pass.

Evidence checked:

  • Inspected app/request_parsing.py, app/main.py, and tests/test_request_parsing.py against current origin/main.
  • Verified JSON body parsing, required/optional string parsing, integer parsing, positive bounty/ledger path validation, proof-hash normalization, and wallet-address normalization moved behind app.request_parsing while preserving the same HTTPException status/details used by the route layer.
  • Verified route imports keep the old helper aliases in app/main.py, so API, wallet, ledger, proof, admin, and MCP route call sites keep their existing behavior.
  • Verified new focused tests cover positive path ids, proof-hash normalization/rejection, string helper errors, and integer helper parsing/rejection.
  • Hosted quality check is green; GitHub currently reports mergeState UNSTABLE while CodeRabbit is still processing.

Validation:

  • uv run --extra dev python -m pytest tests/test_request_parsing.py tests/test_security.py tests/test_wallet_api.py -q -> 87 passed.
  • uv run --extra dev python -m pytest -q -> 339 passed.
  • uv run --extra dev ruff check app/main.py app/request_parsing.py tests/test_request_parsing.py -> passed.
  • uv run --extra dev ruff format --check app/main.py app/request_parsing.py tests/test_request_parsing.py -> passed.
  • uv run --extra dev python -m mypy app/main.py app/request_parsing.py -> passed.
  • uv run --extra dev python scripts/docs_smoke.py -> docs smoke ok.
  • git diff --check origin/main...HEAD -> clean.

Copy link
Copy Markdown

@aiautotool aiautotool left a comment

Choose a reason for hiding this comment

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

No blockers found on current head 115feca.

Evidence summary:

  • Inspected app/request_parsing.py, app/main.py, and tests/test_request_parsing.py.
  • Verified the extracted path/body helpers preserve the existing HTTP 400 details for bounty IDs, ledger sequences, wallet addresses, proof hashes, invalid JSON bodies, missing string fields, and integer coercion.
  • Checked that parse_int() still rejects booleans separately from integers, trims signed numeric strings, and keeps None handling split between required/optional field helpers.
  • Confirmed app.main continues to call the same helper names through private aliases, so route behavior stays unchanged while request parsing moves out of the large app module.

Validation:

  • uv run --extra dev python -m pytest tests/test_request_parsing.py tests/test_wallet_api.py::test_github_login_stores_safe_default_for_backslash_next -q -> 5 passed.
  • uv run --extra dev ruff check app/main.py app/request_parsing.py tests/test_request_parsing.py -> passed.
  • uv run --extra dev python -m mypy app/main.py app/request_parsing.py -> success.

No secrets, wallet private keys, payout credentials, private vulnerability details, deployment values, or MRWK price claims are included.

@ramimbo ramimbo added the mrwk:needs-info More information needed label May 26, 2026
@ramimbo
Copy link
Copy Markdown
Owner

ramimbo commented May 26, 2026

Maintainer note after #320 filled: this PR still references closed bounty #320. If you want it considered for the current code-health round, rebase against main, update the bounty reference to #377, and keep the scope distinct from already accepted #328, #337, #364, #375, and #376. This is not accepted or paid as-is.

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

Labels

mrwk:needs-info More information needed

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants