Skip to content

feat: add sequential task queue to prevent parallel overload#2010

Open
AMIRKHANEF wants to merge 1 commit intoPolkaGate:mainfrom
AMIRKHANEF:queuedSharedWorker
Open

feat: add sequential task queue to prevent parallel overload#2010
AMIRKHANEF wants to merge 1 commit intoPolkaGate:mainfrom
AMIRKHANEF:queuedSharedWorker

Conversation

@AMIRKHANEF
Copy link
Member

@AMIRKHANEF AMIRKHANEF commented Nov 5, 2025

Description

This PR introduces a sequential task queue for the SharedWorker to avoid simultaneous network requests that cause performance bottlenecks.

Closes #2009

Summary by CodeRabbit

  • Bug Fixes

    • Fixed edge cases in asset fetching when certain conditions are not met.
  • Refactor

    • Improved sequential processing of background tasks for enhanced reliability.
    • Enhanced error handling and reporting system to provide clearer feedback on operation failures.
    • Optimized asset operation workflows for better consistency.

@AMIRKHANEF AMIRKHANEF requested a review from Nick-1979 November 5, 2025 12:05
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 5, 2025

Walkthrough

The SharedWorker message handler is refactored to process incoming requests sequentially through a new RequestQueue class instead of handling them in parallel. Error handling is enhanced with per-task try/catch blocks, and conditional logic for asset fetching is updated to handle undefined cases explicitly.

Changes

Cohort / File(s) Change Summary
Sequential Request Processing
packages/extension-polkagate/src/util/workers/sharedWorker.js
Introduces RequestQueue class for sequential task management; replaces parallel message handling with queue-based processing; refactors switch-case logic into queued async tasks; enhances per-task error handling with try/catch; updates MULTI_ASSET and ASSET_HUB handlers to check for undefined assetsToBeFetched; replaces .catch(console.error) chains with awaited calls in function handlers; generalizes error reporting to post functionName and error.message payloads.

Sequence Diagram

sequenceDiagram
    participant Client
    participant SW as SharedWorker
    participant Queue as RequestQueue
    participant Handler as Handler Functions
    
    rect rgb(240, 248, 255)
    Note over SW,Queue: Old: Parallel Processing
    Client->>SW: Message 1
    Client->>SW: Message 2
    SW->>Handler: Request 1 (async)
    SW->>Handler: Request 2 (async)
    Handler-->>SW: Response 1
    Handler-->>SW: Response 2
    end
    
    rect rgb(240, 255, 240)
    Note over SW,Queue: New: Sequential Queue Processing
    Client->>SW: Message 1
    SW->>Queue: add(async task 1)
    Client->>SW: Message 2
    SW->>Queue: add(async task 2)
    Queue->>Handler: Execute task 1
    Handler-->>Queue: Complete ✓
    Queue->>Handler: Execute task 2
    Handler-->>Queue: Complete ✓
    Queue-->>SW: Results
    SW-->>Client: Response 1
    SW-->>Client: Response 2
    end
Loading

Estimated Code Review Effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Areas requiring extra attention:
    • Verify RequestQueue implementation correctly handles concurrent subscriptions and task ordering
    • Validate error handling paths for each handler (MULTI_ASSET, ASSET_HUB, etc.) to ensure undefined asset conditions are properly handled and reported
    • Confirm that sequential processing doesn't introduce unexpected delays or deadlock scenarios
    • Review the transition from promise chains (.catch()) to async/await patterns for consistency and correctness

Poem

🐰 One queue to rule them all, no more rushing through the hall,
Tasks line up so neat and tidy, processed steady, not so flighty,
Sequential hops reduce the strain, better performance, crystal plain! 🌟

Pre-merge checks and finishing touches

✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title clearly summarizes the main change: introducing a sequential task queue to the SharedWorker to prevent parallel overload, which aligns with the core objective of the changeset.
Linked Issues check ✅ Passed The PR successfully implements all coding requirements from issue #2009: introduces a RequestQueue class, enqueues tasks sequentially, and ensures requests are processed one at a time rather than in parallel.
Out of Scope Changes check ✅ Passed All changes are within scope: the RequestQueue implementation, message handling refactoring, and error handling improvements directly address the sequential task queue objective from issue #2009.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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

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

@AMIRKHANEF AMIRKHANEF added enhancement New feature or request suggestion labels Nov 5, 2025
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: 1

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e38a1a7 and 11a32a3.

