Skip to content

fix: Server crash from unhandled promise rejection when multiple Cloud Code validator fields fail#10540

Open
dblythy wants to merge 1 commit into
parse-community:alphafrom
dblythy:fix/validator-multiple-field-crash
Open

fix: Server crash from unhandled promise rejection when multiple Cloud Code validator fields fail#10540
dblythy wants to merge 1 commit into
parse-community:alphafrom
dblythy:fix/validator-multiple-field-crash

Conversation

@dblythy

@dblythy dblythy commented Jul 4, 2026

Copy link
Copy Markdown
Member

Closes #8826

Summary by CodeRabbit

  • Bug Fixes
    • Fixed an issue where validation failures involving multiple fields could trigger an unhandled rejection.
    • Invalid input now reliably returns a validation error without leaving behind unexpected async errors.

@parse-github-assistant

Copy link
Copy Markdown

🚀 Thanks for opening this pull request! We appreciate your effort in improving the project. Please let us know once your pull request is ready for review.

Tip

  • Keep pull requests small. Large PRs will be rejected. Break complex features into smaller, incremental PRs.
  • Use Test Driven Development. Write failing tests before implementing functionality. Ensure tests pass.
  • Group code into logical blocks. Add a short comment before each block to explain its purpose.
  • We offer conceptual guidance. Coding is up to you. PRs must be merge-ready for human review.
  • Our review focuses on concept, not quality. PRs with code issues will be rejected. Use an AI agent.
  • Human review time is precious. Avoid review ping-pong. Inspect and test your AI-generated code.

Note

Please respond to review comments from AI agents just like you would to comments from a human reviewer. Let the reviewer resolve their own comments, unless they have reviewed and accepted your commit, or agreed with your explanation for why the feedback was incorrect.

Caution

Pull requests must be written using an AI agent with human supervision. Pull requests written entirely by a human will likely be rejected, because of lower code quality, higher review effort and the higher risk of introducing bugs. Please note that AI review comments on this pull request alone do not satisfy this requirement. Our CI and AI review are safeguards, not development tools. If many issues are flagged, rethink your development approach. Invest more effort in planning and design rather than using review cycles to fix low-quality code.

@coderabbitai

coderabbitai Bot commented Jul 4, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Fixes a server crash caused by an unhandled promise rejection when multiple Cloud Code validated fields fail simultaneously. Refactors field validation in builtInTriggerValidator to collect validation inputs before invoking Promise.all, and adds a regression test verifying no unhandled rejection occurs.

Changes

Validation rejection fix

Layer / File(s) Summary
Refactor field validation scheduling
src/triggers.js
Replaces immediate validateOptions promise creation with collection of [opt, key, val] tuples into optionValidations, then runs Promise.all(optionValidations.map(...)) after the loop.
Regression test for unhandled rejection
spec/CloudCode.Validator.spec.js
Adds a test that attaches an unhandledRejection listener, triggers a function with multiple invalid fields, asserts the rejection is a Parse.Error.VALIDATION_ERROR, verifies no unhandled rejections were captured, and removes the listener in finally.

Estimated code review effort: 2 (Simple) | ~10 minutes

Sequence Diagram(s)

sequenceDiagram
  participant CloudFunction
  participant builtInTriggerValidator
  participant validateOptions

  CloudFunction->>builtInTriggerValidator: invoke with multiple invalid fields
  loop for each field in options.fields
    builtInTriggerValidator->>builtInTriggerValidator: collect [opt, key, val] into optionValidations
  end
  builtInTriggerValidator->>validateOptions: Promise.all(optionValidations.map(validateOptions))
  validateOptions-->>builtInTriggerValidator: rejection reasons
  builtInTriggerValidator-->>CloudFunction: reject with VALIDATION_ERROR (no unhandled rejection)
Loading
🚥 Pre-merge checks | ✅ 5 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description only says "Closes #8826" and omits the required Issue, Approach, and Tasks sections. Fill in the template sections for Issue, Approach, and Tasks, and note the test/documentation/security checklist status as applicable.
Engage In Review Feedback ❓ Inconclusive Repo diff shows the fix and tests, but no review-thread history is available to verify discussion before resolving feedback. Provide the PR review comments or discussion history showing feedback was discussed and either implemented in a commit or retracted by the reviewer.
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title starts with the required "fix:" prefix and accurately describes the server crash fix.
Linked Issues check ✅ Passed The changes address #8826 by preventing unhandled rejections in multi-field validation failures and adding a regression test.
Out of Scope Changes check ✅ Passed The diff stays focused on the reported validation crash and its regression test with no unrelated code changes.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Security Check ✅ Passed Patch only changes validation scheduling and adds a regression test; no new auth, injection, or sensitive-data paths, and it reduces an unhandled-rejection crash risk.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

