Skip to content

Release/0.6.0#63

Merged
j03-dev merged 10 commits intomainfrom
release/0.6.0
Jul 15, 2025
Merged

Release/0.6.0#63
j03-dev merged 10 commits intomainfrom
release/0.6.0

Conversation

@j03-dev
Copy link
Copy Markdown
Owner

@j03-dev j03-dev commented Jul 14, 2025

Summary by CodeRabbit

  • New Features

    • Improved handling and serialization of SQLAlchemy relationships in serializers.
    • Added a method to retrieve the numeric HTTP status code from status objects.
  • Performance Improvements

    • Optimized JSON serialization by caching the orjson module and reducing repeated imports.
    • Enhanced serializer performance with SQLAlchemy inspection caching.
    • Added inline hints to key functions for potential speedup.
  • Bug Fixes

    • Refined response body handling for different content types.
  • Tests

    • Introduced new ORM models and added benchmark tests for serializer and response creation performance.
  • Documentation

    • Updated version badge in the documentation to reflect the latest release.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Jul 14, 2025

Walkthrough

This update introduces enhancements to JSON handling and SQLAlchemy integration, optimizes serialization and response construction, and adds new ORM models and benchmarks in tests. It also updates the package version and documentation, improves type handling in response logic, and refines the Status enum with a new method.

Changes

Files / Areas Change Summary
Cargo.toml, README.md Bumped version from 0.5.9 to 0.6.0 in manifest and README badge.
src/json.rs, src/lib.rs Added global orjson module caching, initialization function, and integrated it into module setup.
src/into_response.rs Added #[inline] annotation to convert_to_response function.
src/response.rs Changed Response constructor to accept Bound<PyAny> for body and improved type extraction logic.
src/serializer/mod.rs Enhanced serialization using SQLAlchemy inspection, cached inspect function, improved schema cache, inlined methods.
src/status.rs Simplified __richcmp__ method, added code() method with docstring to Status enum.
tests/test.py Added Dog and User ORM models, new serializer and response benchmarks, refactored test to use global User.

Sequence Diagram(s)

sequenceDiagram
    participant PythonApp
    participant oxapy
    participant orjson
    participant SQLAlchemy

    PythonApp->>oxapy: Initialize module
    oxapy->>orjson: Import and cache orjson (init_orjson)
    oxapy->>SQLAlchemy: Import and cache inspect function

    PythonApp->>oxapy: Create Response(body, status, content_type)
    oxapy->>oxapy: Check body type, handle as bytes/JSON/string

    PythonApp->>oxapy: Serialize SQLAlchemy instance
    oxapy->>SQLAlchemy: Use inspect to get columns/relationships
    oxapy->>oxapy: Serialize fields and nested relationships
Loading

Suggested reviewers

  • LucaZH

Poem

In the garden of code, new features bloom bright,
SQLAlchemy and orjson now work just right.
With benchmarks and models, the tests hop ahead,
And version six brings fresh carrots to bed!
🥕
— A happy CodeRabbit, thumping with delight

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.

🔧 Clippy (1.86.0)
Updating crates.io index

warning: failed to write cache, path: /usr/local/registry/index/index.crates.io-1949cf8c6b5b557f/.cache/ah/as/ahash, error: Permission denied (os error 13)
Downloading crates ...
Downloaded block-buffer v0.10.4
error: failed to create directory /usr/local/registry/cache/index.crates.io-1949cf8c6b5b557f

Caused by:
Permission denied (os error 13)

✨ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

@j03-dev j03-dev linked an issue Jul 14, 2025 that may be closed by this pull request
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (5)
README.md (1)

12-12: Version badge update looks good, but consider adding alt text for accessibility.

The version update from 0.5.9 to 0.6.0 is correct and aligns with the package version bump.

Consider adding alt text to the image for better accessibility:

-<a href='https://github.com/j03-dev/oxapy/#'><img src='https://img.shields.io/badge/version-0.6.0-%23b7410e'/></a>
+<a href='https://github.com/j03-dev/oxapy/#'><img src='https://img.shields.io/badge/version-0.6.0-%23b7410e' alt='Version 0.6.0'/></a>
src/json.rs (2)

13-22: Performance improvements look good, but consider error handling.

The #[inline] attribute and use of cached module are excellent optimizations. However, the unwrap() call could panic if initialization fails.

Consider adding error handling for the case where the module isn't initialized:

-        let orjson_module = ORJSON.get().unwrap();
+        let orjson_module = ORJSON.get().ok_or_else(|| {
+            pyo3::exceptions::PyRuntimeError::new_err("orjson module not initialized")
+        })?;

24-31: Same optimization and error handling consideration applies.

The loads function has the same beneficial optimizations and potential unwrap issue as the dumps function.

Consider the same error handling improvement as suggested for the dumps function:

-        let orjson_module = ORJSON.get().unwrap();
+        let orjson_module = ORJSON.get().ok_or_else(|| {
+            pyo3::exceptions::PyRuntimeError::new_err("orjson module not initialized")
+        })?;
tests/test.py (1)

151-184: Consider making benchmark thresholds more flexible.

While the benchmark tests are well-structured, the hardcoded performance thresholds (0.00012s and 0.000013s) may cause flaky test failures on different hardware or CI environments. Consider:

  1. Using relative performance comparisons instead of absolute thresholds
  2. Making thresholds configurable via environment variables
  3. Skipping these tests in CI or marking them as performance tests

