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

feat: V3 Search #1261

Merged
merged 3 commits into from
Nov 27, 2024
Merged

feat: V3 Search #1261

merged 3 commits into from
Nov 27, 2024

Conversation

alexrisch
Copy link
Collaborator

@alexrisch alexrisch commented Nov 26, 2024

Added search for V3 Only

Added tests
Updated Snapshots

Closes #1262
Closes #222

Summary by CodeRabbit

  • New Features

    • Enhanced search functionality for Direct Messages (DMs) and groups based on user-defined queries.
    • Introduced filtering mechanism in the Conversation List to improve search results based on conversation type.
  • Bug Fixes

    • Corrected naming inconsistencies in inbox profile socials queries for improved clarity.
  • Tests

    • Added unit tests for query matching functions to ensure accurate search results.

@alexrisch alexrisch requested a review from a team as a code owner November 26, 2024 23:48
Copy link
Contributor

coderabbitai bot commented Nov 26, 2024

Walkthrough

The pull request introduces new unit tests for the dmMatchesSearchQuery and groupMatchesSearchQuery functions, enhancing the search functionality for direct messages and groups based on user queries. The tests cover various scenarios to ensure accuracy in matching. Additionally, the search utility functions have been updated to accept structured parameters, improving their modularity. A new function for retrieving inbox profile socials data has also been added, alongside corrections to naming conventions in the codebase. The ConversationList component has been modified to utilize these functions for filtering conversations based on search queries.

Changes

File Change Summary
features/conversations/utils/tests/search.test.ts Added unit tests for dmMatchesSearchQuery and groupMatchesSearchQuery covering multiple scenarios.
features/conversations/utils/search.ts Updated dmMatchesSearchQuery and groupMatchesSearchQuery to accept structured parameters; added inboxIdMatchesSearchQuery and addressMatchesSearchQuery functions.
queries/useInboxProfileSocialsQuery.ts Renamed inboxProfileSocialesQueryConfig to inboxProfileSocialsQueryConfig; added getInboxProfileSocialsQueryData function.
screens/ConversationList.tsx Modified to use dmMatchesSearchQuery and groupMatchesSearchQuery for filtering conversation items based on search queries.

Assessment against linked issues