📒 Files selected for processing (1)
  • packages/extension-polkagate/src/util/workers/sharedWorker.js (3 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
packages/extension-polkagate/src/util/workers/sharedWorker.js (5)
packages/extension-polkagate/src/util/constants.ts (1)
  • FETCHING_ASSETS_FUNCTION_NAMES (337-341)
packages/extension-polkagate/src/util/workers/shared-helpers/getAssetOnRelayChain.js (1)
  • getAssetOnRelayChain (15-58)
packages/extension-polkagate/src/util/workers/shared-helpers/getAssetOnMultiAssetChain.js (1)
  • getAssetOnMultiAssetChain (21-110)
packages/extension-polkagate/src/util/workers/shared-helpers/getAssetOnAssetHub.js (1)
  • getAssetOnAssetHub (16-46)
packages/extension-polkagate/src/util/workers/shared-helpers/getValidatorsInformation.js (1)
  • getValidatorsInformation (62-156)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: Analyze (javascript)
  • GitHub Check: build

Comment on lines +86 to 99
case FETCHING_ASSETS_FUNCTION_NAMES.MULTI_ASSET: {
const assetsToBeFetched = assetsChains[parameters.chainName];

case FETCHING_ASSETS_FUNCTION_NAMES.ASSET_HUB: {
if (!parameters.assetsToBeFetched) {
console.warn('getAssetOnAssetHub: No assets to be fetched on, but just Native Token');
/** if assetsToBeFetched === undefined then we don't fetch assets by default at first, but will fetch them on-demand later in account details page*/
if (!assetsToBeFetched) {
console.info(`Shared worker, getAssetOnMultiAssetChain: No assets to be fetched on ${parameters.chainName}`);
port.postMessage(JSON.stringify({ functionName }));

parameters.assetsToBeFetched = [];
return;
}

await getAssetOnMultiAssetChain(assetsToBeFetched, ...params, port);
break;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

Fix the MULTI_ASSET argument order

params still contains parameters.assetsToBeFetched, so when you prepend the new assetsChains lookup and spread ...params, getAssetOnMultiAssetChain now receives the caller’s assetsToBeFetched array where it expects chainName. That turns into a runtime failure (getChainEndpoints gets an array instead of a string) and breaks the “maintain compatibility with existing message handling logic” requirement. Please destructure the fields you actually need and pass them explicitly to keep the signature aligned.

Apply this diff:

-          case FETCHING_ASSETS_FUNCTION_NAMES.MULTI_ASSET: {
-            const assetsToBeFetched = assetsChains[parameters.chainName];
+          case FETCHING_ASSETS_FUNCTION_NAMES.MULTI_ASSET: {
+            const { addresses, chainName, userAddedEndpoints } = parameters;
+            const assetsToBeFetched = assetsChains[chainName];
             /** if assetsToBeFetched === undefined then we don't fetch assets by default at first, but will fetch them on-demand later in account details page*/
             if (!assetsToBeFetched) {
-              console.info(`Shared worker, getAssetOnMultiAssetChain: No assets to be fetched on ${parameters.chainName}`);
+              console.info(`Shared worker, getAssetOnMultiAssetChain: No assets to be fetched on ${chainName}`);
               port.postMessage(JSON.stringify({ functionName }));
 
               return;
             }
 
-            await getAssetOnMultiAssetChain(assetsToBeFetched, ...params, port);
+            await getAssetOnMultiAssetChain(
+              assetsToBeFetched,
+              addresses,
+              chainName,
+              userAddedEndpoints,
+              port
+            );
             break;
           }
📝 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
case FETCHING_ASSETS_FUNCTION_NAMES.MULTI_ASSET: {
const assetsToBeFetched = assetsChains[parameters.chainName];
case FETCHING_ASSETS_FUNCTION_NAMES.ASSET_HUB: {
if (!parameters.assetsToBeFetched) {
console.warn('getAssetOnAssetHub: No assets to be fetched on, but just Native Token');
/** if assetsToBeFetched === undefined then we don't fetch assets by default at first, but will fetch them on-demand later in account details page*/
if (!assetsToBeFetched) {
console.info(`Shared worker, getAssetOnMultiAssetChain: No assets to be fetched on ${parameters.chainName}`);
port.postMessage(JSON.stringify({ functionName }));
parameters.assetsToBeFetched = [];
return;
}
await getAssetOnMultiAssetChain(assetsToBeFetched, ...params, port);
break;
}
case FETCHING_ASSETS_FUNCTION_NAMES.MULTI_ASSET: {
const { addresses, chainName, userAddedEndpoints } = parameters;
const assetsToBeFetched = assetsChains[chainName];
/** if assetsToBeFetched === undefined then we don't fetch assets by default at first, but will fetch them on-demand later in account details page*/
if (!assetsToBeFetched) {
console.info(`Shared worker, getAssetOnMultiAssetChain: No assets to be fetched on ${chainName}`);
port.postMessage(JSON.stringify({ functionName }));
return;
}
await getAssetOnMultiAssetChain(
assetsToBeFetched,
addresses,
chainName,
userAddedEndpoints,
port
);
break;
}
🤖 Prompt for AI Agents
In packages/extension-polkagate/src/util/workers/sharedWorker.js around lines 86
to 99, the call to getAssetOnMultiAssetChain spreads params which still contains
the original assetsToBeFetched, causing the function to receive arguments in the
wrong order (chainName vs assets array). Destructure the incoming message to
extract exactly the required fields (e.g., chainName and any other params like
accountId or asset identifiers), replace the spread ...params with explicit
arguments so you call getAssetOnMultiAssetChain(chainName, assetsToBeFetched, /*
other explicit args in correct order */, port), and remove or update any
redundant parameters to preserve the original function signature and avoid
passing the caller’s assets array as the chainName.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request suggestion

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Optimize SharedWorker with sequential task queue to reduce parallel connection overhead

1 participant