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

fix: add ClearAll dataloader method #9975

Merged
merged 2 commits into from
Jul 15, 2024
Merged

fix: add ClearAll dataloader method #9975

merged 2 commits into from
Jul 15, 2024

Conversation

mattkrick
Copy link
Member

@mattkrick mattkrick commented Jul 15, 2024

Description

Curious for your feedback on this pattern @Dschoordsch @nickoferrall.

The problem:
After the DB is mutated, devs have to call clearAll on every dataloader that could have been used & is now stale. Adding a new dataloader requires auditing all existing DB mutations to make sure calls to clear it exist.

// imagine this line gets called early on in the resolver, nested a few functions deep, so it's not obvious it was called
const orgUsersByOrg = await dataLoader.get('organizationUsersByOrgId').load(orgId)

// resolver.ts
const orgUsersByUserId = await dataLoader.get('organizationUsersByUserId').load(userId)
await pg.updateTable('OrganizationUser').set({foo: 2}).where('userId', '=', userId).where('orgId', '=', orgId).execute()

dataLoader.get('organizationUsersByUserId').clear(userId) // does not clear ByOrgId
dataLoader.get('organizationUsers').updateCache({orgId, userId}, {foo: 2}) // does not update the object in ByOrgId
const orgUsersByOrg = await dataLoader.get('organizationUsersByOrgId').load(orgId) // ERROR! Stale data

Proposed solution:
Immediately after a database mutation, wipe out any dataloaders that depend on that table

dataLoader.clearAll('organizationUsers') // clears any used dataloader that registers as a dependent of `organizationUsers`
const orgUsersByOrg = await dataLoader.get('organizationUsersByOrgId').load(orgId) // Fresh hit to the DB

Summary by CodeRabbit

  • New Features

    • Introduced a generic saml function for fetching SAML-related data.
  • Improvements

    • Enhanced dataLoader functionality with a more flexible and extensible design.
    • Improved performance and consistency in data loading by clearing all organizationUsers entries.
  • Refactor

    • Unified and simplified loader dependency management.
    • Refactored normalizeResults to improve performance.
  • Bug Fixes

    • Corrected return type in rethinkForeignKeyLoader to ensure accurate data loading and caching.

Copy link
Contributor

coderabbitai bot commented Jul 15, 2024

Walkthrough

The updates streamline and enhance the flexibility of data-loader handling in the server package. Key changes include clearing all organisation user data instead of individual user data, introducing a more generic approach to the RootDataLoader class and its dependencies, and adding a new saml function for primary key loading. Moreover, various loader functions in customLoaderMakers and foreignKeyLoaderMaker now accommodate dependency registration, ensuring efficient and consistent data management.

Changes

File Path Change Summary
.../billing/helpers/adjustUserCount.ts Modified to clear all dataLoader entries for 'organizationUsers' rather than clearing by specific userId.
.../dataloader/RootDataLoader.ts Refactored to introduce a generic GenericDataLoader interface, add dependency tracking, and enhance loader instantiation and management.
.../dataloader/customLoaderMakers.ts Added dependsOn: RegisterDependsOn parameter to various loader functions to register dependencies efficiently.
.../dataloader/foreignKeyLoaderMaker.ts Updated function signatures for generic type usage and added a dependsOn parameter to handle dependencies.
.../dataloader/normalizeResults.ts Refactored normalizeResults to directly map results by keys using Array.map.
.../dataloader/primaryKeyLoaderMakers.ts Introduced a new saml function for fetching data related to SAML domains and SAML IDs.
.../dataloader/rethinkForeignKeyLoader.ts Modified rethinkForeignKeyLoader to return UpdatableCacheDataLoader<string, DBType[T][]> instead of UpdatableCacheDataLoader<string, DBType[T]>
.../graphql/DataLoaderCache.ts Enhanced CacheWorker and DataLoaderCache classes to improve data loader handling with generic type constraints and streamlined methods.
.../graphql/getDataLoader.ts Initialized dataLoaderCache with RootDataLoader and streamlined the getDataLoader function to avoid redundant instantiation.

Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 118dd95 and 78feb1d.

