Skip to content

Change/incorrect parameters cause errors#64

Merged
kjdev merged 2 commits into
masterfrom
change/incorrect-parameters-cause-errors
May 2, 2025
Merged

Change/incorrect parameters cause errors#64
kjdev merged 2 commits into
masterfrom
change/incorrect-parameters-cause-errors

Conversation

@kjdev

@kjdev kjdev commented May 2, 2025

Copy link
Copy Markdown
Owner

Summary by CodeRabbit

  • Bug Fixes

    • Improved validation for compression quality and mode parameters, ensuring invalid values now cause immediate failure with clear error messages.
    • Enhanced error handling during incremental compression and decompression, with stricter checks on operation modes and early termination on invalid inputs.
  • Tests

    • Added and updated tests to cover various valid and invalid argument scenarios, verifying accurate error reporting and handling for edge cases.

@coderabbitai

coderabbitai Bot commented May 2, 2025

Copy link
Copy Markdown

Walkthrough

This update introduces stricter validation and enhanced error handling for Brotli compression and decompression in the PHP extension. The encoder creation function is refactored to accept an additional parameter controlling error behavior, with improved error messages and conditional fallbacks. Validation for compression quality and mode is now stricter, aborting operations on invalid input. Incremental compression and decompression functions also validate operation modes, emitting warnings and returning failure on invalid values. Corresponding tests are added and updated to verify argument validation and error handling, including cases with invalid parameters.

Changes

File(s) Change Summary
brotli.c Refactored encoder creation to php_brotli_context_create_encoder_ex with an extra parameter for error handling and validation; added stricter parameter checks and improved error reporting for compression and decompression functions; validated incremental compression and decompression modes.
tests/compress_args.phpt Added new test to verify brotli_compress() behavior with various quality and mode arguments, including invalid cases and expected warnings/errors.
tests/incremental_compress_add_args.phpt Updated test to check error handling in incremental compression with invalid quality and mode; improved error output and validation; added test case for invalid incremental mode.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant PHP_Extension
    participant Brotli_Encoder

    User->>PHP_Extension: brotli_compress(data, quality, mode)
    PHP_Extension->>PHP_Extension: Validate quality and mode
    alt Invalid parameters
        PHP_Extension-->>User: Emit warning, return failure
    else Valid parameters
        PHP_Extension->>Brotli_Encoder: Create encoder with params
        alt Encoder creation fails
            PHP_Extension-->>User: Emit error, return failure
        else Encoder created
            PHP_Extension->>Brotli_Encoder: Compress data
            Brotli_Encoder-->>PHP_Extension: Compressed data
            PHP_Extension-->>User: Return compressed data
        end
    end
Loading
sequenceDiagram
    participant User
    participant PHP_Extension

    User->>PHP_Extension: brotli_compress_add(resource, data, mode)
    PHP_Extension->>PHP_Extension: Validate mode
    alt Invalid mode
        PHP_Extension-->>User: Emit warning, return false
    else Valid mode
        PHP_Extension->>PHP_Extension: Compress incrementally
        PHP_Extension-->>User: Return result
    end
Loading

Possibly related PRs

  • kjdev/php-ext-brotli#62: Introduced the original php_brotli_context_create_encoder function, which is directly refactored and extended in this PR for stricter error handling and parameter validation.

Poem

In the warren of code, a bunny hops fast,
Validating each parameter, catching errors at last.
With stricter checks and warnings that chime,
Compression is safer, and tests run just fine.
So here’s to robust code, where bugs are few—
🐇 This rabbit approves these changes for you!


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8a40dd5 and 5d461de.

📒 Files selected for processing (3)
  • brotli.c (6 hunks)
  • tests/compress_args.phpt (1 hunks)
  • tests/incremental_compress_add_args.phpt (4 hunks)
✅ Files skipped from review due to trivial changes (1)
  • tests/compress_args.phpt
🚧 Files skipped from review as they are similar to previous changes (1)
  • brotli.c
