-
Notifications
You must be signed in to change notification settings - Fork 56
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
PresenceMap: only emit a leave if a member was present #1918
Conversation
Caution Review failedThe pull request is closed. WalkthroughThe changes in this pull request involve modifications to several files to enhance the management of client presence in a real-time application. The Changes
Possibly related PRs
Suggested reviewers
Poem
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? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
41f01ed
to
c28f836
Compare
There was a problem hiding this 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
🧹 Outside diff range and nitpick comments (8)
.mocharc.js (1)
12-12
: LGTM! Consider updating the comment to document the test directories.The addition of the unit test pattern is correct and aligns with the new PresenceMap implementation. Consider updating the comment above to document all test directories for better maintainability.
// mocha has a ridiculous issue (https://github.com/mochajs/mocha/issues/4100) that command line // specs don't override config specs; they are merged instead, so you can't run a single test file -// if you've defined specs in your config. therefore we work around it by only adding specs to the -// config if none are passed as arguments +// if you've defined specs in your config. Therefore we work around it by only adding specs to the +// config if none are passed as arguments. The specs include: +// - test/realtime/*.test.js: Realtime-related tests +// - test/rest/*.test.js: REST-related tests +// - test/unit/*.test.js: Unit tests for individual componentstest/unit/presencemap.test.js (3)
1-6
: Remove redundant 'use strict' directiveThe 'use strict' directive is redundant in JavaScript modules as they are automatically in strict mode.
-'use strict'; define(['chai', 'ably'], function (chai, Ably) {
🧰 Tools
🪛 Biome
[error] 1-1: Redundant use strict directive.
The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.(lint/suspicious/noRedundantUseStrict)
10-16
: Add input validation and documentation to helper functionThe helper function could benefit from input validation and JSDoc documentation for better maintainability.
- // Helper function to create a presence message - const createPresenceMessage = (clientId, connectionId, action, timestamp) => ({ + /** + * Creates a presence message object for testing + * @param {string} clientId - The client identifier + * @param {string} connectionId - The connection identifier + * @param {string} action - The presence action (present/leave) + * @param {number} timestamp - The message timestamp + * @returns {Object} The presence message object + */ + const createPresenceMessage = (clientId, connectionId, action, timestamp) => { + if (!clientId || !connectionId || !action || timestamp == null) { + throw new Error('All parameters are required'); + } + return { clientId, connectionId, timestamp, action, - }); + }; + };
27-46
: Consider adding more test cases for comprehensive coverageWhile the current tests cover the basic scenarios, consider adding tests for:
- Multiple presence entries for the same client
- Edge cases with identical timestamps
- Different presence actions (enter, update)
- Boundary conditions for timestamps
Example test case:
it('should handle multiple presence entries for same client', () => { const present1 = createPresenceMessage('client1', 'conn1', 'present', 100); const present2 = createPresenceMessage('client1', 'conn2', 'present', 150); presenceMap.put(present1); presenceMap.put(present2); const leave1 = createPresenceMessage('client1', 'conn1', 'leave', 200); assert.isTrue(presenceMap.remove(leave1)); assert.isTrue(presenceMap.has('client1:conn2')); });src/common/lib/client/presencemap.ts (4)
67-68
: Use Optional Chaining for Safer Property AccessYou can simplify property access and prevent potential null reference errors by using optional chaining when accessing
params.clientId
andparams.connectionId
.Apply this diff to improve the code:
const map = this.map, - clientId = params && params.clientId, - connectionId = params && params.connectionId, + clientId = params?.clientId, + connectionId = params?.connectionId, result = [];🧰 Tools
🪛 Biome
[error] 67-67: Change to an optional chain.
Unsafe fix: Change to an optional chain.
(lint/complexity/useOptionalChain)
[error] 68-68: Change to an optional chain.
Unsafe fix: Change to an optional chain.
(lint/complexity/useOptionalChain)
60-60
: Use Strict Equality Operators to Avoid Type CoercionUsing strict equality (
===
and!==
) instead of abstract equality (==
and!=
) prevents unexpected type coercion, leading to safer comparisons.Apply this diff to enhance code safety:
/* Line 60 */ - if (item.clientId == clientId && item.action != 'absent') result.push(item); + if (item.clientId === clientId && item.action !== 'absent') result.push(item); /* Lines 74-75 */ - if (clientId && clientId != item.clientId) continue; - if (connectionId && connectionId != item.connectionId) continue; + if (clientId && clientId !== item.clientId) continue; + if (connectionId && connectionId !== item.connectionId) continue; /* Line 105 */ - if (item.action != 'absent') result.push(item); + if (item.action !== 'absent') result.push(item);Also applies to: 74-75, 105-105
44-44
: Consider UsingMap
for Enhanced PerformanceUsing a
Map
object instead of a plain object forthis.map
can improve performance, especially when dealing with a large number of members.Map
provides better optimization for frequent additions and deletions.Apply this diff to update the implementation:
- this.map = Object.create(null); + this.map = new Map<string, PresenceMessage>();You'll also need to update the methods to accommodate the
Map
API, for example, usingthis.map.get(key)
instead ofthis.map[key]
.
115-117
: Avoid Returningfalse
When No Action is NeededIn the
remove
method, returningfalse
when no action is taken might be misleading. Consider returningvoid
or a more descriptive result to indicate that no modification was necessary.Adjust the return statement:
- return false; + return;And update the method signature if needed.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (5)
.mocharc.js
(1 hunks)src/common/lib/client/defaultrealtime.ts
(2 hunks)src/common/lib/client/presencemap.ts
(1 hunks)src/common/lib/client/realtimepresence.ts
(1 hunks)test/unit/presencemap.test.js
(1 hunks)
🧰 Additional context used
🪛 Biome
src/common/lib/client/presencemap.ts
[error] 67-67: Change to an optional chain.
Unsafe fix: Change to an optional chain.
(lint/complexity/useOptionalChain)
[error] 68-68: Change to an optional chain.
Unsafe fix: Change to an optional chain.
(lint/complexity/useOptionalChain)
test/unit/presencemap.test.js
[error] 1-1: Redundant use strict directive.
The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.
(lint/suspicious/noRedundantUseStrict)
🔇 Additional comments (4)
test/unit/presencemap.test.js (1)
18-25
: LGTM! Well-structured test initialization
The test setup is well-designed with:
- Proper beforeEach hook
- Correct member key function combining clientId and connectionId
- Appropriate timestamp-based comparison function
src/common/lib/client/defaultrealtime.ts (2)
14-14
: LGTM! Clean import statement
The import is properly grouped with other presence-related imports and follows the established conventions.
73-73
: Verify test usage of _PresenceMap
The static property follows the established pattern for test-related properties. Let's verify its usage in tests.
✅ Verification successful
Static _PresenceMap property is used in tests as expected
The verification confirms that:
- The
_PresenceMap
static property is used in tests viaAbly.Realtime._PresenceMap
- It follows the established pattern for test access as seen in
test/unit/presencemap.test.js
- The property provides test access to the internal
PresenceMap
class which is imported indefaultrealtime.ts
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Verify the usage of _PresenceMap in test files
# Expected: Find references to DefaultRealtime._PresenceMap in test files
# Search for test files using _PresenceMap
rg "DefaultRealtime\._PresenceMap" -t js -t ts
Length of output: 48
Script:
#!/bin/bash
# Let's try a broader search to understand the usage pattern
# First, find all test files that mention DefaultRealtime
rg "DefaultRealtime" --type ts --type js -l | grep -i "test"
# Also search for any usage of _PresenceMap in test files
rg "_PresenceMap" --type ts --type js | grep -i "test"
# Let's also check the actual implementation to understand the context
rg "class DefaultRealtime" -A 5 -B 5
Length of output: 1473
Script:
#!/bin/bash
# Let's check the presencemap.test.js file content to understand the test usage
cat test/unit/presencemap.test.js
# Also check the PresenceMap import in DefaultRealtime
rg "import.*PresenceMap" src/common/lib/client/defaultrealtime.ts -A 2 -B 2
Length of output: 1995
src/common/lib/client/realtimepresence.ts (1)
16-16
: Integration of PresenceMap
and RealtimePresenceParams
The addition of this import statement correctly integrates the PresenceMap
and RealtimePresenceParams
classes from './presencemap'
, which aligns with the proposed enhancements to the presence management system.
c28f836
to
90ef5bc
Compare
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🧹 Outside diff range and nitpick comments (4)
test/unit/presencemap.test.js (2)
1-1
: Remove redundant 'use strict' directiveThe 'use strict' directive is redundant in modules as they are automatically in strict mode.
-'use strict';
🧰 Tools
🪛 Biome
[error] 1-1: Redundant use strict directive.
The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.(lint/suspicious/noRedundantUseStrict)
29-48
: Enhance test coverage for leave eventsWhile the current tests verify basic removal behavior, consider adding these test cases to better align with the PR objective of "only emit leave if member was present":
Multiple members scenario:
- Add multiple members
- Remove one member
- Verify others remain unchanged
Double leave scenario:
- Add a member
- Remove the member
- Attempt to remove again
- Verify second remove returns false
Timestamp edge cases:
- Test removal with equal timestamps
Would you like me to help generate these additional test cases?
test/realtime/presence.test.js (1)
571-584
: Great refactoring to async/await pattern!The refactoring improves code readability and maintainability by:
- Using modern async/await syntax instead of callbacks
- Using Promise.all for concurrent operations
- Properly handling cleanup by closing the client
Consider adding an assertion to verify the presence state after leave:
await Promise.all([clientChannel.presence.leave(), clientChannel.presence.subscriptions.once('leave')]); +const members = await clientChannel.presence.get(); +expect(members.length).to.equal(0, 'Presence set should be empty after leave'); clientRealtime.close();src/common/lib/client/presencemap.ts (1)
67-68
: Simplify property access using optional chainingYou can enhance code readability by using optional chaining when accessing
clientId
andconnectionId
fromparams
.Apply this diff to simplify the code:
- clientId = params && params.clientId, - connectionId = params && params.connectionId, + clientId = params?.clientId, + connectionId = params?.connectionId,🧰 Tools
🪛 Biome
[error] 67-67: Change to an optional chain.
Unsafe fix: Change to an optional chain.
(lint/complexity/useOptionalChain)
[error] 68-68: Change to an optional chain.
Unsafe fix: Change to an optional chain.
(lint/complexity/useOptionalChain)
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (4)
.mocharc.js
(1 hunks)src/common/lib/client/presencemap.ts
(1 hunks)test/realtime/presence.test.js
(1 hunks)test/unit/presencemap.test.js
(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- .mocharc.js
🧰 Additional context used
🪛 Biome
src/common/lib/client/presencemap.ts
[error] 67-67: Change to an optional chain.
Unsafe fix: Change to an optional chain.
(lint/complexity/useOptionalChain)
[error] 68-68: Change to an optional chain.
Unsafe fix: Change to an optional chain.
(lint/complexity/useOptionalChain)
test/unit/presencemap.test.js
[error] 1-1: Redundant use strict directive.
The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.
(lint/suspicious/noRedundantUseStrict)
🔇 Additional comments (2)
test/unit/presencemap.test.js (2)
13-27
: LGTM! Well-structured test setup
The test setup is comprehensive with:
- Clear helper function for creating presence messages
- Proper memberKey function combining clientId and connectionId
- Correct timestamp-based comparison function
5-5
: Verify the use of internal _PresenceMap API
The code is accessing Ably.Realtime._PresenceMap
which appears to be an internal API (prefixed with underscore). This could be risky if the internal API changes.
90ef5bc
to
3cb1699
Compare
per ably/specification#222
Summary by CodeRabbit
Release Notes
New Features
PresenceMap
class for managing client presence in real-time applications.DefaultRealtime
class with access toPresenceMap
.Bug Fixes
Tests
PresenceMap
class, validating the functionality of theremove()
method.