Skip to content

feat(runtime): inject enhanced client or tx context so it can be retrieved in extensions #2018

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Mar 3, 2025

Conversation

Gabrola
Copy link
Contributor

@Gabrola Gabrola commented Feb 27, 2025

Prisma already exposes a $parent property in the context, but this will point towards the unenhanced client or transaction object

Copy link
Contributor

coderabbitai bot commented Feb 27, 2025

📝 Walkthrough

Walkthrough

The changes update the proxy implementation and introduce an integration test for enhanced proxy context behavior. In the proxy code, an extra parameter is now passed to the handler creation, and the get trap returns the provided database/transaction context when queried with a specific property. Additionally, a new test file validates that an enhanced model method correctly increments a counter during record creation, both in and outside a transaction.

Changes

File Path Change Summary
packages/runtime/src/enhancements/node/proxy.ts - Updated makeProxy to pass an additional argument (proxy) to createHandlerProxy
- Modified createHandlerProxy to accept a new parameter dbOrTx and return it when the property '$parent' is accessed.
tests/integration/tests/enhancements/proxy/extension-context.test.ts - Introduced a new test file to validate a Proxy Extension Context
- Added a custom method createWithCounter to enhance model behavior by incrementing a counter during record creation, handling both transactional and non-transactional cases.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant Proxy
    participant Handler

    Caller->>Proxy: Access property "$parent"
    Proxy->>Handler: Invoke get trap with key "$parent"
    Handler-->>Caller: Return dbOrTx (database/transaction context)
Loading
sequenceDiagram
    participant Client
    participant EnhancedModel
    participant CounterModel
    participant TransactionHandler

    Client->>EnhancedModel: call createWithCounter(args)
    EnhancedModel->>CounterModel: Increment counter for the Address model
    alt Operation in Transaction
        EnhancedModel->>TransactionHandler: Execute creation within transaction
    else Operation outside Transaction
        EnhancedModel->>EnhancedModel: Create Address directly
    end
    CounterModel-->>Client: Return updated counter value
Loading

Possibly related PRs

  • fix(runtime): proxy $extends for each and every enhancement #2016: The changes in the main PR modify the makeProxy and createHandlerProxy functions in proxy.ts, while the retrieved PR alters the behavior of the makeProxy function by removing a conditional check related to proxy wrapping; thus, they are directly related through modifications to the same function.

Suggested reviewers

  • ymc9

📜 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 f55a2fd and 981980e.

📒 Files selected for processing (2)
  • packages/runtime/src/enhancements/node/proxy.ts (2 hunks)
  • tests/integration/tests/enhancements/proxy/extension-context.test.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • tests/integration/tests/enhancements/proxy/extension-context.test.ts
  • packages/runtime/src/enhancements/node/proxy.ts
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: OSSAR-Scan
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: build-test (20.x)
  • GitHub Check: build-test (20.x)
  • GitHub Check: dependency-review
  • GitHub Check: build-test (20.x)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

‼️ IMPORTANT
Auto-reply has been disabled for this repository in the CodeRabbit settings. The CodeRabbit bot will not respond to your replies unless it is explicitly tagged.

  • 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.

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 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.

Copy link
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 (2)
tests/integration/tests/enhancements/proxy/extension-context.test.ts (1)

45-48: Clarify the conditional logic comment.

The comment on line 46 states "not running in a transaction, so we need to create a new transaction", but the conditional check is looking for the presence of a $transaction method, which indicates that we're working with a client that can create transactions.

-            if (dbOrTx['$transaction']) {
-                // not running in a transaction, so we need to create a new transaction
+            if (dbOrTx['$transaction']) {
+                // we have a client that can create transactions, not already in a transaction
packages/runtime/src/enhancements/node/proxy.ts (1)

311-313: Effective implementation of context retrieval via a special property.

This code adds support for accessing the enhanced database or transaction context through the $zenstack_parent property, which is the key feature being added in this PR.

Consider adding a JSDoc comment explaining the purpose and usage of the $zenstack_parent property, which would make the code more maintainable and easier to understand:

+        /**
+         * Returns the enhanced database or transaction context that created this proxy.
+         * This allows extensions to access the enhanced client functionality.
+         */
        get(target, propKey) {
            if (propKey === '$zenstack_parent') {
                return dbOrTx;
            }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 82b8d25 and 477fe0d.

📒 Files selected for processing (2)
  • packages/runtime/src/enhancements/node/proxy.ts (2 hunks)
  • tests/integration/tests/enhancements/proxy/extension-context.test.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: build-test (20.x)
  • GitHub Check: build-test (20.x)
  • GitHub Check: build-test (20.x)
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: dependency-review
  • GitHub Check: OSSAR-Scan
🔇 Additional comments (6)
tests/integration/tests/enhancements/proxy/extension-context.test.ts (4)

1-84: Excellent test implementation for the proxy extension context feature.

This new test file effectively validates the functionality of retrieving enhanced client/transaction context in extensions. The test creates a custom method that increments a counter whenever a new Address is created, demonstrating how the enhanced context can be utilized.


31-32: Good implementation of context retrieval using the new property.

The line const dbOrTx = this['$zenstack_parent']; shows how to access the enhanced client or transaction context within an extension, which is the core functionality being added in this PR.


70-73: Effective test coverage for both standalone and transaction contexts.

This test section creates Address entries both individually and within transactions, ensuring that the enhanced context retrieval works correctly in both scenarios.


76-81: Clear validation of the expected behavior.

The test verifies that the Counter model correctly tracks the total number of Address entries created, confirming that the enhanced context is properly accessible within extensions.

packages/runtime/src/enhancements/node/proxy.ts (2)

292-292: Well-implemented modification to pass database/transaction context to the handler proxy.

The change updates the createHandlerProxy call to pass the original target (database or transaction) as a parameter, enabling access to the enhanced context within extensions.


306-306: Appropriate parameter addition for context retrieval.

Adding the dbOrTx parameter to createHandlerProxy enables the proxy to maintain a reference to the original database or transaction object.

@Gabrola Gabrola force-pushed the feat/set-model-parent branch from 477fe0d to d20cbd4 Compare March 1, 2025 01:14
@Gabrola Gabrola force-pushed the feat/set-model-parent branch from d20cbd4 to f55a2fd Compare March 1, 2025 03:58
Copy link
Member

@ymc9 ymc9 left a comment

Choose a reason for hiding this comment

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

I didn't know there's actually the $parent field in client extensions that refer to the current prisma client instance. I saw it in Prisma code but seems not documented anywhere ...

Do you think we should simply proxy this field directly instead of using a separate $zenstack_parent field? Wondering if most people would expect $parent to be enhanced if it originated from an enhanced client. What do you think?

@Gabrola
Copy link
Contributor Author

Gabrola commented Mar 1, 2025

@ymc9 Yeah, actually that makes a lot of sense since the proxy will still allow access to any non-proxied properties; so this shouldn't break any existing usage of $parent. I'll push that change 👍

Copy link
Member

@ymc9 ymc9 left a comment

Choose a reason for hiding this comment

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

Thank you! Looking great now!

@ymc9 ymc9 merged commit 7c243dd into zenstackhq:dev Mar 3, 2025
11 checks passed
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.

2 participants