Skip to content

feat: Allow option publicServerURL to be set dynamically as async function #9803

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

dblythy
Copy link
Member

@dblythy dblythy commented Jun 22, 2025

Pull Request

Issue

Closes: #9798

Approach

Adds mechanism to load publicServerUrl on handleParseSession

Tasks

  • Add tests

Summary by CodeRabbit

  • New Features

    • Added support for configuring the server URL using a function or an asynchronous operation, in addition to a direct string value.
  • Bug Fixes

    • Ensured that dynamic or asynchronous server URL values are correctly loaded and applied during request processing.
  • Tests

    • Added a test to verify that the server URL configuration works when provided as a function returning a URL.

Copy link

parse-github-assistant bot commented Jun 22, 2025

🚀 Thanks for opening this pull request!

Copy link

coderabbitai bot commented Jun 22, 2025

📝 Walkthrough

"""

Walkthrough

Support for dynamic and asynchronous configuration of the publicServerURL option is introduced. The server now accepts publicServerURL as a string, a synchronous function, or an async function (returning a string or a Promise). Middleware and configuration logic are updated to resolve such functions at runtime, and tests and type definitions are updated accordingly.

Changes

File(s) Change Summary
src/Config.js Added support for async publicServerURL via new methods; updated validation; minor whitespace cleanup.
src/middlewares.js Middleware now awaits config.loadKeys() to ensure async config keys are resolved before request handling.
types/Options/index.d.ts Expanded publicServerURL type to accept string, function, or Promise.
spec/index.spec.js Added test to verify loading of publicServerURL when provided as a function.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Middleware
    participant Config

    Client->>Middleware: Incoming request
    Middleware->>Config: get(appId)
    Middleware->>Config: await config.loadKeys()
    Config->>Config: Resolve async keys (e.g., publicServerURL)
    Config-->>Middleware: Config with resolved keys
    Middleware->>Middleware: Attach config to request
    Middleware-->>Client: Continue request handling
Loading

Assessment against linked issues

Objective Addressed Explanation
Allow option publicServerURL to be set as an async function (#9798)
Accept publicServerURL as a function or Promise (#9798)
Update type definitions for async/sync function (#9798)
Test dynamic/async publicServerURL configuration (#9798)

Assessment against linked issues: Out-of-scope changes

No out-of-scope changes were found.
"""

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: 'parse@6.1.1',
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-22T12_14_46_484Z-debug-0.log


📜 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 8d4528e and 3f4e350.

