Skip to content

Conversation

@ymc9
Copy link
Member

@ymc9 ymc9 commented Jun 13, 2025

Summary by CodeRabbit

  • Refactor

    • Improved validation logic for model operations by introducing schema caching and standardized validation methods, resulting in more efficient and consistent validation.
    • Centralized and reused validation and result processing across model operations for better performance and maintainability.
  • Chores

    • Updated dependencies to include a new runtime package for stable JSON stringification.
    • Marked the "Cache validation schemas" task as complete in the project checklist.

@coderabbitai
Copy link

coderabbitai bot commented Jun 13, 2025

Walkthrough

The updates introduce schema caching for input validation in the ORM runtime, refactoring the InputValidator to use a generic validation method and cache schemas using stable stringification. The client proxy and CRUD handler logic are updated to instantiate and share validator and result processor instances. A new dependency, json-stable-stringify, is added.

Changes

File(s) Change Summary
TODO.md Marked "Cache validation schemas" as completed in the checklist.
packages/runtime/package.json Added json-stable-stringify as a runtime dependency.
packages/runtime/src/client/client-impl.ts Refactored to create and share InputValidator and ResultProcessor instances; updated handler signatures.
packages/runtime/src/client/crud/validator.ts Refactored InputValidator to use a generic, schema-caching validate method; updated all validation methods and schema creation signatures.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant ClientProxy
    participant InputValidator
    participant ResultProcessor
    participant ModelCrudHandler

    Client->>ClientProxy: createClientProxy()
    ClientProxy->>InputValidator: instantiate (once)
    ClientProxy->>ResultProcessor: instantiate (once)
    ClientProxy->>ModelCrudHandler: createModelCrudHandler(..., InputValidator, ResultProcessor)
    Client->>ModelCrudHandler: Perform operation (e.g., find, create)
    ModelCrudHandler->>InputValidator: validate(args)
    InputValidator->>InputValidator: fetch/create schema from cache
    InputValidator-->>ModelCrudHandler: validated args
    ModelCrudHandler->>ResultProcessor: process result (if needed)
    ResultProcessor-->>ModelCrudHandler: processed result
    ModelCrudHandler-->>Client: result
Loading

Poem

In the warren of code, a cache now appears,
Schemas remembered, allaying old fears.
Validators gather, but only once born,
No more repeated, no more forlorn.
With stable strings and tidy new flow,
This bunny hops swiftly—validation in tow!
🐇✨

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

@ymc9 ymc9 merged commit 295d5a2 into dev Jun 13, 2025
2 checks passed
Copy link

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

🔭 Outside diff range comments (1)
packages/runtime/package.json (1)

86-99: 💡 Verification agent

🧩 Analysis chain

Add accompanying @types/json-stable-stringify to avoid TS compilation errors