Example improvement:

-    assert end - start < 0.00012
+    # Consider using environment variable for threshold
+    threshold = float(os.environ.get('SERIALIZER_BENCH_THRESHOLD', '0.001'))
+    assert end - start < threshold, f"Serialization took {end - start:.6f}s, expected < {threshold}s"
src/serializer/mod.rs (1)

329-368: Good SQLAlchemy integration, but consider graceful fallback.

The integration with SQLAlchemy's inspection API is well-implemented. However, consider providing a graceful fallback or clearer error handling for cases where SQLAlchemy is not installed but the serializer is used with non-ORM objects.

You might want to check if the instance is actually a SQLAlchemy model before attempting inspection:

+    # Check if this is a SQLAlchemy model
+    if not hasattr(instance.get_type(), "__table__"):
+        # Fallback to simple attribute iteration for non-ORM objects
+        for attr in dir(instance):
+            if not attr.startswith('_'):
+                # ... handle non-ORM objects
+        return dict
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0df92b2 and a262e58.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (9)
  • Cargo.toml (1 hunks)
  • README.md (1 hunks)
  • src/into_response.rs (1 hunks)
  • src/json.rs (1 hunks)
  • src/lib.rs (1 hunks)
  • src/response.rs (1 hunks)
  • src/serializer/mod.rs (4 hunks)
  • src/status.rs (2 hunks)
  • tests/test.py (3 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
tests/test.py (1)
src/serializer/mod.rs (13)
  • serializer (473-473)
  • serializer (474-474)
  • serializer (475-475)
  • serializer (476-476)
  • serializer (477-477)
  • serializer (478-478)
  • serializer (479-479)
  • serializer (480-480)
  • serializer (481-481)
  • serializer (482-482)
  • serializer (483-483)
  • is_valid (143-156)
  • data (214-236)
🪛 markdownlint-cli2 (0.17.2)
README.md

12-12: Images should have alternate text (alt text)

(MD045, no-alt-text)

🔇 Additional comments (17)
Cargo.toml (1)

3-3: Version bump looks good.

The version update from 0.5.9 to 0.6.0 is correct and aligns with the release objectives.

src/lib.rs (1)

471-471: JSON initialization call is correctly placed.

The json::init_orjson(m.py())? call properly initializes the JSON caching subsystem during module setup, which is necessary for the performance optimizations introduced in this release.

src/into_response.rs (1)

79-79: Inline optimization is appropriate for this function.

The #[inline] attribute is a good performance optimization for convert_to_response since it's a small, frequently-called function in the response processing pipeline.

src/json.rs (3)

1-1: Good addition of OnceCell for caching.

The import of OnceCell is appropriate for implementing the module caching mechanism.


5-5: Static caching variable is well-designed.

The ORJSON static variable using OnceCell is an excellent approach for caching the orjson module to avoid repeated imports.


7-11: Initialization function is correctly implemented.

The init_orjson function properly initializes the cached module during Python module setup. The error handling and module import logic are correct.

src/status.rs (2)

186-197: LGTM! Good simplification of the comparison method.

The removal of the explicit Python GIL context and direct return of a Rust bool simplifies the code. PyO3 automatically handles the conversion to Python objects, making this cleaner and more idiomatic.


199-208: LGTM! Useful addition for accessing numeric status codes.

The code method provides a clean way to get the numeric HTTP status code value, which is a common requirement when working with HTTP responses.

src/response.rs (1)

68-77: LGTM! Improved type handling in Response constructor.

The change to Bound<PyAny> is more idiomatic for modern PyO3. The instance check before extraction and explicit conversion for JSON serialization improve type safety and clarity.

tests/test.py (3)

2-5: LGTM! Necessary imports for new functionality.

The imports for SQLAlchemy relationship functionality and time module are required for the new ORM models and benchmark tests.


12-30: LGTM! Well-structured ORM models with proper relationships.

The SQLAlchemy models are correctly defined with:

  • Proper type annotations using Mapped
  • Bidirectional one-to-one relationship between User and Dog
  • Appropriate foreign key constraints

102-114: LGTM! Improved test consistency.

Good refactoring to use the globally defined User ORM model instead of a local definition, improving test consistency.

src/serializer/mod.rs (5)

10-15: LGTM! Appropriate imports for thread-safe caching.

The addition of OnceCell and Arc supports the new SQLAlchemy inspection caching and thread-safe schema caching.


187-197: LGTM! Efficient in-place modification.

Good optimization to directly modify the dictionary instead of cloning it. This reduces memory usage and improves performance.


371-372: LGTM! Improved thread safety with Arc.

The addition of Arc enables safe shared ownership of the cache across threads, which is important for multi-threaded web applications.


461-461: LGTM! Thread-safe lazy initialization.

Using OnceCell for the SQLAlchemy inspect function is the right approach for thread-safe lazy initialization.


463-472: LGTM! Graceful SQLAlchemy initialization.

The module initialization properly handles the optional SQLAlchemy dependency, attempting to cache the inspect function if available without failing if it's not installed.

@j03-dev j03-dev added the new version Bump the version label Jul 14, 2025
@j03-dev j03-dev merged commit a852c1c into main Jul 15, 2025
17 checks passed
@j03-dev j03-dev deleted the release/0.6.0 branch July 15, 2025 08:02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

new version Bump the version

Projects

None yet

Development

Successfully merging this pull request may close these issues.

push new release 0.6.0

1 participant