Objective Addressed Explanation
Searching for a user should return groups they are in with you (#222)

Possibly related PRs

  • fix: Test Updates #1253: The test updates in this PR may relate to the new unit tests introduced in the main PR, as both involve testing functionalities within the application, although they focus on different aspects.
  • feat: Notification Subscriptions forV3 #1258: This PR's changes to notification subscriptions could be indirectly related to the search functionalities in the main PR, as improved notification handling may affect how conversations are filtered or displayed based on user interactions.

Suggested reviewers

  • thierryskoda

Poem

In the burrow where queries roam,
We search for friends, we call them home.
With tests that hop and functions bright,
Conversations bloom, a joyous sight!
So let us cheer, with whiskers wide,
For every match, we take in stride! 🐰✨


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.

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.

@alexrisch alexrisch added the 3.0.0 Release 3.0.0 label Nov 26, 2024
@alexrisch alexrisch added this to the Milestone 1 - V3 Only milestone Nov 26, 2024
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: 6

🧹 Outside diff range and nitpick comments (8)
features/conversations/utils/search.ts (2)

73-79: Add input validation to addressMatchesSearchQuery

While the function is correct, it should validate inputs to prevent potential errors.

Consider this improvement:

 const addressMatchesSearchQuery = (
   account: string,
   searchQuery: string,
   address: string
 ) => {
+  if (!address || !searchQuery) return false;
   return address.toLowerCase().includes(searchQuery.toLowerCase());
 };

1-79: Consider performance optimizations

The search implementation makes multiple async calls and string operations per item, which could impact performance with large datasets. Consider these improvements:

  1. Cache profile data to reduce API calls
  2. Implement debouncing for search operations
  3. Consider using a more efficient search algorithm for large datasets (e.g., Trie data structure for prefix matching)

Would you like assistance in implementing any of these optimizations?

queries/useInboxProfileSocialsQuery.ts (1)

Line range hint 36-56: Consider improving type safety by handling undefined values explicitly

The config uses non-null assertions (!) with potentially undefined inboxId. While the enabled condition prevents execution when inboxId is undefined, it's better to handle these cases explicitly for improved type safety.

Consider this safer approach:

 const inboxProfileSocialsQueryConfig = (
   account: string,
   inboxId: InboxId | undefined
 ) => ({
-  queryKey: profileSocialsQueryKey(account, inboxId!),
-  queryFn: () => fetchInboxProfileSocials(inboxId!),
+  queryKey: profileSocialsQueryKey(account, inboxId ?? ''),
+  queryFn: () => {
+    if (!inboxId) throw new Error('inboxId is required');
+    return fetchInboxProfileSocials(inboxId);
+  },
   enabled: !!account && !!inboxId,
   // ... rest of the config
 });
features/conversations/utils/__tests__/search.test.ts (2)

14-16: Consider using a separate mock implementation file

The inline mock implementation for getPreferredInboxName might be brittle as it's tightly coupled to the implementation details. Consider moving mock implementations to a separate mock file for better maintainability.

- jest.mock("@/utils/profile", () => ({
-   getPreferredInboxName: jest.fn((profiles) => profiles?.userNames?.[0] || ""),
- }));
+ jest.mock("@/utils/profile", () => require("../__mocks__/profile"));

30-70: Add test cases for edge scenarios

The current test suite misses some important edge cases. Consider adding tests for:

  • Empty search query
  • Case sensitivity
  • Special characters in search query
  • Unicode/emoji in names
utils/xmtpRN/sync.ts (3)

Line range hint 120-134: LGTM! Consider enhancing error context.

The error handling and retry strategy for conversation streaming are well-implemented. The non-fatal error approach is appropriate for stream failures.

Consider adding the error type to the logging context for better debugging:

     }).catch((e) => {
       logger.error(e, {
-        context: `Failed to stream conversations for ${account} no longer retrying`,
+        context: `Failed to stream conversations for ${account} no longer retrying. Error type: ${e.constructor.name}`,
       });
     });

Line range hint 134-146: Consider refactoring retry configuration and improving documentation.

While the implementation is correct, there are opportunities for improvement:

  1. Extract the retry configuration to reduce duplication:
const RETRY_CONFIG = {
  retries: 5,
  delay: 1000,
  factor: 2,
  maxDelay: 30000,
};

await retryWithBackoff({
  ...RETRY_CONFIG,
  fn: () => streamAllMessages(account),
  context: `streaming all messages for ${account}`,
});
  1. Enhance the comment about group message streaming:
-    // Streaming all dm messages (not groups because buggy)
+    // Streaming all DM messages only. Group message streaming is temporarily disabled
+    // due to known synchronization issues (TODO: Link to issue tracker)

Line range hint 120-146: Consider adding rate limiting for message synchronization.

While the retry mechanism and error handling are robust, the message synchronization process might benefit from rate limiting to prevent overwhelming the XMTP network or client resources, especially when dealing with large message histories.

Consider implementing rate limiting using a token bucket algorithm or similar approach. This could help prevent potential issues with:

  • Network bandwidth consumption
  • Client-side memory usage
  • Server load during mass synchronization

Would you like me to provide an example implementation of rate limiting for the sync process?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 40b3c01 and 35adfaa.

