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

[DTP-1024] GC tombstoned map entries for LiveMap and objects in the global pool #1937

Open
wants to merge 1 commit into
base: DTP-986/handle-tombstone-and-object-delete
Choose a base branch
from

Conversation

VeskeR
Copy link
Contributor

@VeskeR VeskeR commented Dec 11, 2024

Resolves DTP-1024

Summary by CodeRabbit

  • New Features

    • Introduced a new constant DEFAULTS for garbage collection settings.
    • Added methods for handling garbage collection in LiveCounter, LiveMap, LiveObject, and LiveObjectsPool.
    • Enhanced tracking of tombstoned entries with new properties and methods.
  • Bug Fixes

    • Improved management of tombstoned entries to ensure proper garbage collection.
  • Tests

    • Added scenarios to test garbage collection behavior for tombstoned objects and map entries.
  • Chores

    • Updated private API identifiers for better tracking.

Copy link

coderabbitai bot commented Dec 11, 2024

Walkthrough

The pull request introduces several changes across multiple files to enhance garbage collection functionality within the LiveObjects plugin. Key additions include a new DEFAULTS constant in defaults.ts to configure garbage collection intervals and grace periods. Several classes, including LiveCounter, LiveMap, LiveObject, and LiveObjectsPool, receive new methods and properties to manage tombstoned entries effectively. Additionally, tests are added to ensure proper functionality of the garbage collection logic, confirming that tombstoned objects are removed after the specified grace period.

Changes

File Path Change Summary
src/plugins/liveobjects/defaults.ts Added constant DEFAULTS with properties gcInterval (300,000 ms) and gcGracePeriod (150,000 ms).
src/plugins/liveobjects/livecounter.ts Added internal method onGCInterval() in LiveCounter class; no implementation provided.
src/plugins/liveobjects/livemap.ts Added property tombstonedAt in MapEntry interface; added onGCInterval() method in LiveMap class; modified methods to handle tombstoned entries.
src/plugins/liveobjects/liveobject.ts Added private property _tombstonedAt and public method tombstonedAt() in LiveObject class.
src/plugins/liveobjects/liveobjects.ts Added static property _DEFAULTS in LiveObjects class, assigned value from DEFAULTS.
src/plugins/liveobjects/liveobjectspool.ts Added private property _gcInterval and implemented _onGCInterval() method for garbage collection.
test/common/modules/private_api_recorder.js Updated privateAPIIdentifiers array with new entries related to garbage collection methods.
test/realtime/live_objects.test.js Added tests for garbage collection scenarios involving tombstoned objects and map entries.

Possibly related PRs

Suggested reviewers

  • mschristensen
  • owenpearson

🐇 In the land of code, where objects roam,
A grace period set, to call them home.
With tombstones in tow, they won't be alone,
Garbage collection, our new milestone!
Let the intervals dance, and logic unfold,
In the realm of LiveObjects, new stories are told! 🌟


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 generate docstrings to generate docstrings for this PR. (Experiment)
  • @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.

@github-actions github-actions bot temporarily deployed to staging/pull/1937/bundle-report December 11, 2024 07:49 Inactive
@github-actions github-actions bot temporarily deployed to staging/pull/1937/features December 11, 2024 07:49 Inactive
@github-actions github-actions bot temporarily deployed to staging/pull/1937/typedoc December 11, 2024 07:49 Inactive
@VeskeR VeskeR changed the base branch from integration/liveobjects to DTP-986/handle-tombstone-and-object-delete December 11, 2024 07:54
@VeskeR VeskeR force-pushed the DTP-986/handle-tombstone-and-object-delete branch from f370f62 to 4ff3647 Compare December 11, 2024 07:55
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: 2

🧹 Outside diff range and nitpick comments (2)
src/plugins/liveobjects/liveobject.ts (1)

190-190: Add documentation for the abstract method.

Please add JSDoc documentation for the onGCInterval() method to explain its purpose, when it's called, and what implementing classes should do.

src/plugins/liveobjects/liveobjects.ts (1)

30-31: Enhance the documentation comment.

The current comment "Used by tests" could be more descriptive. Consider adding more context about what aspects of the defaults are being tested, such as:

-// Used by tests
+// Exposed for testing garbage collection configuration
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 4ff3647 and 1a598e0.

📒 Files selected for processing (8)
  • src/plugins/liveobjects/defaults.ts (1 hunks)
  • src/plugins/liveobjects/livecounter.ts (1 hunks)
  • src/plugins/liveobjects/livemap.ts (6 hunks)
  • src/plugins/liveobjects/liveobject.ts (4 hunks)
  • src/plugins/liveobjects/liveobjects.ts (2 hunks)
  • src/plugins/liveobjects/liveobjectspool.ts (3 hunks)
  • test/common/modules/private_api_recorder.js (4 hunks)
  • test/realtime/live_objects.test.js (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • src/plugins/liveobjects/livecounter.ts
🔇 Additional comments (4)
src/plugins/liveobjects/liveobjectspool.ts (1)

22-26: Ensure compatibility of unref usage across environments

The use of this._gcInterval.unref?.(); effectively prevents the Node.js event loop from being blocked by the interval. Please verify that the optional chaining operator ?. and the unref method are compatible with all target environments, including browsers and older Node.js versions, as unref may not be available.

src/plugins/liveobjects/defaults.ts (1)

1-10: Definition of DEFAULTS constants is clear and appropriate

The introduction of the DEFAULTS constant with properly documented gcInterval and gcGracePeriod provides clarity and configurability for garbage collection timings.

src/plugins/liveobjects/liveobject.ts (1)

131-137: LGTM!

The tombstonedAt() getter method is well-implemented and correctly marked as internal.

test/common/modules/private_api_recorder.js (1)

19-21: LGTM!

The new private API identifiers are well-organized, follow the existing naming pattern, and correctly reflect the private APIs used for garbage collection functionality.

Also applies to: 78-78, 119-119, 136-137

Comment on lines +307 to +308
if (value.tombstone === true && Date.now() - value.tombstonedAt! >= DEFAULTS.gcGracePeriod) {
keysToDelete.push(key);
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Avoid using non-null assertions on tombstonedAt

In the onGCInterval method, the code uses value.tombstonedAt! with a non-null assertion. To prevent potential runtime errors if tombstonedAt is undefined, consider adding a null check to ensure safety.

Apply this diff to add a null check:

-if (value.tombstone === true && Date.now() - value.tombstonedAt! >= DEFAULTS.gcGracePeriod) {
+if (value.tombstone === true && value.tombstonedAt !== undefined && Date.now() - value.tombstonedAt >= DEFAULTS.gcGracePeriod) {
📝 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
if (value.tombstone === true && Date.now() - value.tombstonedAt! >= DEFAULTS.gcGracePeriod) {
keysToDelete.push(key);
if (value.tombstone === true && value.tombstonedAt !== undefined && Date.now() - value.tombstonedAt >= DEFAULTS.gcGracePeriod) {
keysToDelete.push(key);

Comment on lines +2686 to +2734
forScenarios(tombstonesGCScenarios, async function (helper, scenario) {
try {
helper.recordPrivateApi('write.LiveObjects._DEFAULTS.gcInterval');
LiveObjectsPlugin.LiveObjects._DEFAULTS.gcInterval = 500;
helper.recordPrivateApi('write.LiveObjects._DEFAULTS.gcGracePeriod');
LiveObjectsPlugin.LiveObjects._DEFAULTS.gcGracePeriod = 250;

const liveObjectsHelper = new LiveObjectsHelper(helper);
const client = RealtimeWithLiveObjects(helper);

await helper.monitorConnectionThenCloseAndFinish(async () => {
const channelName = scenario.description;
const channel = client.channels.get(channelName, channelOptionsWithLiveObjects());
const liveObjects = channel.liveObjects;

await channel.attach();
const root = await liveObjects.getRoot();

// helper function to spy on the GC interval callback and wait for a specific number of GC cycles.
// returns a promise which will resolve when required number of cycles have happened.
const waitForGCCycles = (cycles) => {
const onGCIntervalOriginal = liveObjects._liveObjectsPool._onGCInterval;
let gcCalledTimes = 0;
return new Promise((resolve) => {
helper.recordPrivateApi('replace.LiveObjects._liveObjectsPool._onGCInterval');
liveObjects._liveObjectsPool._onGCInterval = function () {
helper.recordPrivateApi('call.LiveObjects._liveObjectsPool._onGCInterval');
onGCIntervalOriginal.call(this);

gcCalledTimes++;
if (gcCalledTimes >= cycles) {
resolve();
liveObjects._liveObjectsPool._onGCInterval = onGCIntervalOriginal;
}
};
});
};

await scenario.action({
root,
liveObjectsHelper,
channelName,
channel,
liveObjects,
helper,
waitForGCCycles,
});
}, client);
} finally {
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Avoid accessing and modifying private properties and methods in tests

In the test code starting at line 2686, the private properties LiveObjectsPlugin.LiveObjects._DEFAULTS.gcInterval and LiveObjectsPlugin.LiveObjects._DEFAULTS.gcGracePeriod are being modified, and private methods like _onGCInterval are being overridden. Accessing private APIs directly can lead to fragile tests that are tightly coupled to internal implementations. Consider refactoring the code to use public APIs or introduce appropriate hooks or configuration options to facilitate testing without relying on private internals.

Copy link
Contributor

@mschristensen mschristensen left a comment

Choose a reason for hiding this comment

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

One small comment, otherwise looks good.

*
* Applies both for map entries tombstones and object tombstones.
*/
gcGracePeriod: 1000 * 60 * 2.5, // 2.5 minutes
Copy link
Contributor

Choose a reason for hiding this comment

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

I think this actually needs to be 24 hours, which is how long realtime will keep tombstones for

* Even though the `timeserial` from the operation that deleted the object contains the timestamp value,
* the `timeserial` should be treated as an opaque string on the client, meaning we should not attempt to parse it.
*
* Therefore, we need to set our own timestamp when the object is deleted client-side. Strictly speaking, this is
Copy link
Contributor

Choose a reason for hiding this comment

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

This does make an assumption about the client clock not being too heavily skewed behind the server.

I think we have two options for a proper fix:

  1. Use the /time endpoint to get a server timestamp instead of Date.now()
  2. Include the time component of the timeserial in the MAP_REMOVE operation so that the client has access to that value without parsing the timeserial

Given the grace period, the likelihood of encountering a race here is pretty low. So, I think we should create a ticket to do this properly but for now this is fine.

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

Successfully merging this pull request may close these issues.

2 participants