🔧 Biome (2.5.1)
src/triggers.js

File contains syntax errors that prevent linting: Line 230: Type annotations are a TypeScript only feature. Convert your file to a TypeScript file or remove the syntax.; Line 230: Type annotations are a TypeScript only feature. Convert your file to a TypeScript file or remove the syntax.; Line 230: Type annotations are a TypeScript only feature. Convert your file to a TypeScript file or remove the syntax.; Line 230: return types can only be used in TypeScript files


Comment @coderabbitai help to get the list of available commands.

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

🧹 Nitpick comments (1)
src/triggers.js (1)

903-912: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Same latent pattern remains in the requireUserKeys branch.

This block still invokes validateOptions(...) immediately inside the loop before Promise.all, the same pattern that caused #8826 in the options.fields branch. It's not currently exploitable here since no other statement in this loop throws synchronously, but it's structurally fragile — any future addition of a synchronous check (e.g. a required validation) in this loop would reintroduce the same unhandled-rejection risk. Consider applying the same input-deferral pattern here for consistency.

♻️ Suggested consistency fix
   } else if (typeof userKeys === 'object') {
-    const optionPromises = [];
+    const optionValidations = [];
     for (const key in options.requireUserKeys) {
       const opt = options.requireUserKeys[key];
       if (opt.options) {
-        optionPromises.push(validateOptions(opt, key, reqUser.get(key)));
+        optionValidations.push([opt, key, reqUser.get(key)]);
       }
     }
-    await Promise.all(optionPromises);
+    await Promise.all(optionValidations.map(([o, k, v]) => validateOptions(o, k, v)));
   }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/triggers.js` around lines 903 - 912, The `requireUserKeys` branch in
`src/triggers.js` has the same eager-promise pattern as the earlier
`options.fields` fix: `validateOptions(...)` is being invoked directly inside
the loop before `Promise.all`, which can reintroduce unhandled-rejection risk if
a future synchronous check is added. Update the logic in this branch to defer
execution the same way as the `options.fields` path, collecting functions/thunks
(or equivalent deferred work) and only invoking `validateOptions` during the
`Promise.all` phase, keeping `userKeys` handling consistent and safe.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@src/triggers.js`:
- Around line 903-912: The `requireUserKeys` branch in `src/triggers.js` has the
same eager-promise pattern as the earlier `options.fields` fix:
`validateOptions(...)` is being invoked directly inside the loop before
`Promise.all`, which can reintroduce unhandled-rejection risk if a future
synchronous check is added. Update the logic in this branch to defer execution
the same way as the `options.fields` path, collecting functions/thunks (or
equivalent deferred work) and only invoking `validateOptions` during the
`Promise.all` phase, keeping `userKeys` handling consistent and safe.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 4d4e34ea-7b2f-4ebd-a9aa-6101770f1c21

📥 Commits

Reviewing files that changed from the base of the PR and between 7e9d53a and 6a047b4.

📒 Files selected for processing (2)
  • spec/CloudCode.Validator.spec.js
  • src/triggers.js

@dblythy dblythy requested review from a team and mtrezza July 4, 2026 16:33
@codecov

codecov Bot commented Jul 4, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 92.66%. Comparing base (cce91e5) to head (6a047b4).
⚠️ Report is 1 commits behind head on alpha.

Additional details and impacted files
@@           Coverage Diff           @@
##            alpha   #10540   +/-   ##
=======================================
  Coverage   92.66%   92.66%           
=======================================
  Files         193      193           
  Lines       16981    16981           
  Branches      248      248           
=======================================
  Hits        15736    15736           
  Misses       1224     1224           
  Partials       21       21           

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@Moumouls

Moumouls commented Jul 6, 2026

Copy link
Copy Markdown
Member

@coderabbitai what is the practical use case where the server crashed ?

@coderabbitai

coderabbitai Bot commented Jul 6, 2026

Copy link
Copy Markdown

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
fd triggers.js src
echo "---"
ast-grep run --pattern 'function builtInTriggerValidator($$$) { $$$ }' --lang js src/triggers.js | head -100

Length of output: 5201


@Moumouls Good question — let me walk through the exact mechanics of the crash.