Files selected for processing (3)
  • packages/server/billing/helpers/adjustUserCount.ts (2 hunks)
  • packages/server/dataloader/customLoaderMakers.ts (23 hunks)
  • packages/server/dataloader/primaryKeyLoaderMakers.ts (1 hunks)
Files skipped from review as they are similar to previous changes (2)
  • packages/server/billing/helpers/adjustUserCount.ts
  • packages/server/dataloader/primaryKeyLoaderMakers.ts
Additional comments not posted (20)
packages/server/dataloader/customLoaderMakers.ts (20)

87-91: Review of commentCountByDiscussionId function: Correct use of dependsOn

The addition of the dependsOn parameter to register the 'comments' dependency is correctly implemented. This ensures that any changes affecting comments will trigger the appropriate updates in this loader, aligning with the PR's objectives to manage dependencies effectively.


149-150: Review of reactables function: Correct dependency registration

The function now correctly registers multiple dependencies based on the reactableLoaders array. This change makes the data loader more robust by ensuring it responds to changes in any of the related loaders.


171-172: Review of userTasks function: Dependency on 'tasks'

The addition of the dependsOn('tasks') ensures that this loader is cleared when tasks data is mutated, which is crucial for maintaining data integrity and freshness.


318-319: Review of meetingSettingsByType function: Dependency registration

The dependsOn('meetingSettings') correctly registers a dependency on meeting settings, which is essential for ensuring that changes in meeting settings are reflected in the loader's data.


399-403: Review of organizationUsersByUserIdOrgId function: Dependency management

This function now properly registers a dependency on 'organizationUsers'. This is a critical update that helps maintain the integrity of user data within organizations.


430-431: Review of meetingTemplatesByType function: Dependency on 'meetingTemplates'

The function correctly registers a dependency on 'meetingTemplates'. This ensures that any updates to meeting templates are propagated to this loader, maintaining data consistency.


484-485: Review of meetingTemplatesByOrgId function: Dependency registration

The addition of the dependsOn('meetingTemplates') is correctly implemented. This ensures that the loader is aware of changes to meeting templates at the organization level, which is crucial for accurate data representation.


511-512: Review of meetingTemplatesByTeamId function: Correct dependency management

This function's dependency on 'meetingTemplates' is correctly implemented, ensuring that changes at the team level in meeting templates are correctly handled by the loader.


535-536: Review of meetingStatsByOrgId function: Dependency on 'newMeetings'

The function correctly registers a dependency on 'newMeetings'. This is crucial for ensuring that the loader updates its data in response to new meetings data.


567-568: Review of teamStatsByOrgId function: Correct use of dependsOn

The implementation of dependsOn('teams') is correct, ensuring that team-related changes are accounted for in this loader.


588-592: Review of taskIdsByTeamAndGitHubRepo function: Dependency on 'tasks'

The addition of the dependsOn('tasks') parameter is correctly implemented, ensuring that task-related changes trigger appropriate updates to this loader.


630-634: Review of activeMeetingsByMeetingSeriesId function: Dependency registration

The function correctly registers a dependency on 'newMeetings', ensuring that changes in meeting series data are reflected in the loader's output.


652-656: Review of lastMeetingByMeetingSeriesId function: Correct use of dependsOn

The implementation of dependsOn('newMeetings') is correct, ensuring that the loader responds to changes in meeting series data accurately.


680-681: Review of billingLeadersIdsByOrgId function: Dependency management

The function's dependency on 'organizationUsers' is correctly implemented, ensuring that changes in organization user data are accounted for.


705-706: Review of samlByDomain function: Dependency on 'saml'

The addition of the dependsOn('saml') parameter is correctly implemented, ensuring that SAML-related changes are propagated to this loader.


725-726: Review of samlByOrgId function: Correct dependency registration

This function correctly registers a dependency on 'saml', ensuring that changes in SAML data at the organization level are handled correctly.