📒 Files selected for processing (1)
  • src/Config.js (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/Config.js
⏰ Context from checks skipped due to timeout of 90000ms (12)
  • GitHub Check: PostgreSQL 17, PostGIS 3.5
  • GitHub Check: PostgreSQL 15, PostGIS 3.5
  • GitHub Check: PostgreSQL 15, PostGIS 3.3
  • GitHub Check: Node 20
  • GitHub Check: PostgreSQL 15, PostGIS 3.4
  • GitHub Check: Redis Cache
  • GitHub Check: PostgreSQL 16, PostGIS 3.5
  • GitHub Check: MongoDB 8, ReplicaSet
  • GitHub Check: Node 18
  • GitHub Check: MongoDB 7, ReplicaSet
  • GitHub Check: MongoDB 6, ReplicaSet
  • GitHub Check: Docker Build

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 22, 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: 4

🧹 Nitpick comments (3)
src/middlewares.js (1)

216-216: Consider performance implications of loading keys on every request.

The await config.loadKeys() call adds async overhead to every request. While the placement is correct (after config retrieval, before usage), consider implementing caching or memoization to avoid repeatedly resolving the same functions on subsequent requests.

Consider adding a cache invalidation strategy or TTL mechanism to avoid unnecessary function calls:

+  // Only load keys if they haven't been loaded or if cache is expired
+  if (!config._keysLoaded || (config._keysLoadedAt && Date.now() - config._keysLoadedAt > config.keysCacheTtl)) {
     await config.loadKeys();
+  }
src/Config.js (2)

35-35: Define asyncKeys as a constant to avoid duplication.

The asyncKeys array is defined here and again in the loadKeys() method (line 61). This duplication could lead to inconsistencies.

Use the constant defined at the top:

  async loadKeys() {
-    const asyncKeys = ['publicServerURL'];
-
     await Promise.all(
       asyncKeys.map(async key => {

74-81: Consider edge cases in transformConfiguration.

The method correctly moves function values to underscored properties, but should validate that the transformation is safe.

Add validation to ensure the transformation doesn't overwrite existing underscored properties:

  static transformConfiguration(serverConfiguration) {
     for (const key of Object.keys(serverConfiguration)) {
       if (asyncKeys.includes(key) && typeof serverConfiguration[key] === 'function') {
+        if (serverConfiguration[`_${key}`]) {
+          throw new Error(`Configuration conflict: both ${key} and _${key} are defined`);
+        }
         serverConfiguration[`_${key}`] = serverConfiguration[key];
         delete serverConfiguration[key];
       }
     }
   }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d14a723 and 8d4528e.

📒 Files selected for processing (4)
  • spec/index.spec.js (1 hunks)
  • src/Config.js (3 hunks)
  • src/middlewares.js (1 hunks)
  • types/Options/index.d.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (12)
  • GitHub Check: Redis Cache
  • GitHub Check: Node 18
  • GitHub Check: MongoDB 6, ReplicaSet
  • GitHub Check: Node 20
  • GitHub Check: MongoDB 8, ReplicaSet
  • GitHub Check: Docker Build
  • GitHub Check: PostgreSQL 16, PostGIS 3.5
  • GitHub Check: MongoDB 7, ReplicaSet
  • GitHub Check: PostgreSQL 15, PostGIS 3.5
  • GitHub Check: PostgreSQL 15, PostGIS 3.4
  • GitHub Check: PostgreSQL 17, PostGIS 3.5
  • GitHub Check: PostgreSQL 15, PostGIS 3.3
🔇 Additional comments (1)
src/Config.js (1)

477-477: ```bash
#!/bin/bash

Search for any loadKeys references across the repository to determine when publicServerURL is resolved

rg -n "loadKeys" -C5 .


</details>

</blockquote></details>

</details>

<!-- This is an auto-generated comment by CodeRabbit for review status -->

Comment on lines +618 to +627
it('should load publicServerURL', async () => {
await reconfigureServer({
publicServerURL: () => 'https://myserver.com/1',
});

await new Parse.Object('TestObject').save();

const config = Config.get(Parse.applicationId);
expect(config.publicServerURL).toEqual('https://myserver.com/1');
});
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Expand test coverage for complete functionality.

The test only covers the function case but the type definition also allows Promise<string>. Consider adding test coverage for:

  1. Promise-based publicServerURL
  2. Error handling scenarios (function throws, invalid URL returned)

Add comprehensive test coverage:

it('should load publicServerURL from Promise', async () => {
  await reconfigureServer({
    publicServerURL: Promise.resolve('https://myserver.com/2'),
  });

  await new Parse.Object('TestObject').save();

  const config = Config.get(Parse.applicationId);
  expect(config.publicServerURL).toEqual('https://myserver.com/2');
});

it('should handle publicServerURL function errors', async () => {
  await expectAsync(reconfigureServer({
    publicServerURL: () => { throw new Error('Function failed'); },
  })).toBeRejected();
});
🤖 Prompt for AI Agents
In spec/index.spec.js around lines 618 to 627, the test only covers the case
where publicServerURL is a function returning a string, but it also supports a
Promise<string> and error scenarios. Add tests to cover when publicServerURL is
a Promise resolving to a URL string and when the function throws an error,
verifying that reconfigureServer rejects appropriately. This will ensure full
coverage of the publicServerURL option's behavior.

@mtrezza mtrezza changed the title feature: add dynamic publicServerUrl feat: Add dynamic publicServerUrl Jun 22, 2025
@mtrezza mtrezza changed the title feat: Add dynamic publicServerUrl feat: Allow option publicServerURL to be set dynamically as async function Jun 22, 2025
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.

Allow option publicServerURL to be set dynamically as async function
2 participants