Skip to content

feat: Enable cross-trigger transactions via shared context #9794

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

Open
wants to merge 2 commits into
base: alpha
Choose a base branch
from

Conversation

Yumcoder-dev
Copy link

@Yumcoder-dev Yumcoder-dev commented Jun 10, 2025

Transaction Support Across Parse Server Triggers

This modification extends Parse Server to support multi-operation transactions across beforeSave, afterSave, and other Cloud Code triggers using a shared transactional context.


✨ Features

  • ✅ Create a transaction in beforeSave
  • ✅ Reuse the same MongoDB/PostgreSQL session in nested .save() calls
  • ✅ Preserve context across triggers (beforeSave, afterSave, etc.)
  • ✅ Explicit control over commit and abort timing
  • ✅ Integration with Parse Server’s internal RestWrite logic

🧠 Why

Out-of-the-box, Parse Server creates a new DatabaseController per internal operation, which leads to:

  • Loss of transactional session context across chained .save()s
  • Inability to group multiple object writes into a true transaction (with in trigger event)

This patch ensures the transaction session is persisted across triggers and reused consistently, enabling ACID-safe operations.


🛠 How It Works

1. Modify getRequestObject in triggers.js

Inject transactional helpers into the request.context:

request.context = Object.assign({
  createTransactionalSession: config.database.createTransactionalSession.bind(config.database),
  commitTransactionalSession: config.database.commitTransactionalSession.bind(config.database),
  abortTransactionalSession: config.database.abortTransactionalSession.bind(config.database),
}, context);

2. Extend DatabaseController.js

Add support for:

// new method
setTransactionalSession(session) {
  this._transactionalSession = session;
}

createTransactionalSession() {
  return this.adapter.createTransactionalSession().then(session => {
    this._transactionalSession = session;
    return this._transactionalSession ; // add this line
  });
}

commitTransactionalSession() {
  // currently impl.
}

abortTransactionalSession() {
  // currently impl.
}

3. Patch RestWrite.execute() in RestWrite.js

Apply the shared transaction session before executing write logic:

if (this.context.transaction) {
  this.config.database.setTransactionalSession(this.context.transaction);
}

✅ Usage Example in Cloud Code

Parse.Cloud.beforeSave('TestObject', async (request) => {
  const session = await request.context.createTransactionalSession();
  const context = Object.assign(request.context, { transaction: session });
 
  try {
    const obj1 = new Parse.Object('Dependent_TestObject_1');
    obj1.set('name', request.object.get('name'));
    await obj1.save(null, { context });
  } catch (err) {
    await request.context.abortTransactionalSession();
    throw new Parse.Error(Parse.Error.SCRIPT_FAILED, 'Transaction failed');
  }
});

Parse.Cloud.afterSave('TestObject', async (request) => {
  const { transaction, commitTransactionalSession, abortTransactionalSession } = request.context;
  const context = { transaction };

  try {
    const obj2 = new Parse.Object('Dependent_TestObject_2');
    obj2.set('name', request.object.get('name'));
    await obj2.save(null, { context });

    await commitTransactionalSession();
  } catch (err) {
    await abortTransactionalSession();
    throw new Parse.Error(Parse.Error.SCRIPT_FAILED, 'Transaction failed');
  }
});

🧪 Behavior

  • context.transaction is injected into every .save() call
  • Nested triggers can access and reuse the transaction session
  • RestWrite ensures internal DB calls are linked to the correct transaction
  • Final commit/abort logic is handled manually in the final trigger (usually afterSave)

Summary by CodeRabbit

  • New Features

    • Added support for transactional database sessions during write operations, enhancing data consistency and isolation.
    • Exposed transactional session management methods within trigger contexts for greater control during trigger execution.
    • Introduced automated Gitpod development environment setup for easier onboarding and development.
  • Bug Fixes

    • Ensured transactional sessions are properly cleared after operations, preventing potential session leakage.

Copy link

I will reformat the title to use the proper commit message syntax.

@parse-github-assistant parse-github-assistant bot changed the title feat: enable cross-trigger transactions via shared context feat: Enable cross-trigger transactions via shared context Jun 10, 2025
Copy link

parse-github-assistant bot commented Jun 10, 2025

🚀 Thanks for opening this pull request!

Copy link

coderabbitai bot commented Jun 10, 2025

📝 Walkthrough

Walkthrough

A new Gitpod configuration file is introduced to automate development environment setup. The DatabaseController class gains a setter for transactional sessions and updates its session creation method to return the session. The RestWrite class now sets a transactional session if present in the context. Trigger request objects are enhanced to include bound transactional session methods in their context.

Changes