747-748: Review of isOrgVerified function: Dependency management

The implementation of dependsOn('organizationUsers') is correct, ensuring that changes in organization user data are reflected in the verification process.


778-779: Review of autoJoinTeamsByOrgId function: Dependency on 'teams'

The addition of the dependsOn('teams') parameter is correctly implemented, ensuring that team-related changes are accounted for in this loader.


824-825: Review of favoriteTemplateIds function: Dependency on 'users'

The function correctly registers a dependency on 'users', ensuring that changes in user data are handled by this loader.


873-874: Review of meetingCount function: Dependency on 'selectTeams'

The addition of the dependsOn('selectTeams') parameter is correctly implemented. This ensures that changes in team data are reflected in the meeting count data.


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

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

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Outside diff range, codebase verification and nitpick comments (3)
packages/server/dataloader/customLoaderMakers.ts (3)

88-91: Update the function call to include the dependsOn argument.

The function commentCountByDiscussionId has been updated to accept a new dependsOn parameter. However, the call to this function in packages/server/graphql/types/Discussion.ts does not include this argument, which could lead to issues.

  • File: packages/server/graphql/types/Discussion.ts
    • Line: Return statement using dataLoader.get('commentCountByDiscussionId').load(discussionId)

Please update the function call to include the dependsOn argument.

Analysis chain

LGTM! Verify correct usage of the dependsOn parameter.

The changes introduce a dependsOn parameter to register dependencies for the data loader. Ensure that all calls to this function correctly provide the dependsOn argument.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify all function calls to `commentCountByDiscussionId` provide the `dependsOn` argument.

# Test: Search for the function usage. Expect: All function calls include the `dependsOn` argument.
rg --type typescript -A 2 $'commentCountByDiscussionId'

Length of output: 89


Script:

#!/bin/bash
# Description: Verify all function calls to `commentCountByDiscussionId` provide the `dependsOn` argument.

# Test: Search for the function usage. Expect: All function calls include the `dependsOn` argument.
rg --type ts -A 2 $'commentCountByDiscussionId'

Length of output: 523


510-511: The dependsOn argument is missing in the function call to meetingTemplatesByTeamId.

The function call in archiveTeam.ts needs to be updated to include the dependsOn argument, as per the new function signature.

  • File: packages/server/graphql/mutations/archiveTeam.ts
  • Line: const teamTemplates = await dataLoader.get('meetingTemplatesByTeamId').load(teamId)

Please update the function call to provide the dependsOn argument.

Analysis chain

LGTM! Verify correct usage of the dependsOn parameter.

The changes introduce a dependsOn parameter to register dependencies for the data loader. Ensure that all calls to this function correctly provide the dependsOn argument.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify all function calls to `meetingTemplatesByTeamId` provide the `dependsOn` argument.

# Test: Search for the function usage. Expect: All function calls include the `dependsOn` argument.
rg --type typescript -A 2 $'meetingTemplatesByTeamId'

Length of output: 87


Script:

#!/bin/bash
# Description: Verify all function calls to `meetingTemplatesByTeamId` provide the `dependsOn` argument.

# Test: Search for the function usage. Expect: All function calls include the `dependsOn` argument.
rg -A 2 'meetingTemplatesByTeamId'

Length of output: 672


587-590: Missing dependsOn Argument in Function Call

The function taskIdsByTeamAndGitHubRepo is being called without the required dependsOn argument in the following location:

  • packages/server/graphql/types/Task.ts, lines surrounding the usage:
    const taskIds = await dataLoader
      .get('taskIdsByTeamAndGitHubRepo')
      .load({teamId, nameWithOwner})

Please ensure that the dependsOn argument is correctly provided in this function call.

Analysis chain

LGTM! Verify correct usage of the dependsOn parameter.

The changes introduce a dependsOn parameter to register dependencies for the data loader. Ensure that all calls to this function correctly provide the dependsOn argument.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify all function calls to `taskIdsByTeamAndGitHubRepo` provide the `dependsOn` argument.