In src/triggers.js, inside builtInTriggerValidator, when options.fields is a plain object (not an array), the code loops over each field key (around Line 819 onward). For each field:

  • If the field has opt.required set, it calls requiredParam(key) (Line 774-779), which throws synchronously (a plain string) if the value is missing.
  • If the field has opt.type/opt.options, it calls validateOptions(opt, key, val) (Line 781-807), which is an async function. Calling an async function immediately starts executing it and returns a Promise right away — even before anyone awaits it.

Before the fix, the code did:

optionPromises.push(validateOptions(opt, key, val)); // called immediately, inside the loop

and only after the entire for...in loop finished did it call await Promise.all(optionPromises).

Here's the crash scenario matching #8826: imagine a fields config like

fields: {
  type: { type: String, options: ['a', 'b'] }, // validated first
  project: { required: true }                   // validated second
}
  1. The loop first hits type. Since an invalid type value was sent, validateOptions() is invoked immediately — this creates a Promise that will eventually reject (because the value isn't in opts). This rejected promise is pushed into optionPromises, but nothing has "handled" it yet.
  2. The loop then hits project. Since project is missing, requiredParam('project') throws synchronously, right there inside the for...in loop body.
  3. That synchronous throw immediately unwinds the loop — execution never reaches the await Promise.all(optionPromises) line.
  4. The type validation promise created in step 1 is now orphaned: it rejects on its own (asynchronously, on a later microtask tick) with no .catch() or Promise.all() ever attached to it.
  5. Node.js detects this as an unhandled promise rejection, which (depending on the Node version/flags, e.g., --unhandled-rejections=strict, or if there's no global handler) can crash the whole server process.

So the practical trigger is: a Cloud Code validator with a fields object containing more than one field where at least one fails via a synchronous throw (e.g., a missing required field) and another fails via the async validateOptions path (e.g., an invalid type/options value) in the same request. If both fail simultaneously, the async one's promise gets abandoned instead of aggregated, producing the unhandled rejection.

The fix defers invocation of validateOptions() — it now just collects [opt, key, val] tuples during the loop and only creates/awaits the promises together via Promise.all(optionValidations.map(...)) after the loop (and any synchronous throws) complete. This ensures no async validation promise is ever created without being immediately covered by Promise.all.

@Moumouls

Moumouls commented Jul 6, 2026

Copy link
Copy Markdown
Member

@coderabbitai does the test correctly cover the issue, with a try/catch system within the test any chance of a false positive test even in case of a crash ?

@coderabbitai

coderabbitai Bot commented Jul 6, 2026

Copy link
Copy Markdown

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
fd "CloudCode.Validator.spec.js" spec
echo "---"
rg -n "unhandled rejection when multiple fields" -A 40 spec/CloudCode.Validator.spec.js | head -80

Length of output: 1836


@Moumouls Good instinct to double-check this — let me be precise about what the test actually does, because "try/catch masking a crash" is a real anti-pattern I'd also be wary of, but that's not what's happening here.

There is no try/catch in this test — it's try/finally.

try {
  Parse.Cloud.define('hello', () => 'Hello world!', {
    fields: {
      type: { type: String, options: ['Option A', 'Option B'] },
      project: { required: true },
    },
  });
  await expectAsync(Parse.Cloud.run('hello', { type: 'Invalid' })).toBeRejectedWith(
    jasmine.objectContaining({ code: Parse.Error.VALIDATION_ERROR })
  );
  await new Promise(resolve => setTimeout(resolve, 100));
  expect(rejections).toEqual([]);
} finally {
  process.removeListener('unhandledRejection', onUnhandledRejection);
}

The finally block only detaches the process.on('unhandledRejection', ...) listener for cleanup — it does not catch or swallow any thrown error. If expectAsync(...).toBeRejectedWith(...) fails, or if expect(rejections).toEqual([]) fails, that assertion error propagates normally and Jasmine will mark the test as failed. So there's no risk of the test silently passing due to an exception being swallowed.

Why the unhandledRejection listener approach is actually the correct way to catch this, not a source of false positives:

Node.js only terminates the process on an unhandled rejection when there are zero listeners registered for the 'unhandledRejection' event at the time it fires. By registering onUnhandledRejection before triggering the bug, the test:

  1. Prevents the crash from actually taking down the whole test process (which would otherwise abort the suite non-deterministically).
  2. Captures the rejection reason into the rejections array instead.
  3. Asserts rejections is empty afterward.

So if the pre-fix code path in src/triggers.js were still in place — where validateOptions('type', ...) creates a promise before the synchronous requiredParam('project') throw aborts the loop — the orphaned rejection from type validation would land in rejections, and expect(rejections).toEqual([]) would correctly fail. This is a standard and reliable pattern for testing "does this code path produce an unhandled rejection" without letting it actually crash your test runner.

Field ordering also matches the exact repro from #8826: type (async validateOptions path) is declared before project (sync requiredParam throw), so the loop hits the async path first, then throws synchronously on project — exactly the sequence needed to orphan the first promise before the fix.

One caveat worth noting: the setTimeout(resolve, 100) delay is a timing heuristic to give the orphaned rejection's microtask a chance to surface as an unhandledRejection event (Node needs at least one macrotask tick to fire the event) before the assertion runs. 100ms is generous and should be reliable in CI, but it is technically a heuristic rather than a deterministic guarantee. If you want to eliminate that heuristic entirely, an alternative is to use setImmediate/process.nextTick chaining instead of a fixed timeout, but in practice 100ms is a safe margin and shouldn't cause flakiness.

So to directly answer: yes, the test correctly reproduces and covers the crash scenario, and no, there's no try/catch masking a failure — a real crash-triggering regression would cause this test to fail, not silently pass.

Comment thread src/triggers.js
}
}
await Promise.all(optionPromises);
await Promise.all(optionValidations.map(([o, k, v]) => validateOptions(o, k, v)));

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@coderabbitai i'm not sure why it can help to fix the server crash, we should use a promise all settled here no ?

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail
gh pr diff 10540 --repo parse-community/parse-server -- src/triggers.js || true
echo "---full file at base---"
gh api repos/parse-community/parse-server/pulls/10540 --jq '.base.sha' > /tmp/base_sha.txt
cat /tmp/base_sha.txt
git fetch origin $(cat /tmp/base_sha.txt) --depth=1 2>&1 | tail -5 || true
git show $(cat /tmp/base_sha.txt):src/triggers.js | sed -n '780,900p' || true