⏰ Context from checks skipped due to timeout of 90000ms (20)
  • GitHub Check: ci (8.1, x86, nts, vs16, true)
  • GitHub Check: ci (8.1, x86, nts, vs16, false)
  • GitHub Check: ci (8.1, x86, ts, vs16, true)
  • GitHub Check: ci (8.1, x64, nts, vs16, true)
  • GitHub Check: ci (8.2, x64, nts, vs16, true)
  • GitHub Check: ci (8.2, x86, ts, vs16, false)
  • GitHub Check: ci (8.2, x86, ts, vs16, true)
  • GitHub Check: ci (8.2, x86, nts, vs16, true)
  • GitHub Check: ci (8.2, x86, nts, vs16, false)
  • GitHub Check: ci (8.3, x86, ts, vs16, true)
  • GitHub Check: ci (8.3, x86, ts, vs16, false)
  • GitHub Check: ci (8.1-alpine, apcu, php, linux/amd64)
  • GitHub Check: ci (8.3-alpine, apcu, php, linux/386)
  • GitHub Check: ci (8.4, x86, nts, vs17, true)
  • GitHub Check: ci (7.0-alpine, ghcr.io/kjdev/php, linux/amd64)
  • GitHub Check: ci (8.1-alpine, php, linux/amd64)
  • GitHub Check: ci (8.2-zts-alpine, system, apcu, php, linux/amd64)
  • GitHub Check: ci (7.3-alpine, ghcr.io/kjdev/php, linux/amd64)
  • GitHub Check: ci (8.4, x86, ts, vs17, true)
  • GitHub Check: ci (8.3-zts-alpine, apcu, php, linux/amd64)
🔇 Additional comments (6)
tests/incremental_compress_add_args.phpt (6)

9-9: Well-designed function signature enhancement.

The added $types parameter makes the test function more flexible, enabling testing of custom mode types including invalid ones. This is crucial for validating the error handling capabilities of the Brotli extension.


12-15: Good approach for extending test cases.

Using array_merge() to combine default mode types with custom ones is a clean implementation that avoids code duplication and allows for targeted testing of specific scenarios.


22-25: Essential error handling improvement.

This check properly validates the return value of brotli_compress_init(), ensuring the test doesn't proceed with invalid resources. This is critical for robust error handling and aligns with the PR objective of addressing parameter-related errors.


28-34: Improved validation for incremental compression.

The added error checking for brotli_compress_add() result ensures proper detection and reporting of failures during the compression process. Including the mode type key in the error message helps identify which specific mode caused the failure.


51-51: Valuable test case for error handling.

This test case specifically targets the handling of invalid mode types, which directly addresses the PR's objective of fixing incorrect parameter errors. It verifies that the Brotli extension properly validates operation mode parameters before attempting compression.


66-67: Expected output properly updated for error cases.

The expected output now correctly includes appropriate warning messages for each error condition:

  • Invalid quality values (too high or negative)
  • Invalid mode values (out of range or negative)
  • Invalid operation mode for incremental compression

These updates ensure that the test properly verifies the extension's error reporting behavior.

Also applies to: 70-71, 83-84, 87-88, 92-94

✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@kjdev

kjdev commented May 2, 2025

Copy link
Copy Markdown
Owner Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented May 2, 2025

Copy link
Copy Markdown
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@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

🔭 Outside diff range comments (2)
brotli.c (2)

138-153: ⚠️ Potential issue

Symmetric leak on invalid mode path

The same leak scenario exists for an invalid mode (§ lines 138-153). The encoder handle must be destroyed before returning.

@@
-        if (fail) {
-            return FAILURE;
-        }
+        if (fail) {
+            BrotliEncoderDestroyInstance(ctx->encoder);
+            ctx->encoder = NULL;
+            return FAILURE;
+        }

135-137: 🛠️ Refactor suggestion

No range validation for lgwin parameter

lgwin defaults to BROTLI_DEFAULT_WINDOW, but if the caller passes an explicit (non-zero) value outside Brotli’s supported 10-24 range the subsequent BrotliEncoderSetParameter call will just fail, causing the generic “failed to set compression parameters” message later.
Consider performing an explicit bounds check similar to quality and mode, so users receive precise feedback.

🧹 Nitpick comments (3)
brotli.c (1)

155-164: Minor: chain of BrotliEncoderSetParameter calls obscures which parameter failed

Using the logical OR chain loses information about which individual SetParameter failed. Splitting them or at least checking the return value one-by-one would surface the actual reason to users and aid debugging.

tests/compress_args.phpt (1)

23-28: Tiny nit — use constants for readability

Instead of raw 0, 1, 2 literals for mode, consider the public constants (BROTLI_GENERIC, BROTLI_TEXT, BROTLI_FONT). This makes the intent clearer and keeps the test resilient to future enum changes. Same remark for quality where you could reuse BROTLI_COMPRESS_LEVEL_* macros.

tests/incremental_compress_add_args.phpt (1)

45-51: Nit — duplicate loop values