# Test: Search for the function usage. Expect: All function calls include the `dependsOn` argument.
rg --type typescript -A 2 $'taskIdsByTeamAndGitHubRepo'

Length of output: 89


Script:

#!/bin/bash
# Description: Verify all function calls to `taskIdsByTeamAndGitHubRepo` provide the `dependsOn` argument.

# Test: Search for the function usage. Expect: All function calls include the `dependsOn` argument.
rg --type ts -A 2 $'taskIdsByTeamAndGitHubRepo'

Length of output: 577


Script:

#!/bin/bash
# Description: Inspect the surrounding lines of the identified usage of `taskIdsByTeamAndGitHubRepo` to confirm whether the `dependsOn` argument is missing.

# Test: Search for the function usage and include more context lines. Expect: All function calls include the `dependsOn` argument.
rg --type ts -A 5 -B 5 $'taskIdsByTeamAndGitHubRepo' packages/server/graphql/types/Task.ts

Length of output: 654

? inPrimaryLoaders
: [inPrimaryLoaders]
primaryLoaders.forEach((primaryLoader) => {
;(this.dependentLoaders[primaryLoader] ??= []).push(loaderName)
Copy link
Contributor

Choose a reason for hiding this comment

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

Avoid assignments in expressions.

The assignment within the expression can be confusing and should be avoided.

- ;(this.dependentLoaders[primaryLoader] ??= []).push(loaderName)
+ if (!this.dependentLoaders[primaryLoader]) {
+   this.dependentLoaders[primaryLoader] = [];
+ }
+ this.dependentLoaders[primaryLoader].push(loaderName);
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
;(this.dependentLoaders[primaryLoader] ??= []).push(loaderName)
if (!this.dependentLoaders[primaryLoader]) {
this.dependentLoaders[primaryLoader] = [];
}
this.dependentLoaders[primaryLoader].push(loaderName);
Tools
Biome

[error] 111-111: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)

@@ -97,6 +96,7 @@ const addUser = async (orgIds: string[], user: IUser, dataLoader: DataLoaderWork
tier: organization.tier
})
})
dataLoader.clearAll('organizationUsers')
Copy link
Member Author

Choose a reason for hiding this comment

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

now we don't have to wipe every single dataloader that could have been used.
we just wipe the primary key datalaoder & it wipes all dependents.

export interface DataLoaderInstance {
get<LoaderName extends Loaders>(loaderName: LoaderName): TypedDataLoader<LoaderName>
// The RethinkDB logic is a leaky abstraction! It will be gone soon & this will be generic enough to put in its own package
interface GenericDataLoader<TLoaders, TPrimaryLoaderNames> {
Copy link
Member Author

Choose a reason for hiding this comment

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

this is basically TypedDataLoader, but the old version took 350ms to load types, this takes ~150ms

parent: RootDataLoader,
dependsOn: RegisterDependsOn
) => {
dependsOn('comments')
Copy link
Member Author

Choose a reason for hiding this comment

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

custom dataloaders can register with a primary key loader.
when a mutation calls dataLoader.clearAll('comments') this dataloader, if initialized, will get wiped, too.

return (parent: RootDataLoader) => {
const primaryLoader = parent.get(primaryLoaderKey) as DataLoader<PrimaryKeyT, T, PrimaryKeyT>
return (parent: RootDataLoader, dependsOn: RegisterDependsOn) => {
dependsOn(primaryLoaderKey)
Copy link
Member Author

Choose a reason for hiding this comment

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

foreignKey dataloaders are automatically tagged as dependents of the pk loaders

Copy link
Contributor

@nickoferrall nickoferrall left a comment

Choose a reason for hiding this comment

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

I really like this! Not clearing the right dataloader is such a classic bug. This will help a lot!

@mattkrick mattkrick merged commit 63bf930 into master Jul 15, 2024
6 checks passed
@mattkrick mattkrick deleted the fix/dataloader branch July 15, 2024 18:47
@github-actions github-actions bot mentioned this pull request Jul 15, 2024
24 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants