Skip to content
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

cleanup event handlers in looker2d #4988

Merged
merged 1 commit into from
Oct 30, 2024

Conversation

sashankaryal
Copy link
Contributor

@sashankaryal sashankaryal commented Oct 24, 2024

incomplete

Summary by CodeRabbit

  • New Features

    • Enhanced event listener management in the Modal component for improved resource cleanup.
    • Added abort functionality to asynchronous operations in various components, improving lifecycle management.
    • Improved error handling and logging for image loading processes.
  • Bug Fixes

    • Resolved potential memory leaks by ensuring proper removal of event listeners during component unmounting.
  • Documentation

    • Updated import statements and lifecycle management practices for better clarity on component behavior.

@sashankaryal sashankaryal self-assigned this Oct 24, 2024
Copy link
Contributor

coderabbitai bot commented Oct 24, 2024

Walkthrough

The pull request introduces several modifications across multiple components, primarily focusing on enhancing event listener management and resource cleanup. Key changes include the addition of AbortController instances in various classes to handle the cancellation of asynchronous operations and event listeners. The Modal component's cleanup process is refined, while the AbstractLooker and ImaVidFrameSamples classes have updated methods to improve control over their lifecycle events. These adjustments aim to prevent memory leaks and ensure proper management of event listeners throughout the application.

Changes

File Path Change Summary
app/packages/core/src/components/Modal/Modal.tsx Added event listener removal in modalCloseHandler for cleanup on modal close; removed cleanup effect on unmount.
app/packages/looker/src/lookers/abstract.ts Updated getLabelsWorker to accept abortController; added controller to manage resource cleanup in detach method.
app/packages/looker/src/lookers/imavid/ima-vid-frame-samples.ts Added abortController for managing async operations; improved error handling in image loading process.
app/packages/looker/src/util.ts Modified createWorker to include abortController for managing event listener lifecycle; structured error handling.
app/packages/state/src/hooks/useCreateLooker.ts Introduced useEffect for AbortController lifecycle management; updated event listener in create function.

Possibly related PRs

  • Video playback #4878: The changes in the main PR regarding event listener management in the Modal component are related to the enhancements made in the ImaVidLooker component, which also involves managing event listeners for video playback within the modal context.

Suggested reviewers

  • sashankaryal
  • imanjra
  • manivoxel51
  • lanzhenw

🐰 In the meadow where bunnies play,
Event listeners hop, then fade away.
With controllers to guide, we clean up the mess,
Ensuring our code is at its best!
So here’s to the changes, both clever and bright,
In our coding burrow, everything feels right! 🌼


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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

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.

@sashankaryal sashankaryal force-pushed the fix/event-handler-memory-leak branch from f5b9c94 to df695cc Compare October 28, 2024 18:29
@benjaminpkane benjaminpkane force-pushed the fix/event-handler-memory-leak branch from df695cc to de40602 Compare October 30, 2024 19:45
@benjaminpkane benjaminpkane changed the base branch from develop to release/v1.0.2 October 30, 2024 19:45
@benjaminpkane benjaminpkane marked this pull request as ready for review October 30, 2024 19:45
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: 7

🧹 Outside diff range and nitpick comments (2)
app/packages/state/src/hooks/useCreateLooker.ts (2)

72-77: Simplify the cleanup function.

The cleanup function has an unnecessary return statement that can be simplified.

  useEffect(() => {
    return () => {
-     // sending abort signal to clean up all event handlers
-     return abortControllerRef.current.abort();
+     // Clean up all event handlers
+     abortControllerRef.current.abort();
    };
  }, []);

Line range hint 81-290: Consider splitting the create function for better maintainability.

The create function handles multiple responsibilities including:

  • Determining the looker type
  • Configuring different looker types
  • Setting up event listeners

Consider splitting this into smaller, more focused functions for better maintainability and testing.

Some suggestions:

  1. Extract looker type determination into a separate function
  2. Create separate configuration factories for each looker type
  3. Consider using a builder pattern for looker configuration

Example structure:

const determineLookerType = (sample: Sample, urls: Urls) => {
  // Logic to determine looker type
};