File(s) Change Summary
.gitpod.yml Added configuration file to automate Gitpod environment setup, including dependency installation, build, and application start commands.
src/Controllers/DatabaseController.js Added setTransactionalSession method; updated createTransactionalSession to return the session after assignment.
src/RestWrite.js Modified execute method to set transactional session on the database if a transaction exists in the context before proceeding, and clear it after completion.
src/triggers.js Enhanced request.context in trigger-related requests to merge in bound transactional session methods from the database, making them accessible during trigger events.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant RestWrite
    participant DatabaseController

    Client->>RestWrite: execute(context)
    alt context has transaction
        RestWrite->>DatabaseController: setTransactionalSession(context.transaction)
    end
    RestWrite->>DatabaseController: (proceed with write operation)
    alt context has transaction
        RestWrite->>DatabaseController: setTransactionalSession(null) (finally)
    end
Loading
sequenceDiagram
    participant Trigger
    participant getRequestObject
    participant DatabaseController

    Trigger->>getRequestObject: (for certain trigger types)
    getRequestObject->>DatabaseController: bind createTransactionalSession, commitTransactionalSession, abortTransactionalSession
    getRequestObject->>Trigger: request.context includes bound methods + original context
Loading

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.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

npm warn EBADENGINE Unsupported engine {
npm warn EBADENGINE package: '[email protected]',
npm warn EBADENGINE required: { node: '18 || 19 || 20 || 22' },
npm warn EBADENGINE current: { node: 'v24.2.0', npm: '11.3.0' }
npm warn EBADENGINE }
npm error Exit handler never called!
npm error This is an error with npm itself. Please report this error at:
npm error https://github.com/npm/cli/issues
npm error A complete log of this run can be found in: /.npm/_logs/2025-06-11T20_56_34_086Z-debug-0.log


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 sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai auto-generate unit tests to generate unit tests 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.

@parseplatformorg
Copy link
Contributor

parseplatformorg commented Jun 10, 2025

🎉 Snyk checks have passed. No issues have been found so far.

security/snyk check is complete. No issues have been found. (View Details)

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: 3

🧹 Nitpick comments (3)
.gitpod.yml (1)

7-10: Gitpod task runs both npm run build and npm run start in the same task – can cause blocking

npm run build generally exits, but if the script starts a watcher or leaves a process running (common with tsc -w, webpack-watch, etc.), the subsequent npm run start command will never be executed.
Consider splitting the init and workspace tasks or adding a second task entry:

tasks:
  - init: npm install && npm run build
  - command: npm run start

This keeps the build phase isolated and avoids accidental hangs.

src/Controllers/DatabaseController.js (1)

1694-1697: createTransactionalSession now returns the session – good, but missing defensive check

Returning the session is useful. Add a guard to avoid silently re-creating when one is already active:

+  if (this._transactionalSession) {
+    return Promise.resolve(this._transactionalSession);
+  }
   return this.adapter.createTransactionalSession().then(transactionalSession => {
     this._transactionalSession = transactionalSession;
     return this._transactionalSession;
   });

Prevents nested calls from starting multiple DB transactions.

src/triggers.js (1)

284-288: Minor: avoid per-call re-binding to cut allocation noise

The three bind() calls run on every trigger invocation. Consider hoisting the bound helpers once (e.g. in module scope or caching them on the database instance) and reusing the same function references to reduce needless allocations in hot paths.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1ae3176 and 83ab9f7.

📒 Files selected for processing (4)
  • .gitpod.yml (1 hunks)
  • src/Controllers/DatabaseController.js (1 hunks)
  • src/RestWrite.js (1 hunks)
  • src/triggers.js (1 hunks)

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: 0

♻️ Duplicate comments (1)
src/RestWrite.js (1)

98-100: 🛠️ Refactor suggestion

Guard session-clear with an explicit sessionSet flag

The assignment logic is correct, yet we still mutate the shared DatabaseController.
Introduce a local sessionSet boolean so the subsequent cleanup only runs when this call actually set the session, avoiding accidental removal of a session established by an outer/sibling write.

-if (this.context.transaction) {
-  this.config.database.setTransactionalSession(this.context.transaction)
-}
+let sessionSet = false;
+if (this.context.transaction) {
+  this.config.database.setTransactionalSession(this.context.transaction);
+  sessionSet = true;
+}
🧹 Nitpick comments (1)
src/RestWrite.js (1)

172-177: Nit: use sessionSet & drop stray semicolon

  1. Re-use the sessionSet flag instead of repeating the this.context.transaction check—clearer intent and safer.
  2. The });; leaves an extra semicolon that trips linters (noUnreachable warning in Biome).
-    }).finally(() => {
-      if (this.context.transaction) {
+    })
+    .finally(() => {
+      if (sessionSet) {
         this.config.database.setTransactionalSession(null);
       }
-    });;
+    });
🧰 Tools
🪛 Biome (1.9.4)

[error] 177-177: This code is unreachable

... because this statement will return from the function beforehand

(lint/correctness/noUnreachable)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 83ab9f7 and c23c364.

📒 Files selected for processing (2)
  • src/RestWrite.js (2 hunks)
  • src/triggers.js (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/triggers.js
🧰 Additional context used
🪛 Biome (1.9.4)
src/RestWrite.js

[error] 177-177: This code is unreachable

... because this statement will return from the function beforehand

(lint/correctness/noUnreachable)

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