json-stable-stringify is published without bundled typings.
Unless the project globally enables skipLibCheck, importing it (see validator.ts) will break the build.

   "devDependencies": {
+    "@types/json-stable-stringify": "^1.0.0",

Please run pnpm tsc -b after adding the types – the build should succeed without skipLibCheck.


🏁 Script executed:

#!/bin/bash
echo "== Checking skipLibCheck settings =="
rg -n skipLibCheck .

echo
echo "== Checking for @types/json-stable-stringify in devDependencies =="
rg -n "@types/json-stable-stringify" packages/runtime/package.json || echo "Not found"

echo
echo "== Checking for json-stable-stringify in dependencies =="
rg -n "json-stable-stringify" packages/runtime/package.json

echo
echo "== Searching for imports of json-stable-stringify =="
rg -n "json-stable-stringify" -t ts

Length of output: 972


Add missing @types/json-stable-stringify dev dependency

Although skipLibCheck is enabled in your root tsconfig, TypeScript still reports a “Cannot find module 'json-stable-stringify'” error (TS7016) when no declaration file exists. To eliminate this, add the official types package:

• File: packages/runtime/package.json
• Section: devDependencies

   "devDependencies": {
+    "@types/json-stable-stringify": "^1.0.0",

After adding, run pnpm tsc -b to confirm the build passes without missing‐module errors.

🧹 Nitpick comments (3)
TODO.md (1)

56-60: Markdown list indentation violates MD007

Indentation for the newly-checked item is 8 spaces instead of 4, tripping markdownlint.

-        -   [x] Cache validation schemas
+    -   [x] Cache validation schemas
🧰 Tools
🪛 markdownlint-cli2 (0.17.2)

56-56: Unordered list indentation
Expected: 4; Actual: 8

(MD007, ul-indent)


57-57: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


58-58: Unordered list indentation
Expected: 4; Actual: 8

(MD007, ul-indent)


59-59: Unordered list indentation
Expected: 4; Actual: 8

(MD007, ul-indent)


60-60: Unordered list indentation
Expected: 4; Actual: 8

(MD007, ul-indent)

packages/runtime/src/client/client-impl.ts (1)

306-309: Potential memory growth via shared ResultProcessor

ResultProcessor.processResult keeps internal caches (see implementation).
With the same instance now shared by every query, its cache could grow unbounded during a long-lived process (e.g. server).
Consider adding an eviction policy or exposing a clear() API that users can hook into between requests.

packages/runtime/src/client/crud/validator.ts (1)

183-205: Schema cache lacks eviction – risk of unbounded memory usage

schemaCache is a plain Map that only ever grows.
Long-running services executing a large variety of models/operations/options will keep every generated ZodSchema forever.

Consider an LRU cache with a sane upper bound (e.g. 100-500 entries):

-    private schemaCache = new Map<string, ZodSchema>();
+    private readonly schemaCache = new Map<string, ZodSchema>();
+    private static readonly MAX_CACHE_SIZE = 256;
...
-        if (!schema) {
+        if (!schema) {
             schema = getSchema(model, options);
-            this.schemaCache.set(cacheKey!, schema);
+            // simple LRU eviction
+            if (this.schemaCache.size >= InputValidator.MAX_CACHE_SIZE) {
+                const oldestKey = this.schemaCache.keys().next().value;
+                this.schemaCache.delete(oldestKey);
+            }
+            this.schemaCache.set(cacheKey!, schema);
         }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 22246e8 and 6287d46.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (4)
  • TODO.md (1 hunks)
  • packages/runtime/package.json (1 hunks)
  • packages/runtime/src/client/client-impl.ts (3 hunks)
  • packages/runtime/src/client/crud/validator.ts (5 hunks)
🧰 Additional context used
🪛 markdownlint-cli2 (0.17.2)
TODO.md

58-58: Unordered list indentation
Expected: 4; Actual: 8

(MD007, ul-indent)

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build-test (20.x)
🔇 Additional comments (2)
packages/runtime/src/client/client-impl.ts (1)

251-270: Nice centralisation of validator / processor instances

Creating the InputValidator & ResultProcessor once per client avoids thousands of schema rebuilds – good call.
No functional issues spotted here.

packages/runtime/src/client/crud/validator.ts (1)

1-4: Missing type definitions for json-stable-stringify

The default export is CommonJS; without @types/json-stable-stringify the import will produce TS7016.
See package-level comment for the proposed dev-dependency addition.

Comment on lines 47 to 58
validateFindArgs(model: GetModels<Schema>, unique: boolean, args: unknown) {
return this.validate<FindArgs<Schema, GetModels<Schema>, true>>(
this.makeFindSchema(model, unique, true),
return this.validate<
FindArgs<Schema, GetModels<Schema>, true>,
Parameters<typeof this.makeFindSchema>[1]
>(
model,
'find',
{ unique, collection: true },
(model, options) => this.makeFindSchema(model, options),
args
);
}
Copy link

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

collection flag hard-coded to true

validateFindArgs always sets collection: true, enabling skip/take/orderBy even for findUnique and findFirst.
If this is unintended and parity with Prisma is desired, derive the flag from the concrete operation:

-        { unique, collection: true },
+        { unique, collection: !unique },  // findMany → true, findUnique/First → false

Double-check all call-sites (e.g. FindOperationHandler) after the signature change.


I’d like to inspect how makeFindSchema and the other validateFind* helpers use the collection flag. Let me run a few searches in validator.ts:


🏁 Script executed:

#!/bin/bash
# Locate validateFind* methods and makeFindSchema in the validator
rg -n "validateFindArgs" packages/runtime/src/client/crud/validator.ts
rg -n "validateFindUniqueArgs" packages/runtime/src/client/crud/validator.ts || true
rg -n "validateFindFirstArgs" packages/runtime/src/client/crud/validator.ts || true
rg -n "makeFindSchema" -n -A5 -B5 packages/runtime/src/client/crud/validator.ts

Length of output: 1325


I’ll inspect the full makeFindSchema implementation and how options.collection is used:


🏁 Script executed:

#!/bin/bash
# Show the body of makeFindSchema
sed -n '207,350p' packages/runtime/src/client/crud/validator.ts

# Highlight where options.collection is referenced
rg -n "options.collection" -A5 -B5 packages/runtime/src/client/crud/validator.ts

Length of output: 6229


Derive the collection flag from unique

In packages/runtime/src/client/crud/validator.ts (around lines 52–58), the call to makeFindSchema always passes collection: true, which allows pagination and ordering on unique queries (findUnique). To align with Prisma semantics, update it to:

-        { unique, collection: true },
+        { unique, collection: !unique },  // collections only for non‐unique queries

This change will disable skip/take/orderBy for findUnique while still permitting them for findMany and findFirst. After applying, review any call-sites of validateFindArgs to ensure your higher-level handlers continue to work correctly.

📝 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
validateFindArgs(model: GetModels<Schema>, unique: boolean, args: unknown) {
return this.validate<FindArgs<Schema, GetModels<Schema>, true>>(
this.makeFindSchema(model, unique, true),
return this.validate<
FindArgs<Schema, GetModels<Schema>, true>,
Parameters<typeof this.makeFindSchema>[1]
>(
model,
'find',
{ unique, collection: true },
(model, options) => this.makeFindSchema(model, options),
args
);
}
validateFindArgs(model: GetModels<Schema>, unique: boolean, args: unknown) {
return this.validate<
FindArgs<Schema, GetModels<Schema>, true>,
Parameters<typeof this.makeFindSchema>[1]
>(
model,
'find',
- { unique, collection: true },
+ { unique, collection: !unique }, // collections only for non‐unique queries
(model, options) => this.makeFindSchema(model, options),
args
);
}
🤖 Prompt for AI Agents
In packages/runtime/src/client/crud/validator.ts around lines 47 to 58, the
validateFindArgs method currently hard-codes the collection flag to true when
calling makeFindSchema, which incorrectly enables pagination and ordering
options for unique queries like findUnique. To fix this, derive the collection
flag from the unique parameter by setting collection to !unique, so that
collection is false for unique queries and true otherwise. After making this
change, verify all call-sites of validateFindArgs to ensure they handle the
updated signature correctly.

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