const createLookerConfig = (type: LookerType, sample: Sample, options: Options) => {
  // Type-specific configuration logic
};

const create = useRecoilCallback(
  ({ snapshot }) =>
    (params) => {
      const lookerType = determineLookerType(params.sample, params.urls);
      const config = createLookerConfig(lookerType, params.sample, params);
      const looker = new lookerType(params.sample, config, options);
      setupEventListeners(looker);
      return looker;
    }
);
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 1f5eaa8 and de40602.

📒 Files selected for processing (5)
  • app/packages/core/src/components/Modal/Modal.tsx (1 hunks)
  • app/packages/looker/src/lookers/abstract.ts (5 hunks)
  • app/packages/looker/src/lookers/imavid/ima-vid-frame-samples.ts (3 hunks)
  • app/packages/looker/src/util.ts (3 hunks)
  • app/packages/state/src/hooks/useCreateLooker.ts (4 hunks)
🧰 Additional context used
📓 Path-based instructions (5)
app/packages/core/src/components/Modal/Modal.tsx (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

app/packages/looker/src/lookers/abstract.ts (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

app/packages/looker/src/lookers/imavid/ima-vid-frame-samples.ts (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

app/packages/looker/src/util.ts (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

app/packages/state/src/hooks/useCreateLooker.ts (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

🔇 Additional comments (9)
app/packages/looker/src/lookers/imavid/ima-vid-frame-samples.ts (3)

25-26: LGTM: Well-implemented AbortController addition

The addition of a private readonly AbortController is a good practice for managing the lifecycle of async operations and event listeners.

Also applies to: 29-29


71-92: Consider enhancing error handling and addressing TODO

While the error handling is improved, consider:

  1. Using a structured error logging approach
  2. Implementing proper error recovery beyond using a black image
  3. Adding error metrics/monitoring for this edge case

Would you like me to propose a more robust error handling implementation or help create an issue to track the TODO?


138-138: LGTM: Proper cleanup implementation

The addition of abortController.abort() ensures proper cleanup of pending operations during reset.

app/packages/core/src/components/Modal/Modal.tsx (1)

Line range hint 208-211: Verify event listener management.

The event listener is added in onLookerSet but there's no protection against multiple additions of the same listener.

Let's verify the event listener management pattern in other files:

✅ Verification successful

Event listener management is properly handled

After reviewing the codebase, the event listener management is implemented correctly in the Modal component. The code shows:

  1. The "close" event listener is added in a controlled way within the component:
looker.addEventListener("close", modalCloseHandler);
  1. The cleanup is properly handled with removeEventListener in the cleanup function:
activeLookerRef.current?.removeEventListener("close", modalCloseHandler);

This pattern is consistent with React's best practices for event listener management, and similar cleanup patterns are used throughout other modal-related components in the codebase. The concern about multiple additions of the same listener is unfounded as the code follows the standard React lifecycle pattern where listeners are properly cleaned up.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for similar event listener patterns in looker-related files
rg -A 5 "addEventListener.*close" app/packages/looker/

Length of output: 56


Script:

#!/bin/bash
# Let's search for event listener patterns in the Modal component and related files
rg -A 5 "addEventListener" app/packages/core/src/components/Modal/

# Also search for any cleanup or removal of event listeners
rg -A 5 "removeEventListener" app/packages/core/src/components/Modal/

# Let's also check the specific onLookerSet implementation
ast-grep --pattern 'function onLookerSet($$$) { $$$ }'

Length of output: 10722

app/packages/state/src/hooks/useCreateLooker.ts (1)

259-265: 🛠️ Refactor suggestion

Consider enhancing error context.

While the error handling is functional, consider adding more context about which looker instance failed.

  looker.addEventListener(
    "error",
    (event) => {
-     handleError(event.error);
+     handleError({
+       error: event.error,
+       context: {
+         sampleId: sample._id,
+         lookerType: looker.constructor.name
+       }
+     });
    },
    { signal: abortControllerRef.current.signal }
  );

Likely invalid or redundant comment.

app/packages/looker/src/util.ts (1)

460-479: LGTM! Improved error handling with proper cleanup

The error handling has been improved by:

  1. Using dedicated event listeners for both error and message events
  2. Properly integrating with AbortController for cleanup
  3. Maintaining consistent error handling logic
app/packages/looker/src/lookers/abstract.ts (3)

111-112: Appropriate use of AbortController for managing async operations

The addition of the abortController as a private readonly member and its initialization in the constructor is a correct approach for managing cancellation of asynchronous operations within the AbstractLooker instance.

Also applies to: 118-118


395-407: Integrating AbortController with event listeners correctly

Modifying addEventListener to include signal: this.abortController.signal ensures that event listeners are properly cleaned up when this.abortController.abort() is called. This aligns with best practices for managing event listeners in modern JavaScript and TypeScript applications.


511-511: Proper cleanup of resources in the detach method

Calling this.abortController.abort(); in the detach method effectively cancels any ongoing operations and removes associated event listeners, aiding in preventing memory leaks and ensuring that resources are properly released when the instance is detached.

Comment on lines +94 to +109
image.addEventListener(
"error",
() => {
console.error(
"Sample was removed from cache before image loaded",
sampleId
"Failed to load image for sample with id",
sampleId,
"at url",
source
);
image.src = BASE64_BLACK_IMAGE;
return;
}

sample.image = image;
resolve(sampleId);
});

image.addEventListener("error", () => {
console.error(
"Failed to load image for sample with id",
sampleId,
"at url",
source
);

// use a placeholder blank black image to not block animation
// setting src should trigger the load event
image.src = BASE64_BLACK_IMAGE;
});
// use a placeholder blank black image to not block animation
// setting src should trigger the load event
image.src = BASE64_BLACK_IMAGE;
},
{ signal: this.abortController.signal }
);
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider enhancing image loading error recovery

The current implementation could be improved by:

  1. Adding retry logic for transient failures
  2. Using structured logging with error categorization
  3. Adding telemetry for failed image loads

Here's a suggested improvement:

 image.addEventListener(
   "error",
   () => {
+    const error = {
+      type: 'IMAGE_LOAD_ERROR',
+      sampleId,
+      url: source,
+      timestamp: Date.now()
+    };
     console.error(
-      "Failed to load image for sample with id",
-      sampleId,
-      "at url",
-      source
+      'Image load failed:',
+      JSON.stringify(error)
     );
+    // todo: add retry logic here
     image.src = BASE64_BLACK_IMAGE;
   },
   { signal: this.abortController.signal }
 );

Committable suggestion was skipped due to low confidence.

Comment on lines +107 to +110
activeLookerRef.current?.removeEventListener(
"close",
modalCloseHandler
);
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

Add null check before removing event listener.

The event listener removal should include a null check to prevent potential runtime errors.

Apply this diff:

-        activeLookerRef.current?.removeEventListener(
-          "close",
-          modalCloseHandler
-        );
+        if (activeLookerRef.current) {
+          activeLookerRef.current.removeEventListener(
+            "close",
+            modalCloseHandler
+          );
+        }
📝 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
activeLookerRef.current?.removeEventListener(
"close",
modalCloseHandler
);
if (activeLookerRef.current) {
activeLookerRef.current.removeEventListener(
"close",
modalCloseHandler
);
}

⚠️ Potential issue

Potential memory leak: Add cleanup effect.

The event listener cleanup only occurs when the modal is manually closed. If the component is unmounted without closing (e.g., route change), the event listener will remain attached.

Add a cleanup effect to ensure the event listener is always removed:

+ useEffect(() => {
+   return () => {
+     if (activeLookerRef.current) {
+       activeLookerRef.current.removeEventListener("close", modalCloseHandler);
+     }
+   };
+ }, [modalCloseHandler]);

Committable suggestion was skipped due to low confidence.

Comment on lines +449 to +450
dispatchEvent?: DispatchEvent,
abortController?: AbortController
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

Add null check for abortController parameter

The abortController parameter is optional but used without null checks in the event listeners. This could lead to runtime errors if the function is called without providing an AbortController.

Add a null check at the beginning of the function:

 export const createWorker = (
   listeners?: {
     [key: string]: ((worker: Worker, args: any) => void)[];
   },
   dispatchEvent?: DispatchEvent,
   abortController?: AbortController
 ): Worker => {
+  if (!abortController) {
+    throw new Error('AbortController is required for proper event listener cleanup');
+  }
   let worker: Worker = null;

Committable suggestion was skipped due to low confidence.

Comment on lines +490 to +500
worker.addEventListener(
"message",
({ data: { method, ...args } }) => {
if (!(method in listeners)) {
return;
}

listeners[method].forEach((callback) => callback(worker, args));
});
listeners[method].forEach((callback) => callback(worker, args));
},
{ signal: abortController.signal }
);
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider improving type safety for message handling

While the message handling implementation is good, we could improve type safety by:

  1. Adding type definitions for the message data
  2. Adding runtime type checks for the message structure

Consider applying this improvement:

+interface WorkerMessage {
+  method: string;
+  [key: string]: any;
+}

 worker.addEventListener(
   "message",
-  ({ data: { method, ...args } }) => {
+  ({ data }: MessageEvent<WorkerMessage>) => {
+    const { method, ...args } = data;
+    if (typeof method !== 'string') {
+      console.warn('Received worker message with invalid method type');
+      return;
+    }
     if (!(method in listeners)) {
       return;
     }
     listeners[method].forEach((callback) => callback(worker, args));
   },
   { signal: abortController.signal }
 );
📝 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
worker.addEventListener(
"message",
({ data: { method, ...args } }) => {
if (!(method in listeners)) {
return;
}
listeners[method].forEach((callback) => callback(worker, args));
});
listeners[method].forEach((callback) => callback(worker, args));
},
{ signal: abortController.signal }
);
interface WorkerMessage {
method: string;
[key: string]: any;
}
worker.addEventListener(
"message",
({ data }: MessageEvent<WorkerMessage>) => {
const { method, ...args } = data;
if (typeof method !== 'string') {
console.warn('Received worker message with invalid method type');
return;
}
if (!(method in listeners)) {
return;
}
listeners[method].forEach((callback) => callback(worker, args));
},
{ signal: abortController.signal }
);

Comment on lines +63 to +73
return (dispatchEvent, abortController) => {
if (!workers) {
workers = [];
for (let i = 0; i < numWorkers; i++) {
workers.push(createWorker(LookerUtils.workerCallbacks, dispatchEvent));
workers.push(
createWorker(
LookerUtils.workerCallbacks,
dispatchEvent,
abortController
)
);
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

⚠️ Potential issue

Potential issue with shared AbortControllers in worker pool

The getLabelsWorker function uses a shared worker pool across all instances of AbstractLooker. Passing abortController to createWorker during worker initialization might lead to unintended behavior, as the abortController from one instance could affect workers used by other instances. This could result in aborting workers that are still in use elsewhere.

Consider modifying the worker management to ensure that each AbstractLooker instance does not interfere with others. One approach could be to instantiate separate workers for each instance or adjust the design so that the abortController is appropriately scoped and does not conflict across instances.

Comment on lines +697 to +699
const labelsWorker = getLabelsWorker(
(event, detail) => this.dispatchEvent(event, detail),
this.abortController
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

⚠️ Potential issue

Unintended side effects when aborting shared workers

When calling getLabelsWorker with this.abortController, the retrieved worker from the shared pool might have been initialized with a different AbortController. Calling this.abortController.abort() in one instance of AbstractLooker could inadvertently abort workers that are in use by other instances.

To prevent cross-instance interference, consider revising the worker pool implementation. Options include:

  • Assign unique workers to each AbstractLooker instance.
  • Implement a messaging protocol within workers to handle abort signals specific to each instance.
  • Avoid passing the instance-specific abortController when initializing shared workers.

Would you like assistance in refactoring the worker management to address this issue?

@benjaminpkane
Copy link
Contributor

Going to merge this. Will follow up with the rest of the 2d changes

@benjaminpkane benjaminpkane merged commit 8758186 into release/v1.0.2 Oct 30, 2024
10 of 11 checks passed
@benjaminpkane benjaminpkane deleted the fix/event-handler-memory-leak branch October 30, 2024 20:20
@coderabbitai coderabbitai bot mentioned this pull request Jan 15, 2025
7 tasks
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