Length of output: 11352


@Moumouls Good question — I dug into the base commit (7e9d53a08) to compare, and I can now explain precisely why this small reordering fixes the crash, and why Promise.allSettled wouldn't be the right tool here.

Root cause (confirmed from the pre-PR code):

const optionPromises = [];
for (const key in options.fields) {
  ...
  if (opt.type) {
    const type = getType(opt.type);
    const valType = Array.isArray(val) ? 'array' : typeof val;
    if (valType !== type) {
      throw `Validation failed. Invalid type for ${key}. Expected: ${type}`; // synchronous throw, not caught here
    }
  }
  if (opt.options) {
    optionPromises.push(validateOptions(opt, key, val)); // eagerly invoked -> live Promise created NOW
  }
}
await Promise.all(optionPromises); // never reached if a LATER field throws above

With multiple fields (e.g. project and type from the issue), the loop iterates over all fields in order:

  1. If an earlier field's opt.options check runs first, validateOptions(...) is called immediately, creating a live Promise that's pushed into optionPromises.
  2. If a later field's opt.type check then throws synchronously (a plain throw, no try/catch around it), the whole loop — and the containing async function — unwinds right there. Execution never reaches await Promise.all(optionPromises).
  3. The Promise created in step 1 is now orphaned: nothing ever attaches a .then/.catch to it. If/when it eventually settles as rejected (validateOptions does an await opts(val) for function-based options, so it can resolve/reject on a later microtask), Node's unhandled-rejection detection fires because no handler was ever attached — and depending on the Node version/flags, that terminates the process.

Why the fix works:

const optionValidations = [];
for (const key in options.fields) {
  ...
  if (opt.options) {
    optionValidations.push([opt, key, val]); // just data, no Promise created yet
  }
}
await Promise.all(optionValidations.map(([o, k, v]) => validateOptions(o, k, v)));

Now validateOptions is never invoked while the loop is running — we only store [opt, key, val] tuples. Promises are only constructed (via .map(...)) right before Promise.all(...), and only if the loop finished without an early synchronous throw. So if a later field's type check throws first, no dangling, unhandled Promise was ever created for the earlier field — there's nothing left "floating" to reject unhandled.

Why not Promise.allSettled:

  • allSettled wouldn't address the actual bug — the eager creation of the promise inside the loop is the problem, and that still happens whether you later reduce with all or allSettled.
  • Also, allSettled never rejects: it resolves with an array of {status, value/reason} results, so maybeRunValidator's .catch() would never trigger for these field validations. You'd need extra code to inspect the results array and manually throw on the first failure — otherwise a failed field validation would silently be treated as a pass, which is a real regression, not an equivalent fix.

