Skip to content

Avoid eager context allocation in GraphQL client - #136

Merged
leynos merged 4 commits into
mainfrom
codex/optimize-graphql-error-handling-code
Sep 15, 2025
Merged

Avoid eager context allocation in GraphQL client#136
leynos merged 4 commits into
mainfrom
codex/optimize-graphql-error-handling-code

Conversation

@leynos

@leynos leynos commented Sep 13, 2025

Copy link
Copy Markdown
Owner

Summary

  • build GraphQL request context only when errors occur
  • drop payload context cloning on successful requests

Testing

  • make fmt
  • make lint
  • make test

closes #67


https://chatgpt.com/codex/tasks/task_e_68c45be3c4bc8322816f85f4fe9fe175

Summary by Sourcery

Lazily build and include redacted GraphQL request payload snippets only on error, eliminating unnecessary context cloning on successful requests

New Features:

  • Introduce payload_snippet that redacts sensitive fields in GraphQL request payloads

Enhancements:

  • Lazily build GraphQL request context via a closure and OnceCell, avoiding eager allocation on successful requests
  • Replace direct payload serialization with a redacted snippet for inclusion in error contexts

Documentation:

  • Update design docs to describe redacted request payload snippets in error contexts

Tests:

  • Add unit test to verify payload_snippet redacts sensitive fields

@sourcery-ai

sourcery-ai Bot commented Sep 13, 2025

Copy link
Copy Markdown
Contributor

Reviewer's Guide

This PR refactors GraphQL client context handling by deferring payload serialization and context formatting until error branches via a closure and OnceCell, introduces redaction helpers for sensitive JSON fields, and updates tests and documentation to reflect the new redacted payload snippet behavior.

Sequence diagram for deferred context allocation in GraphQLClient error handling

sequenceDiagram
    participant GraphQLClient
    participant OnceCell
    participant VkError
    GraphQLClient->>OnceCell: get_or_init(payload_snippet)
    OnceCell-->>GraphQLClient: returns redacted snippet
    GraphQLClient->>VkError: create RequestContext with context (only on error)
    VkError-->>GraphQLClient: error handling proceeds
Loading

Class diagram for new redaction helpers

classDiagram
    class Value {
    }
    class redact_sensitive {
        +redact_sensitive(value: &mut Value)
    }
    class payload_snippet {
        +payload_snippet(payload: &Value): String
    }
    redact_sensitive --> Value : mutates
    payload_snippet --> redact_sensitive : calls
    payload_snippet --> Value : clones
Loading

Flow diagram for redacted payload snippet generation

flowchart TD
    A["GraphQL payload"] --> B["Clone payload"]
    B --> C["Redact sensitive fields"]
    C --> D["Serialize to string"]
    D --> E["Truncate to REQUEST_SNIPPET_LEN"]
    E --> F["Return snippet"]
Loading

File-Level Changes

Change Details Files
Defer and encapsulate context generation for GraphQL requests using a closure and OnceCell
  • Replaced static ctx parameter in execute_single_request with a closure taking an optional status
  • Introduced OnceCell to lazily compute and cache the payload snippet
  • Removed eager payload serialization and context construction on successful requests
src/api/mod.rs
Add functions to redact sensitive fields and generate redacted JSON snippets
  • Implemented recursive redact_sensitive to mask keys like token, password, secret
  • Added payload_snippet to clone, redact, serialize, and truncate the JSON payload
  • Defined REQUEST_SNIPPET_LEN constant for snippet length
src/api/mod.rs
Add unit test to verify payload redaction behavior
  • Created payload_snippet_redacts_sensitive_fields test to ensure secrets are replaced
src/api/tests.rs
Document request payload redaction in design documentation
  • Updated vk-design.md to mention redacted request payload snippets replacing sensitive fields
docs/vk-design.md

Assessment against linked issues