⛔ Files ignored due to path filters (1)
  • queries/__snapshots__/QueryKeys.test.ts.snap is excluded by !**/*.snap
📒 Files selected for processing (5)
  • features/conversations/utils/__tests__/search.test.ts (1 hunks)
  • features/conversations/utils/search.ts (1 hunks)
  • queries/useInboxProfileSocialsQuery.ts (5 hunks)
  • screens/ConversationList.tsx (2 hunks)
  • utils/xmtpRN/sync.ts (2 hunks)
🔇 Additional comments (6)
features/conversations/utils/search.ts (1)

1-8: LGTM: Imports and type definitions are well-structured

The imports and type definitions are appropriate for the search functionality implementation.

queries/useInboxProfileSocialsQuery.ts (2)

Line range hint 57-93: LGTM! Clean implementation of React Query hooks and utilities

The query hooks and utility functions are well-structured, following React Query best practices. The batch processing implementation for multiple queries is particularly well done.


95-104: 🛠️ Refactor suggestion

Verify return type consistency and add parameter validation

The return type ProfileSocials[] | null might not match the actual data structure from queryClient.getQueryData(). Based on the fetchInboxProfileSocials implementation and other functions in the file, it seems the data should be ProfileSocials | null (single object, not array).

Let's verify the data structure usage:

Consider this safer implementation:

 export const getInboxProfileSocialsQueryData = (
   account: string,
   inboxId: InboxId
-): ProfileSocials[] | null => {
+): ProfileSocials | null => {
+  if (!account || !inboxId) return null;
   return (
     queryClient.getQueryData(
       inboxProfileSocialsQueryConfig(account, inboxId).queryKey
     ) ?? null
   );
 };
features/conversations/utils/__tests__/search.test.ts (2)

21-29: LGTM! Well-structured test setup

The test suite setup follows best practices with proper test isolation through beforeEach and clear variable definitions.


1-1: Verify test coverage for all exported functions

Let's verify that all exported functions from the search module are properly tested.

✅ Verification successful

Test coverage is comprehensive for all exported functions

The test file thoroughly covers both exported functions dmMatchesSearchQuery and groupMatchesSearchQuery. Each function has multiple test cases covering different scenarios:

For dmMatchesSearchQuery:

  • Matching by inboxId
  • Matching by member's address
  • No matches (negative case)

For groupMatchesSearchQuery:

  • Matching by group name
  • Matching by member's inboxId
  • Matching by member's address
  • No matches (negative case)
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Find all exported functions from search.ts and compare with test coverage
ast-grep --pattern 'export function $name($$$)' ../search.ts

Length of output: 122


Script:

#!/bin/bash
# Find the search.ts file first
fd "search.ts" --type f

# Then find all exported functions from search.ts
ast-grep --pattern 'export function $name($$$)'

# Also check for other export patterns
ast-grep --pattern 'export const $name = $$$'

Length of output: 234


Script:

#!/bin/bash
# Let's examine the content of the specific search.ts file and its test file
cat features/conversations/utils/search.ts
cat features/conversations/utils/__tests__/search.test.ts

Length of output: 6705

screens/ConversationList.tsx (1)

45-49: Added necessary imports for search functionality

The imports for ConversationVersion, dmMatchesSearchQuery, and groupMatchesSearchQuery are correctly added to support the new search feature.

features/conversations/utils/search.ts Outdated Show resolved Hide resolved
features/conversations/utils/search.ts Outdated Show resolved Hide resolved
features/conversations/utils/search.ts Outdated Show resolved Hide resolved
Comment on lines +32 to +35
const mockDm = {
peerInboxId: jest.fn().mockResolvedValue(mockInboxId),
members: jest.fn().mockResolvedValue([]),
} as unknown as DmWithCodecsType;
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

Improve type safety in test mocks

Instead of using type casting with as unknown as DmWithCodecsType, consider creating a proper mock factory function that returns a correctly typed mock object. This would catch type issues earlier and make the tests more maintainable.

function createMockDm(overrides?: Partial<DmWithCodecsType>): DmWithCodecsType {
  return {
    peerInboxId: jest.fn().mockResolvedValue("defaultId"),
    members: jest.fn().mockResolvedValue([]),
    ...overrides
  };
}

Also applies to: 46-49

Comment on lines 72 to 160
describe("groupMatchesSearchQuery", () => {
it("returns true if group name matches the search query", async () => {
const mockGroup = {
name: "testGroupName",
members: jest.fn().mockResolvedValue([]),
} as unknown as GroupWithCodecsType;

const result = await groupMatchesSearchQuery(
account,
searchQuery,
mockGroup
);
expect(result).toBe(true);
});

it("returns true if a member's inboxId matches the search query", async () => {
const mockGroup = {
name: "nonMatchingName",
members: jest
.fn()
.mockResolvedValue([
{ inboxId: mockInboxId, addresses: ["nonMatchingAddress"] },
]),
} as unknown as GroupWithCodecsType;

mockGetInboxProfileSocialsQueryData.mockReturnValue([
{ userNames: ["testUser"] },
]);

const result = await groupMatchesSearchQuery(
account,
"mockInbox",
mockGroup
);
expect(result).toBe(true);
});

it("returns true if a member's address matches the search query", async () => {
const mockGroup = {
name: "nonMatchingName",
members: jest
.fn()
.mockResolvedValue([
{ inboxId: "nonMatchingId", addresses: ["testAddress"] },
]),
} as unknown as GroupWithCodecsType;

mockGetInboxProfileSocialsQueryData.mockReturnValue(null);

const result = await groupMatchesSearchQuery(
account,
searchQuery,
mockGroup
);
expect(result).toBe(true);
});

it("returns false if neither group name, inboxId, nor members match the search query", async () => {
const mockGroup = {
name: "nonMatchingName",
members: jest
.fn()
.mockResolvedValue([
{ inboxId: "nonMatchingId", addresses: ["nonMatchingAddress"] },
]),
} as unknown as GroupWithCodecsType;

mockGetInboxProfileSocialsQueryData.mockReturnValue(null);

const result = await groupMatchesSearchQuery(
account,
searchQuery,
mockGroup
);
expect(result).toBe(false);
});
});
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

Refactor test structure to reduce duplication

The group tests follow a similar pattern to DM tests with similar mock setups. Consider:

  1. Creating shared test utilities for common mock setups
  2. Using test.each for similar test cases with different inputs
  3. Adding the same edge cases as suggested for DM tests

Example refactor:

const testCases = [
  ['group name', { name: 'testGroupName' }, 'test', true],
  ['member inboxId', { name: 'other', members: [{ inboxId: 'testId' }] }, 'test', true],
  // ... more cases
] as const;

test.each(testCases)(
  'returns %s when %s matches search query',
  async (scenario, mockData, query, expected) => {
    const mockGroup = createMockGroup(mockData);
    const result = await groupMatchesSearchQuery(account, query, mockGroup);
    expect(result).toBe(expected);
  }
);

screens/ConversationList.tsx Outdated Show resolved Hide resolved
Added search for V3 Only

Added tests
Updated Snapshots
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: 4

🧹 Outside diff range and nitpick comments (4)
features/conversations/utils/search.ts (3)

9-13: Add input validation for searchQuery parameter

Consider adding runtime validation for the searchQuery parameter to ensure it's a non-empty string and within reasonable length limits.

 type DmSearchParams = {
   account: string;
-  searchQuery: string;
+  searchQuery: string & { __brand: 'NonEmptyString' };
   dm: DmWithCodecsType;
 };
+
+const validateSearchQuery = (query: string): query is DmSearchParams['searchQuery'] => {
+  return typeof query === 'string' && 
+         query.trim().length > 0 && 
+         query.length <= 100;  // adjust max length as needed
+};

27-37: Potential memory leak in members iteration

The members array is held in memory while processing each member sequentially. For large groups, this could lead to memory pressure.

Consider using an async generator to process members in chunks:

-  const members = await dm.members();
-  for (const member of members) {
+  for await (const member of dm.members()) {
     if (
       await addressMatchesSearchQuery({
         searchQuery,
         address: member.addresses[0],
       })
     ) {
       return true;
     }
   }

114-122: Remove unnecessary async keyword

The function doesn't perform any asynchronous operations, so it doesn't need to be marked as async.

-const addressMatchesSearchQuery = async ({
+const addressMatchesSearchQuery = ({
   searchQuery,
   address,
-}: AddressSearchParams): Promise<boolean> => {
+}: AddressSearchParams): boolean => {
   if (!address) {
     return false;
   }
   return address.toLowerCase().includes(searchQuery.toLowerCase());
 };
screens/ConversationList.tsx (1)

117-141: Extract filtering logic into a custom hook

The filtering logic is complex enough to warrant its own custom hook, which would improve maintainability and reusability.

Consider creating a new hook useFilteredConversations:

function useFilteredConversations(
  items: (ConversationFlatListItem | ConversationWithCodecsType)[] | undefined,
  searchQuery: string,
  currentAccount: Account | null
) {
  const [filteredItems, setFilteredItems] = useState<{
    items: FlatListItemType[];
    searchQuery: string;
  }>({ items: [], searchQuery: "" });

  useEffect(() => {
    // ... existing filtering logic ...
  }, [searchQuery, items, currentAccount]);

  return filteredItems;
}

This would simplify the main component and make the filtering logic more testable.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 35adfaa and f8ecc59.

⛔ Files ignored due to path filters (1)
  • queries/__snapshots__/QueryKeys.test.ts.snap is excluded by !**/*.snap