So the targeted change here (defer promise construction until after the loop) is the correct, minimal fix — it removes the possibility of orphaned promises without changing validation semantics. Let me know if you'd like me to also double check the requireUserKeys block further down, which still uses the eager-push pattern (optionPromises.push(validateOptions(...))) — it has the same theoretical exposure, though there's no synchronous throw between iterations there today, so it isn't affected by the same #8826 crash scenario.


🧬 Code Graph Analysis Results

Relevant snippets for user comment (promise/all-settled)

1) src/triggers.js (promise parallelism in built-in validator)

  • Lines ~480-610 (function builtInTriggerValidator, includes Promise.all)
async function builtInTriggerValidator(options, request, auth) {
  if (request.master && !options.validateMasterKey) {
    return;
  }
  let reqUser = request.user;
  if (
    !reqUser &&
    request.object &&
    request.object.className === '_User' &&
    !request.object.existed()
  ) {
    reqUser = request.object;
  }
  ...
  const validateOptions = async (opt, key, val) => {
    let opts = opt.options;
    if (typeof opts === 'function') {
      try {
        const result = await opts(val);
        if (!result && result != null) {
          throw opt.error || `Validation failed. Invalid value for ${key}.`;
        }
      } catch (e) {
        if (!e) {
          throw opt.error || `Validation failed. Invalid value for ${key}.`;
        }

        throw opt.error || e.message || e;
      }
      return;
    }
    ...
  };
  ...
  if (Array.isArray(options.fields)) {
    for (const key of options.fields) {
      requiredParam(key);
    }
  } else {
    const optionValidations = [];
    for (const key in options.fields) {
      ...
      if (opt.options) {
        optionValidations.push([opt, key, val]);
      }
    }
    await Promise.all(optionValidations.map(([o, k, v]) => validateOptions(o, k, v)));
  }
  let userRoles = options.requireAnyUserRoles;
  let requireAllRoles = options.requireAllUserRoles;
  const promises = [Promise.resolve(), Promise.resolve(), Promise.resolve()];
  if (userRoles || requireAllRoles) {
    promises[0] = auth.getUserRoles();
  }
  if (typeof userRoles === 'function') {
    promises[1] = userRoles();
  }
  if (typeof requireAllRoles === 'function') {
    promises[2] = requireAllRoles();
  }
  const [roles, resolvedUserRoles, resolvedRequireAll] = await Promise.all(promises);
  ...
  if (userRoles) {
    const hasRole = userRoles.some(requiredRole => roles.includes(`role:${requiredRole}`));
    if (!hasRole) {
      throw `Validation failed. User does not match the required roles.`;
    }
  }
  if (requireAllRoles) {
    for (const requiredRole of requireAllRoles) {
      if (!roles.includes(`role:${requiredRole}`)) {
        throw `Validation failed. User does not match all the required roles.`;
      }
    }
  }
  ...
}

2) src/triggers.js (validator wrapper; how rejections propagate)

  • Lines ~420-480 (function maybeRunValidator, includes .catch behavior)
export function maybeRunValidator(request, functionName, auth) {
  const theValidator = getValidator(functionName, Parse.applicationId);
  if (!theValidator) {
    return;
  }
  if (typeof theValidator === 'object' && theValidator.skipWithMasterKey && request.master) {
    request.skipWithMasterKey = true;
  }
  return new Promise((resolve, reject) => {
    return Promise.resolve()
      .then(() => {
        return typeof theValidator === 'object'
          ? builtInTriggerValidator(theValidator, request, auth)
          : theValidator(request);
      })
      .then(() => {
        resolve();
      })
      .catch(e => {
        const error = resolveError(e, {
          code: Parse.Error.VALIDATION_ERROR,
          message: 'Validation failed.',
        });
        reject(error);
      });
  });
}

3) src/triggers.js (how trigger/after hooks are synchronized)

  • Lines ~610-735 (function maybeRunTrigger, comment about promise return from afterSave/afterDelete/afterLogin)