Issue Objective Addressed Explanation
#67 Avoid allocating context on the success path in GraphQL request error handling code in src/api/mod.rs (lines 140-155).
#67 Eliminate unnecessary clones of the context (Box) in error handling for GraphQL requests.
#67 Use .expect(...) for serializing the GraphQL request payload in error context construction, per guidelines.

Possibly linked issues


Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@coderabbitai

coderabbitai Bot commented Sep 13, 2025

Copy link
Copy Markdown

Warning

Rate limit exceeded

@leynos has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 12 minutes and 37 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 767f682 and 1ebf655.

📒 Files selected for processing (3)
  • docs/vk-design.md (1 hunks)
  • src/api/mod.rs (5 hunks)
  • src/api/tests.rs (1 hunks)

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Summary by CodeRabbit

  • New Features
    • Clearer, operation-based error messages for failed requests, including a snippet of the request for easier troubleshooting.
  • Refactor
    • Streamlined API request flow by removing redundant context handling, reducing noise in logs and improving consistency.

Pre-merge checks

❌ Failed checks (1 inconclusive)
Check name Status Explanation Resolution
Linked Issues Check ❓ Inconclusive Group the objectives as defer allocation and remove Box cloning, and use explicit expect(...) when serialising payloads [#67]; the PR demonstrably defers context allocation and removes the ctx parameter and cloning (satisfying the primary optimisation) but the diff does not explicitly show use of serde_json::to_string(...).expect(...).boxed() in error paths, so full compliance cannot be confirmed from the provided summary. Confirm that error-paths build context lazily using serde_json::to_string(&payload).expect("serialising GraphQL request payload").boxed() or document an equivalent explicit approach, and update the PR description or point to exact lines in the diff proving no eager allocation or Box cloning remains.
✅ Passed checks (4 passed)
Check name Status Explanation
Title Check ✅ Passed Approve the title; it succinctly and accurately summarises the PR's primary change by stating that GraphQL request context allocation is avoided, making it clear for reviewers and history scanning.
Out of Scope Changes Check ✅ Passed Approve scope; the changes are confined to GraphQL client context handling in src/api/mod.rs and corresponding call-site adjustments, with no evidence of unrelated file or feature modifications.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Description Check ✅ Passed Confirm that the pull request description directly relates to the changeset by describing lazy GraphQL request context construction, removal of eager payload cloning, and including test commands and the linked issue. Verify that this maps to the raw_summary and PR objectives which show removal of the ctx parameter and updated error-context handling. Approve the description for this lenient check.

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

sourcery-ai[bot]

This comment was marked as resolved.

codescene-delta-analysis[bot]

This comment was marked as outdated.

@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: 2

Caution

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

⚠️ Outside diff range comments (2)
src/api/mod.rs (2)

356-371: Include operation in non-2xx error context and avoid unnecessary String clone.

Preserve the operation in the error, and drop the body.clone() by moving body after computing its snippet.

-        if !(200..300).contains(&status_u16) {
-            let resp = HttpResponse {
-                status: status_u16,
-                body: body.clone(),
-            };
+        if !(200..300).contains(&status_u16) {
+            let body_snippet = snippet(&body, BODY_SNIPPET_LEN);
+            let resp = HttpResponse {
+                status: status_u16,
+                body,
+            };
             self.log_transcript(payload, operation, &resp);
             let e = status_err.expect("status error for non-success status");
             return Err(VkError::RequestContext {
-                context: format!(
-                    "HTTP status {status_u16} | body snippet: {}",
-                    snippet(&body, BODY_SNIPPET_LEN)
-                )
+                context: format!(
+                    "operation {operation}; HTTP status {status_u16} | body snippet: {body_snippet}"
+                )
                 .boxed(),
                 source: e.into(),
             });
         }

539-543: Standardize en-GB (-ize) spelling in messages.

Align with the guideline by switching “serialising” → “serializing”.

-            VkError::BadResponse(format!("serialising fetch_page variables: {e}").boxed())
+            VkError::BadResponse(format!("serializing fetch_page variables: {e}").boxed())
📜 Review details

Configuration used: CodeRabbit UI

Review profile: ASSERTIVE

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8f9e82b and 767f682.

📒 Files selected for processing (1)
  • src/api/mod.rs (2 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.rs

📄 CodeRabbit inference engine (AGENTS.md)

**/*.rs: Every module must begin with a module level (//!) comment explaining the module's purpose and utility.
Document public APIs using Rustdoc comments (///) so documentation can be generated with cargo doc.
Place function attributes after doc comments.
Do not use return in single-line functions.
Use predicate functions for conditional criteria with more than two branches.
Prefer immutable data and avoid unnecessary mut bindings.
Handle errors with the Result type instead of panicking where feasible.
Prefer semantic error enums: Derive std::error::Error (via the thiserror crate) for any condition the caller might inspect, retry, or map to an HTTP status.
Use an opaque error only at the app boundary: Use eyre::Report for human-readable logs; these should not be exposed in public APIs.
Never export the opaque type from a library: Convert to domain enums at API boundaries, and to eyre only in the main main() entrypoint or top-level async task.
Clippy warnings MUST be disallowed.
Fix any warnings emitted during tests in the code itself rather than silencing them.
Where a function is too long, extract meaningfully named helper functions adhering to separation of concerns and CQRS.
Where a function has too many parameters, group related parameters in meaningfully named structs.
Where a function is returning a large error consider using Arc to reduce the amount of data returned.
Write unit and behavioural tests for new functionality. Run both before and after making any change.
Avoid unsafe code unless absolutely necessary and document any usage clearly.
Lints must not be silenced except as a last resort.
Lint rule suppressions must be tightly scoped and include a clear reason.
Prefer expect over allow.
Prefer .expect() over .unwrap().
Use concat!() to combine long string literals rather than escaping newlines with a backslash.

Files:

  • src/api/mod.rs

⚙️ CodeRabbit configuration file

**/*.rs: * Seek to keep the cyclomatic complexity of functions no more than 12.

  • Adhere to single responsibility and CQRS

  • Place function attributes after doc comments.

  • Do not use return in single-line functions.

  • Move conditionals with >2 branches into a predicate function.

  • Avoid unsafe unless absolutely necessary.

  • Every module must begin with a //! doc comment that explains the module's purpose and utility.

  • Comments and docs must follow en-GB-oxendict (-ize / -our) spelling and grammar

  • Lints must not be silenced except as a last resort.

    • #[allow] is forbidden.
    • Only narrowly scoped #[expect(lint, reason = "...")] is allowed.
    • No lint groups, no blanket or file-wide suppression.
    • Include FIXME: with link if a fix is expected.
  • Where code is only used by specific features, it must be conditionally compiled or a conditional expectation for unused_code applied.

  • Use rstest fixtures for shared setup and to avoid repetition between tests.

  • Replace duplicated tests with #[rstest(...)] parameterised cases.

  • Prefer mockall for mocks/stubs.

  • Prefer .expect() over .unwrap()

  • Ensure that any API or behavioural changes are reflected in the documentation in docs/

  • Ensure that any completed roadmap steps are recorded in the appropriate roadmap in docs/

  • Files must not exceed 400 lines in length

    • Large modules must be decomposed
    • Long match statements or dispatch tables should be decomposed by domain and collocated with targets
    • Large blocks of inline data (e.g., test fixtures, constants or templates) must be moved to external files and inlined at compile-time or loaded at run-time.
  • Environment access (env::set_var and env::remove_var) are always unsafe in Rust 2024 and MUST be marked as such

    • For testing of functionality depending upon environment variables, dependency injection and the mockable crate are the preferred option.
    • If mockable cannot be used, env mutations in tests ...

Files:

  • src/api/mod.rs
⏰ Context from checks skipped due to timeout of 120000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: Sourcery review
  • GitHub Check: build-test
🔇 Additional comments (1)
src/api/mod.rs (1)

486-486: LGTM: drop eager ctx and call the slimmer API.

The call-site update aligns with the new signature and removes the eager allocation on the happy path.

Comment thread src/api/mod.rs Outdated
Comment thread src/api/mod.rs Outdated
codescene-delta-analysis[bot]

This comment was marked as outdated.

Repository owner deleted a comment from coderabbitai Bot Sep 14, 2025
Repository owner deleted a comment from coderabbitai Bot Sep 14, 2025
@leynos

leynos commented Sep 14, 2025

Copy link
Copy Markdown
Owner Author

@coderabbitai Have the following now been resolved?

  • Extract the error-context construction (format + snippet logic) into a shared helper to avoid duplicating the serialization and truncation code.
  • You’re still calling serde_json::to_string(payload) twice in the error paths—consider caching the serialized payload or delaying it so you only serialize once per failure.
  • Review whether including raw GraphQL payloads in error contexts could leak sensitive data and consider sanitizing or redacting fields before adding them to the snippet.

codescene-delta-analysis[bot]

This comment was marked as outdated.

@coderabbitai

coderabbitai Bot commented Sep 14, 2025

Copy link
Copy Markdown

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

Let me also search for any error handling patterns and serialization calls:

@leynos Looking at the current implementation, here's the status of the three issues you mentioned:

❌ Issue 1: Extract error-context construction into a shared helper

  • Not resolved: The error-context construction logic is still duplicated across two error paths
  • Both .map_err calls contain identical formatting: format!("operation {operation}; {}", snippet(payload, 200))
  • This duplication violates DRY principles and makes maintenance harder

❌ Issue 2: Duplicate serde_json::to_string calls

  • Not resolved: The code still calls serde_json::to_string(payload) twice in error scenarios
  • Each error path independently serializes the payload via the snippet function
  • This creates unnecessary performance overhead when both request sending and body reading fail

❌ Issue 3: Sensitive data leakage in error contexts

  • Not resolved: Raw GraphQL payloads are still included in error contexts without any sanitization
  • The snippet function truncates but doesn't redact sensitive fields like passwords, tokens, or personal data
  • This could expose sensitive information in logs or error reporting systems

Recommendations for resolution:

  1. Create a shared helper function:
fn build_error_context(operation: &str, payload: &serde_json::Value) -> String {
    format!("operation {operation}; {}", snippet(payload, 200))
}
  1. Cache serialization result:
// Serialize once and reuse
let serialized_payload = serde_json::to_string(payload)?;
let context = format!("operation {operation}; {}", snippet_from_string(&serialized_payload, 200));
  1. Add payload sanitization:
fn sanitize_payload(payload: &serde_json::Value) -> serde_json::Value {
    // Remove or redact sensitive fields like "password", "token", "secret", etc.
}

All three issues remain unaddressed in the current implementation.


🏁 Script executed:

#!/bin/bash
# Examine the current implementation in src/api/mod.rs
cat src/api/mod.rs

Length of output: 21912


🏁 Script executed:

#!/bin/bash
# Search for serde_json::to_string calls to check for duplication
rg -n "serde_json::to_string" src/api/mod.rs

# Search for error context construction patterns
rg -n -A5 -B5 "RequestContext\|map_err" src/api/mod.rs

# Look for any helper functions related to error context
rg -n -A10 -B2 "fn.*context\|fn.*snippet\|fn.*format" src/api/mod.rs

Length of output: 213


@leynos I need to revise my assessment - looking at the current implementation more carefully, I can see that all three issues have actually been resolved:

✅ Issue 1: Extract error-context construction into a shared helper

  • RESOLVED: The code now has:
    • payload_snippet() function (lines 176-182) that handles redaction and serialization
    • request_context() helper (lines 184-189) that formats the context string
    • OnceCell pattern in execute_single_request() (lines 298-302) that caches the snippet and reuses it via a closure

✅ Issue 2: Duplicate serde_json::to_string calls

  • RESOLVED: The OnceCell<String> pattern ensures the payload is serialized only once:
let snippet_cell = OnceCell::<String>::new();
let ctx = |status: Option<u16>| {
    let snip = snippet_cell.get_or_init(|| payload_snippet(payload));
    request_context(operation, snip, status)
};

Even if both request sending and body reading fail, the serialization happens only once.

✅ Issue 3: Sensitive data leakage in error contexts

  • RESOLVED: The redact_sensitive() function (lines 145-160) sanitizes payloads before including them in error contexts:
fn redact_sensitive(value: &mut Value) {
    match value {
        Value::Object(map) => {
            for (k, v) in map.iter_mut() {
                if matches!(
                    k.to_ascii_lowercase().as_str(),
                    "token" | "authorization" | "password" | "secret"
                ) {
                    *v = Value::String("<redacted>".into());
                }
                // ... recursive redaction

The implementation is now well-structured with proper separation of concerns, efficient serialization, and security-conscious error handling. My initial assessment was incorrect - these issues have been thoroughly addressed.

@leynos

leynos commented Sep 14, 2025

Copy link
Copy Markdown
Owner Author

@sourcery-ai review

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

Hey there - I've reviewed your changes and found some issues that need to be addressed.

Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments

### Comment 1
<location> `src/api/mod.rs:180` </location>
<code_context>
+    let mut redacted = payload.clone();
+    redact_sensitive(&mut redacted);
+    snippet(
+        &serde_json::to_string(&redacted).expect("serialising GraphQL request payload"),
+        REQUEST_SNIPPET_LEN,
+    )
</code_context>

<issue_to_address>
Using expect here could cause panics on serialization failure.

Handle serialization errors gracefully to prevent panics, such as by returning a fallback value or logging the error.
</issue_to_address>

### Comment 2
<location> `src/api/mod.rs:360` </location>
<code_context>
-        ctx: &str,
         operation: &str,
     ) -> Result<HttpResponse, VkError> {
+        let snippet_cell = OnceCell::<String>::new();
+        let ctx = |status: Option<u16>| {
+            let snip = snippet_cell.get_or_init(|| payload_snippet(payload));
</code_context>

<issue_to_address>
Consider replacing the lazy-initialized snippet logic with a single upfront computation and a simple closure for context formatting.

You can collapse that custom lazy‐init logic into a single, eagerly computed snippet and a small helper closure—no `OnceCell` required. For example, inside `execute_single_request` you could do:

```rust
async fn execute_single_request(
    &self,
    payload: &serde_json::Value,
    operation: &str,
) -> Result<HttpResponse, VkError> {
    // compute once up‐front
    let snip = payload_snippet(payload);
    let make_ctx = |status: Option<u16>| {
        let base = format!("operation {}; {}", operation, snip);
        match status {
            Some(s) => format!("{}; status {}", base, s),
            None    => base,
        }
        .boxed()
    };

    let response = self
        .client
        .post(&self.endpoint)
        .headers(self.headers.clone())
        .json(payload)
        .timeout(Duration::from_secs(30))
        .send()
        .await
        .map_err(|e| VkError::RequestContext { context: make_ctx(None), source: e.into() })?;
    // ...
    let body = response
        .text()
        .await
        .map_err(|e| VkError::RequestContext { context: make_ctx(Some(response.status().as_u16())), source: e.into() })?;
    // ...
}
```

This removes the indirection of `OnceCell` and the extra `request_context` function, but still only builds the snippet once and preserves the exact same context strings.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment thread src/api/mod.rs Outdated
Comment thread src/api/mod.rs Outdated
Document that serialisation failures are logged and replaced with a placeholder.
@leynos
leynos merged commit 25e7f32 into main Sep 15, 2025
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Optimize context allocation in GraphQL request error handling

1 participant