📒 Files selected for processing (5)
  • features/conversations/utils/__tests__/search.test.ts (1 hunks)
  • features/conversations/utils/search.ts (1 hunks)
  • queries/useInboxProfileSocialsQuery.ts (5 hunks)
  • screens/ConversationList.tsx (2 hunks)
  • utils/xmtpRN/sync.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • features/conversations/utils/tests/search.test.ts
  • queries/useInboxProfileSocialsQuery.ts
  • utils/xmtpRN/sync.ts
🔇 Additional comments (3)
features/conversations/utils/search.ts (1)

1-122: Ensure comprehensive test coverage

While the AI summary mentions tests were added, ensure the test coverage includes:

  • Edge cases for empty/invalid inputs
  • Performance testing with large member lists
  • Mocking of async operations
  • Error scenarios for profile data fetching
screens/ConversationList.tsx (2)

45-49: LGTM: Clean import structure

The new imports are well-organized and properly scoped for the search functionality.


142-148: LGTM: Clean search query handling

The search query validation and state updates are well implemented.

Comment on lines +98 to +101
const profiles = getInboxProfileSocialsQueryData(account, inboxId);
if (!profiles) {
return false;
}
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

Fix missing await for async operation

The getInboxProfileSocialsQueryData call is likely asynchronous but isn't awaited, which could lead to race conditions.