export function maybeRunTrigger(
  triggerType,
  auth,
  parseObject,
  originalParseObject,
  config,
  context
) {
  if (!parseObject) {
    return Promise.resolve({});
  }
  return new Promise(function (resolve, reject) {
    var trigger = getTrigger(parseObject.className, triggerType, config.applicationId);
    if (!trigger) { return resolve(); }
    var request = getRequestObject(
      triggerType,
      auth,
      parseObject,
      originalParseObject,
      config,
      context
    );
    var { success, error } = getResponseObject(
      request,
      object => {
        ...
        resolve(object);
      },
      error => {
        ...
        reject(error);
      }
    );

    // AfterSave and afterDelete triggers can return a promise, which if they
    // do, needs to be resolved before this promise is resolved,
    // so trigger execution is synced with RestWrite.execute() call.
    // If triggers do not return a promise, they can run async code parallel
    // to the RestWrite.execute() call.
    return Promise.resolve()
      .then(() => {
        return maybeRunValidator(request, `${triggerType}.${parseObject.className}`, auth);
      })
      .then(() => {
        if (request.skipWithMasterKey) {
          return Promise.resolve();
        }
        const promise = trigger(request);
        if (
          triggerType === Types.afterSave ||
          triggerType === Types.afterDelete ||
          triggerType === Types.afterLogin
        ) {
          logTriggerAfterHook(
            triggerType,
            parseObject.className,
            parseObject.toJSON(),
            auth,
            config.logLevels.triggerAfter
          );
        }
        // beforeSave is expected to return null (nothing)
        if (triggerType === Types.beforeSave) {
          if (promise && typeof promise.then === 'function') {
            return promise.then(response => {
              // response.object may come from express routing before hook
              if (response && response.object) {
                return response;
              }
              return null;
            });
          }
          return null;
        }

        return promise;
      })
      .then(success, error);
  });
}

4) src/Routers/FunctionsRouter.js (only tangentially related; Promise.all not present)

  • Lines 32-58:
function parseObject(obj, config) {
  if (Array.isArray(obj)) {
    return obj.map(item => {
      return parseObject(item, config);
    });
  } else if (obj && obj.__type == 'Date') {
    return Object.assign(new Date(obj.iso), obj);
  } else if (obj && obj.__type == 'File') {
    if (obj.url) {
      const { validateFileUrl } = require('../FileUrlValidator');
      validateFileUrl(obj.url, config);
    }
    return Parse.File.fromJSON(obj);
  } else if (obj && obj.__type == 'Pointer') {
    return Parse.Object.fromJSON({
      __type: 'Pointer',
      className: obj.className,
      objectId: obj.objectId,
    });
  } else if (Buffer.isBuffer(obj)) {
    return obj;
  } else if (obj && typeof obj === 'object') {
    return parseParams(obj, config);
  } else {
    return obj;
  }
}

🧠 Learnings used
Learnt from: mtrezza
Repo: parse-community/parse-server PR: 10117
File: benchmark/performance.js:713-737
Timestamp: 2026-03-06T21:30:03.253Z
Learning: In Parse Server LiveQuery, use liveQuery: { classNames: [...] } in the server config to specify which classes emit pub/sub events (server-side producers). Use ParseServer.createLiveQueryServer(httpServer, { appId, masterKey, serverURL }) to start the WebSocket server that forwards events to subscribed clients (event consumers); this function does not require a classNames parameter, as it simply matches incoming events against active client subscriptions.

Learnt from: mtrezza
Repo: parse-community/parse-server PR: 10117
File: benchmark/performance.js:52-52
Timestamp: 2026-03-06T21:30:10.326Z
Learning: In reviews of JavaScript files, ensure separation of concerns for LiveQuery in Parse Server: do not rely on the LiveQuery server to perform className filtering. The filtering and class event emission should occur in the ParseServer configuration (classNames within liveQuery) or related server logic, while ParseServer.createLiveQueryServer(httpServer, { appId, masterKey, serverURL }) should only establish the WebSocket-based delivery of already-filtered events. Treat classNames filtering as the responsibility of ParseServer, not the LiveQuery server, and verify that LiveQuery code receives pre-filtered events and does not duplicate filtering logic.

Learnt from: mtrezza
Repo: parse-community/parse-server PR: 10225
File: spec/Utils.spec.js:399-419
Timestamp: 2026-03-16T21:02:42.989Z
Learning: In the parse-community/parse-server repository, Biome is not used. Do not flag Biome lint issues (e.g., lint/suspicious/noThenProperty) or suggest biome-ignore comments in any JavaScript files. Treat Biome-related checks as exempt for all JS sources under this repo; if CI enforces Biome, ensure this guidance is reflected in CI configuration accordingly.

@mtrezza mtrezza left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Please resolve any open discussions

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.

Multiple Validation failures causes server crash

3 participants