The second foreach uses [0, 1, 2, 3, -1], but the first value (0) duplicates the previous quality loop and produces identical output. Trimming unnecessary iterations can shorten test run-time.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a14f7e0 and 8a40dd5.

📒 Files selected for processing (3)
  • brotli.c (6 hunks)
  • tests/compress_args.phpt (1 hunks)
  • tests/incremental_compress_add_args.phpt (4 hunks)

Comment thread brotli.c
Comment thread brotli.c
Comment on lines 122 to 134
if (quality < BROTLI_MIN_QUALITY || quality > BROTLI_MAX_QUALITY) {
php_error_docref(NULL, E_WARNING,
"brotli: compression level (%ld) "
"must be within %d..%d",
(long)quality, BROTLI_MIN_QUALITY, BROTLI_MAX_QUALITY);
"%s compression quality (%ld)%s:"
" must be within %d..%d",
(fail ? "failed to" : "brotli: set"),
(long)quality,
(fail ? "": " to BROTLI_COMPRESS_LEVEL_DEFAULT"),
BROTLI_MIN_QUALITY, BROTLI_MAX_QUALITY);
if (fail) {
return FAILURE;
}
quality = BROTLI_DEFAULT_QUALITY;
}

@coderabbitai coderabbitai Bot May 2, 2025

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue

Possible memory leak when quality validation fails

BrotliEncoderCreateInstance() is called at line 115 and the returned handle is stored in ctx->encoder.
If quality is out of range and fail is non-zero, control jumps to this return FAILURE; path, but the previously-allocated encoder instance is never destroyed, leaking native memory.

@@
-        if (fail) {
-            return FAILURE;
-        }
+        if (fail) {
+            BrotliEncoderDestroyInstance(ctx->encoder);
+            ctx->encoder = NULL;
+            return FAILURE;
+        }

Please apply similar cleanup wherever early-returns occur after the encoder has been created.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (quality < BROTLI_MIN_QUALITY || quality > BROTLI_MAX_QUALITY) {
php_error_docref(NULL, E_WARNING,
"brotli: compression level (%ld) "
"must be within %d..%d",
(long)quality, BROTLI_MIN_QUALITY, BROTLI_MAX_QUALITY);
"%s compression quality (%ld)%s:"
" must be within %d..%d",
(fail ? "failed to" : "brotli: set"),
(long)quality,
(fail ? "": " to BROTLI_COMPRESS_LEVEL_DEFAULT"),
BROTLI_MIN_QUALITY, BROTLI_MAX_QUALITY);
if (fail) {
return FAILURE;
}
quality = BROTLI_DEFAULT_QUALITY;
}
if (quality < BROTLI_MIN_QUALITY || quality > BROTLI_MAX_QUALITY) {
php_error_docref(NULL, E_WARNING,
"%s compression quality (%ld)%s:"
" must be within %d..%d",
(fail ? "failed to" : "brotli: set"),
(long)quality,
(fail ? "" : " to BROTLI_COMPRESS_LEVEL_DEFAULT"),
BROTLI_MIN_QUALITY, BROTLI_MAX_QUALITY);
if (fail) {
BrotliEncoderDestroyInstance(ctx->encoder);
ctx->encoder = NULL;
return FAILURE;
}
quality = BROTLI_DEFAULT_QUALITY;
}

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

release processing is now performed by the caller.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

@kjdev Thanks for the clarification. I see now that the calling functions (like brotli_compress and others) are handling the cleanup by calling php_brotli_context_close(&ctx) when an error occurs. This design properly manages memory resources without leaking, as the responsibility for cleanup is consistently placed with the caller rather than within the encoder creation function.


✏️ Learnings added
Learnt from: kjdev
PR: kjdev/php-ext-brotli#64
File: brotli.c:122-134
Timestamp: 2025-05-02T04:03:47.781Z
Learning: In the php-ext-brotli extension, encoder/decoder resource cleanup is deliberately handled by the caller functions rather than within resource creation functions like `php_brotli_context_create_encoder_ex`. The cleanup is done via `php_brotli_context_close()` which properly destroys any encoder/decoder instances.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

@kjdev kjdev force-pushed the change/incorrect-parameters-cause-errors branch from 174a23b to 5d461de Compare May 2, 2025 04:05
@kjdev

kjdev commented May 2, 2025

Copy link
Copy Markdown
Owner Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented May 2, 2025

Copy link
Copy Markdown
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@kjdev kjdev merged commit 5d461de into master May 2, 2025
@kjdev kjdev deleted the change/incorrect-parameters-cause-errors branch May 2, 2025 04:12
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.

1 participant