-  const profiles = getInboxProfileSocialsQueryData(account, inboxId);
+  const profiles = await getInboxProfileSocialsQueryData(account, inboxId);
   if (!profiles) {
     return false;
   }

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +55 to +57
if (group.name.toLowerCase().includes(searchQuery.toLowerCase())) {
return true;
}
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

Optimize case-insensitive string comparisons

Converting strings to lowercase on every comparison is inefficient. Consider normalizing the search query once at the start.

 export const groupMatchesSearchQuery = async ({
   account,
   searchQuery,
   group,
 }: GroupSearchParams): Promise<boolean> => {
   if (!group) {
     return false;
   }
+  const normalizedQuery = searchQuery.toLowerCase();
-  if (group.name.toLowerCase().includes(searchQuery.toLowerCase())) {
+  if (group.name.toLowerCase().includes(normalizedQuery)) {
     return true;
   }

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +121 to +125
const groupMatches = await groupMatchesSearchQuery({
account: currentAccount!,
searchQuery,
group: item,
});
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

Improve type safety by validating currentAccount

The code uses non-null assertions (currentAccount!) which could lead to runtime errors if currentAccount is null.

Add early return or validation:

 const getFilteredItems = async () => {
+  if (!currentAccount) {
+    console.warn('No current account available for search');
+    return [];
+  }
   const filteredItems: FlatListItemType[] = [];
   for (const item of items ?? []) {
     if (item.version === ConversationVersion.GROUP) {
       const groupMatches = await groupMatchesSearchQuery({
-        account: currentAccount!,
+        account: currentAccount,
         searchQuery,
         group: item,
       });
       // ... rest of the code
     } else if (item.version === ConversationVersion.DM) {
       const dmMatches = await dmMatchesSearchQuery({
-        account: currentAccount!,
+        account: currentAccount,
         searchQuery,
         dm: item,
       });
       // ... rest of the code
     }
   }
   return filteredItems ?? [];
 };

Also applies to: 130-134

Comment on lines +117 to +141
const getFilteredItems = async () => {
const filteredItems: FlatListItemType[] = [];
for (const item of items ?? []) {
if (item.version === ConversationVersion.GROUP) {
const groupMatches = await groupMatchesSearchQuery({
account: currentAccount!,
searchQuery,
group: item,
});
if (groupMatches) {
filteredItems.push(item);
}
} else if (item.version === ConversationVersion.DM) {
const dmMatches = await dmMatchesSearchQuery({
account: currentAccount!,
searchQuery,
dm: item,
});
if (dmMatches) {
filteredItems.push(item);
}
}
}
return filteredItems ?? [];
};
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 error handling for async operations

The async filtering logic lacks error handling, which could lead to unhandled promise rejections if either dmMatchesSearchQuery or groupMatchesSearchQuery fails.

Add try-catch block:

 const getFilteredItems = async () => {
+  try {
     const filteredItems: FlatListItemType[] = [];
     for (const item of items ?? []) {
       if (item.version === ConversationVersion.GROUP) {
         const groupMatches = await groupMatchesSearchQuery({
           account: currentAccount!,
           searchQuery,
           group: item,
         });
         if (groupMatches) {
           filteredItems.push(item);
         }
       } else if (item.version === ConversationVersion.DM) {
         const dmMatches = await dmMatchesSearchQuery({
           account: currentAccount!,
           searchQuery,
           dm: item,
         });
         if (dmMatches) {
           filteredItems.push(item);
         }
       }
     }
     return filteredItems ?? [];
+  } catch (error) {
+    console.error('Search filtering failed:', error);
+    return [];
+  }
 };
📝 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
const getFilteredItems = async () => {
const filteredItems: FlatListItemType[] = [];
for (const item of items ?? []) {
if (item.version === ConversationVersion.GROUP) {
const groupMatches = await groupMatchesSearchQuery({
account: currentAccount!,
searchQuery,
group: item,
});
if (groupMatches) {
filteredItems.push(item);
}
} else if (item.version === ConversationVersion.DM) {
const dmMatches = await dmMatchesSearchQuery({
account: currentAccount!,
searchQuery,
dm: item,
});
if (dmMatches) {
filteredItems.push(item);
}
}
}
return filteredItems ?? [];
};
const getFilteredItems = async () => {
try {
const filteredItems: FlatListItemType[] = [];
for (const item of items ?? []) {
if (item.version === ConversationVersion.GROUP) {
const groupMatches = await groupMatchesSearchQuery({
account: currentAccount!,
searchQuery,
group: item,
});
if (groupMatches) {
filteredItems.push(item);
}
} else if (item.version === ConversationVersion.DM) {
const dmMatches = await dmMatchesSearchQuery({
account: currentAccount!,
searchQuery,
dm: item,
});
if (dmMatches) {
filteredItems.push(item);
}
}
}
return filteredItems ?? [];
} catch (error) {
console.error('Search filtering failed:', error);
return [];
}
};

utils/xmtpRN/sync.ts Outdated Show resolved Hide resolved
features/conversations/utils/search.ts Outdated Show resolved Hide resolved
features/conversations/utils/search.ts Outdated Show resolved Hide resolved
features/conversations/utils/search.ts Outdated Show resolved Hide resolved
features/conversations/utils/search.ts Outdated Show resolved Hide resolved
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: 0

🧹 Outside diff range and nitpick comments (2)
features/conversations/utils/search.ts (2)

105-113: Optimize string comparisons and consider async consistency

The function could be improved for better performance and consistency:

Consider these improvements:

-const addressMatchesSearchQuery = ({
+const addressMatchesSearchQuery = async ({
   searchQuery,
   address,
-}: AddressSearchParams): boolean => {
+}: AddressSearchParams): Promise<boolean> => {
   if (!address) {
     return false;
   }
-  return address.toLowerCase().includes(searchQuery.toLowerCase());
+  const normalizedQuery = searchQuery.toLowerCase();
+  return address.toLowerCase().includes(normalizedQuery);
 };

1-113: Consider caching normalized strings and search results

While the implementation successfully meets the PR objectives for enhanced search functionality, consider these architectural improvements:

  1. Cache normalized strings (lowercase versions) at the entity level to avoid repeated transformations
  2. Consider implementing a caching mechanism for search results to improve performance for frequently searched terms
  3. Add rate limiting for search operations to prevent potential DoS attacks
  4. Consider implementing fuzzy search for better user experience

Would you like help implementing any of these improvements?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between f8ecc59 and 7ecc269.

📒 Files selected for processing (1)
  • features/conversations/utils/search.ts (1 hunks)
🔇 Additional comments (4)
features/conversations/utils/search.ts (4)

1-14: LGTM! Well-structured type definitions

The type definitions are clear, well-organized, and provide good type safety for the search parameters.

Also applies to: 38-42, 75-79, 100-104


81-98: ⚠️ Potential issue

Fix async operation and optimize string comparisons

The function has several issues that need to be addressed:

Apply these improvements:

 const inboxIdMatchesSearchQuery = async ({
   account,
   searchQuery,
   inboxId,
 }: InboxIdSearchParams): Promise<boolean> => {
+  if (!searchQuery?.trim()) {
+    return false;
+  }
+  try {
+    const normalizedQuery = searchQuery.toLowerCase();
-    if (inboxId.toLowerCase().includes(searchQuery.toLowerCase())) {
+    if (inboxId.toLowerCase().includes(normalizedQuery)) {
       return true;
     }
-    const profiles = getInboxProfileSocialsQueryData(account, inboxId);
+    const profiles = await getInboxProfileSocialsQueryData(account, inboxId);
     if (!profiles) {
       return false;
     }
     const name = getPreferredInboxName(profiles);
-    if (name.toLowerCase().includes(searchQuery.toLowerCase())) {
+    if (name.toLowerCase().includes(normalizedQuery)) {
       return true;
     }
     return false;
+  } catch (error) {
+    console.error('Error in inboxIdMatchesSearchQuery:', error);
+    return false;
+  }
 };

Likely invalid or redundant comment.


15-36: ⚠️ Potential issue

Add error handling and safe array access

The function needs improvements in error handling and array access safety:

Apply these improvements:

 export const dmMatchesSearchQuery = async ({
   account,
   searchQuery,
   dm,
 }: DmSearchParams): Promise<boolean> => {
+  if (!searchQuery?.trim()) {
+    return false;
+  }
+  try {
     const inboxId = await dm.peerInboxId();
     if (await inboxIdMatchesSearchQuery({ account, searchQuery, inboxId })) {
       return true;
     }
     const members = await dm.members();
     for (const member of members) {
+      const address = member.addresses?.[0];
+      if (!address) continue;
       if (
         addressMatchesSearchQuery({
           searchQuery,
-          address: member.addresses[0],
+          address,
         })
       ) {
         return true;
       }
     }
     return false;
+  } catch (error) {
+    console.error('Error in dmMatchesSearchQuery:', error);
+    return false;
+  }
 };

Likely invalid or redundant comment.


44-73: ⚠️ Potential issue

Add error handling and optimize string comparisons

Similar to dmMatchesSearchQuery, this function needs error handling improvements. Additionally, the string comparisons can be optimized.

Apply these improvements:

 export const groupMatchesSearchQuery = async ({
   account,
   searchQuery,
   group,
 }: GroupSearchParams): Promise<boolean> => {
+  if (!searchQuery?.trim()) {
+    return false;
+  }
+  try {
+    const normalizedQuery = searchQuery.toLowerCase();
-    if (group.name.toLowerCase().includes(searchQuery.toLowerCase())) {
+    if (group.name.toLowerCase().includes(normalizedQuery)) {
       return true;
     }
     const members = await group.members();
     for (const member of members) {
+      const address = member.addresses?.[0];
+      if (!address) continue;
       if (
         await inboxIdMatchesSearchQuery({
           account,
           searchQuery,
           inboxId: member.inboxId,
         })
       ) {
         return true;
       }
       if (
         addressMatchesSearchQuery({
           searchQuery,
-          address: member.addresses[0],
+          address,
         })
       ) {
         return true;
       }
     }
     return false;
+  } catch (error) {
+    console.error('Error in groupMatchesSearchQuery:', error);
+    return false;
+  }
 };

Likely invalid or redundant comment.

@alexrisch alexrisch merged commit ef0e8d4 into feature/v3-split Nov 27, 2024
1 check passed
@alexrisch alexrisch deleted the ar/v3-search branch November 27, 2024 16:41
technoplato pushed a commit that referenced this pull request Dec 17, 2024
* feat: V3 Search

Added search for V3 Only

Added tests
Updated Snapshots

* remove checks
Removed async
Removed await

* remove inboxId check
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
3.0.0 Release 3.0.0
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants