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

chore(rethinkdb): SuggestedAction: Phase 2 #10042

Merged
merged 12 commits into from
Aug 2, 2024

Conversation

mattkrick
Copy link
Member

@mattkrick mattkrick commented Jul 26, 2024

migrate existing rows

Summary by CodeRabbit

  • New Features

    • Transitioned email verification and suggested actions management from RethinkDB to PostgreSQL, improving database reliability and performance.
    • Added new loaders for suggested actions, enhancing user-specific action retrieval.
    • Introduced expiration handling for email verification tokens, ensuring timely verification.
  • Bug Fixes

    • Improved handling of suggested actions to prevent duplication during user onboarding.
  • Chores

    • Added migration scripts for the new PostgreSQL database structure, facilitating the transition and ensuring data integrity.

Copy link
Contributor

coderabbitai bot commented Jul 26, 2024

Warning

Rate limit exceeded

@mattkrick has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 9 minutes and 1 seconds before requesting another review.

How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

Commits

Files that changed from the base of the PR and between 333ff79 and 3391267.

Walkthrough

The recent changes primarily involve transitioning from RethinkDB to PostgreSQL across various modules of the server application. This migration enhances the database management strategy, allowing for improved query structuring and data handling. Additionally, several new features have been introduced to manage suggested actions effectively, along with updates to the email verification process to include expiration handling. Overall, these modifications improve code maintainability, performance, and functionality.

Changes

Files Change Summary
packages/server/__tests__/autoJoin.test.ts Transitioned signUpVerified to PostgreSQL, updated token retrieval and test assertions.
packages/server/dataloader/... Added _suggestedActionsByUserId and _suggestedActions loaders for retrieving user-specific actions.
packages/server/email/... Migrated createEmailVerification and createEmailVerficationForExistingUser to PostgreSQL with expiration handling for tokens.
packages/server/graphql/mutations/... Updated mutations (dismissSuggestedAction, signUpWithPassword, verifyEmail) to use Kysely for PostgreSQL interactions.
packages/server/postgres/migrations/... Introduced migration scripts for EmailVerification and SuggestedAction tables, managing their structure and data.
packages/server/safeMutations/... Updated removeSuggestedAction to utilise Kysely for marking actions as removed, enhancing type safety.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Server
    participant Database

    User->>Server: Sign up with email
    Server->>Database: Insert email verification data
    Database-->>Server: Confirmation of insertion
    Server->>User: Send verification email
    User->>Server: Verify email with token
    Server->>Database: Validate token and set expiration
    Database-->>Server: Return validation result
    Server->>User: Confirmation of email verification
Loading

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

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: 11

Outside diff range, codebase verification and nitpick comments (5)
packages/server/email/createEmailVerficationForExistingUser.ts (1)

37-48: Mismatch in function parameters

The function createEmailVerficationForExistingUser is called with incorrect parameters in packages/server/graphql/public/mutations/helpers/getIsUserIdApprovedByOrg.ts. The new implementation expects different parameters.

  • File: packages/server/graphql/public/mutations/helpers/getIsUserIdApprovedByOrg.ts
  • Code:
    const emailError = await createEmailVerficationForExistingUser(
      userId,
      invitationToken,
      dataLoader
    )

The function should be updated to match the new implementation.

Analysis chain

LGTM! But verify the function usage in the codebase.

The code changes are approved.

However, ensure that all function calls to createEmailVerficationForExistingUser match the new implementation.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify all function calls to `createEmailVerficationForExistingUser` match the new implementation.

# Test: Search for the function usage. Expect: Only occurrences of the new implementation.
rg --type ts 'createEmailVerficationForExistingUser'

Length of output: 615


Script:

#!/bin/bash
# Extracting relevant lines around the function call to inspect parameters passed to createEmailVerficationForExistingUser

rg --type ts -A 10 'createEmailVerficationForExistingUser' packages/server/graphql/public/mutations/helpers/getIsUserIdApprovedByOrg.ts

Length of output: 937

packages/server/postgres/migrations/1722013208553_SuggestAction-phase2.ts (3)

28-28: Remove redundant log message.

The log message "Adding index complete" is redundant because the previous log message already indicates the completion of the index creation process.

-  console.log('Adding index complete')

36-38: Clarify loop termination condition.

The loop termination condition i < 1e6 is arbitrary. Consider clarifying the condition or making it configurable.

-  for (let i = 0; i < 1e6; i++) {
+  const MAX_ITERATIONS = 1e6; // or make it configurable
+  for (let i = 0; i < MAX_ITERATIONS; i++) {

52-54: Remove unnecessary spread operator.

The spread operator in rowsToInsert is unnecessary since no additional properties are being added.

-    const rowsToInsert = rawRowsToInsert.map((row) => ({
-      ...row
-    }))
+    const rowsToInsert = rawRowsToInsert
packages/server/__tests__/autoJoin.test.ts (1)

60-62: Update test assertion for authToken.

The test assertion for authToken should check for a non-empty string to ensure the token is valid.

-        authToken: expect.any(String),
+        authToken: expect.stringMatching(/^.+$/),

Comment on lines 38 to 42
await getKysely()
.updateTable('SuggestedAction')
.set({removedAt: now})
.where('id', '=', suggestedActionId)
.execute()
Copy link
Contributor

Choose a reason for hiding this comment

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

Ensure proper error handling for Kysely operations.

The Kysely operations should have proper error handling to catch and log any potential issues.

+ try {
    await getKysely()
      .updateTable('SuggestedAction')
      .set({removedAt: now})
      .where('id', '=', suggestedActionId)
      .execute()
+ } catch (error) {
+   console.error('Error updating SuggestedAction with Kysely:', error)
+ }
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
await getKysely()
.updateTable('SuggestedAction')
.set({removedAt: now})
.where('id', '=', suggestedActionId)
.execute()
try {
await getKysely()
.updateTable('SuggestedAction')
.set({removedAt: now})
.where('id', '=', suggestedActionId)
.execute()
} catch (error) {
console.error('Error updating SuggestedAction with Kysely:', error)
}

Comment on lines 142 to 148
const inviteYourTeam = {
id: generateUID(),
userId,
teamId,
type: 'inviteYourTeam' as const,
priority: 2
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Avoid duplication of action creation.

The creation of the inviteYourTeam action is duplicated. Consider refactoring to avoid redundancy.

-  const inviteYourTeam = {
-    id: generateUID(),
-    userId,
-    teamId,
-    type: 'inviteYourTeam' as const,
-    priority: 2
-  }
+  const inviteYourTeam = createInviteYourTeamAction(userId, teamId)
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 inviteYourTeam = {
id: generateUID(),
userId,
teamId,
type: 'inviteYourTeam' as const,
priority: 2
}
const inviteYourTeam = createInviteYourTeamAction(userId, teamId)

Comment on lines 108 to 114
const inviteYourTeam = {
id: generateUID(),
userId,
teamId,
type: 'inviteYourTeam' as const,
priority: 2
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Avoid duplication of action creation.

The creation of the inviteYourTeam action is duplicated. Consider refactoring to avoid redundancy.

-  const inviteYourTeam = {
-    id: generateUID(),
-    userId,
-    teamId,
-    type: 'inviteYourTeam' as const,
-    priority: 2
-  }
+  const createInviteYourTeamAction = (userId, teamId) => ({
+    id: generateUID(),
+    userId,
+    teamId,
+    type: 'inviteYourTeam' as const,
+    priority: 2
+  })
+  const inviteYourTeam = createInviteYourTeamAction(userId, teamId)
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 inviteYourTeam = {
id: generateUID(),
userId,
teamId,
type: 'inviteYourTeam' as const,
priority: 2
}
const createInviteYourTeamAction = (userId, teamId) => ({
id: generateUID(),
userId,
teamId,
type: 'inviteYourTeam' as const,
priority: 2
})
const inviteYourTeam = createInviteYourTeamAction(userId, teamId)

Comment on lines 43 to 51
export async function down() {
const client = new Client(getPgConfig())
await client.connect()
await client.query(`
DROP TABLE "SuggestedAction";
DROP TYPE "SuggestedActionTypeEnum";
` /* Do undo magic */)
await client.end()
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Ensure proper error handling for the down migration.

The down migration should have proper error handling to catch and log any potential issues.

+ try {
    await client.query(`
      DROP TABLE "SuggestedAction";
      DROP TYPE "SuggestedActionTypeEnum";
    `)
+ } catch (error) {
+   console.error('Error dropping SuggestedAction table and type:', error)
+ }
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
export async function down() {
const client = new Client(getPgConfig())
await client.connect()
await client.query(`
DROP TABLE "SuggestedAction";
DROP TYPE "SuggestedActionTypeEnum";
` /* Do undo magic */)
await client.end()
}
export async function down() {
const client = new Client(getPgConfig())
await client.connect()
try {
await client.query(`
DROP TABLE "SuggestedAction";
DROP TYPE "SuggestedActionTypeEnum";
`)
} catch (error) {
console.error('Error dropping SuggestedAction table and type:', error)
}
await client.end()
}

Comment on lines 6 to 9
const toCreditCard = (creditCard: any) => {
if (!creditCard) return null
return sql<string>`(select json_populate_record(null::"CreditCard", ${JSON.stringify(creditCard)}))`
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Improve type safety for toCreditCard function.

Avoid using any type for creditCard parameter. Define a proper type for creditCard to ensure type safety.

type CreditCard = {
  // Define the properties of CreditCard here
  // Example:
  cardNumber: string;
  expiryDate: string;
  // Add other properties as needed
}

const toCreditCard = (creditCard: CreditCard | null) => {
  if (!creditCard) return null
  return sql<string>`(select json_populate_record(null::"CreditCard", ${JSON.stringify(creditCard)}))`
}

Comment on lines 87 to 93
export async function down() {
await connectRethinkDB()
try {
await r.table('SuggestedAction').indexDrop('createdAtId').run()
} catch {
// index already dropped
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Enhance error handling for index drop.

The catch block for index drop should log the error to provide more context.

-  } catch {
+  } catch (error) {
+    console.error('Error dropping index:', error)
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
export async function down() {
await connectRethinkDB()
try {
await r.table('SuggestedAction').indexDrop('createdAtId').run()
} catch {
// index already dropped
}
export async function down() {
await connectRethinkDB()
try {
await r.table('SuggestedAction').indexDrop('createdAtId').run()
} catch (error) {
console.error('Error dropping index:', error)
}

Comment on lines 66 to 80
await Promise.all(
rowsToInsert.map(async (row) => {
try {
await pg
.insertInto('SuggestedAction')
.values(row)
.onConflict((oc) => oc.doNothing())
.execute()
} catch (e) {
if (e.constraint === 'fk_userId' || e.constraint === 'fk_teamId') {
console.log(`Skipping ${row.id} because it has no user/team`)
return
}
console.log(e, row)
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Optimize error handling for individual row inserts.

The error handling for individual row inserts can be optimized by logging errors once and skipping rows with missing user/team in a single catch block.

-      await Promise.all(
-        rowsToInsert.map(async (row) => {
-          try {
-            await pg
-              .insertInto('SuggestedAction')
-              .values(row)
-              .onConflict((oc) => oc.doNothing())
-              .execute()
-          } catch (e) {
-            if (e.constraint === 'fk_userId' || e.constraint === 'fk_teamId') {
-              console.log(`Skipping ${row.id} because it has no user/team`)
-              return
-            }
-            console.log(e, row)
-          }
-        })
-      )
+      for (const row of rowsToInsert) {
+        try {
+          await pg
+            .insertInto('SuggestedAction')
+            .values(row)
+            .onConflict((oc) => oc.doNothing())
+            .execute()
+        } catch (e) {
+          if (e.constraint === 'fk_userId' || e.constraint === 'fk_teamId') {
+            console.log(`Skipping ${row.id} because it has no user/team`)
+          } else {
+            console.log(e, row)
+          }
+        }
+      }
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
await Promise.all(
rowsToInsert.map(async (row) => {
try {
await pg
.insertInto('SuggestedAction')
.values(row)
.onConflict((oc) => oc.doNothing())
.execute()
} catch (e) {
if (e.constraint === 'fk_userId' || e.constraint === 'fk_teamId') {
console.log(`Skipping ${row.id} because it has no user/team`)
return
}
console.log(e, row)
}
for (const row of rowsToInsert) {
try {
await pg
.insertInto('SuggestedAction')
.values(row)
.onConflict((oc) => oc.doNothing())
.execute()
} catch (e) {
if (e.constraint === 'fk_userId' || e.constraint === 'fk_teamId') {
console.log(`Skipping ${row.id} because it has no user/team`)
} else {
console.log(e, row)
}
}
}

Comment on lines 46 to 52
export async function down() {
const client = new Client(getPgConfig())
await client.connect()
await client.query(`
DROP TABLE IF EXISTS "EmailVerification";
`)
await client.end()
Copy link
Contributor

Choose a reason for hiding this comment

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

Ensure proper error handling for the down migration.

The down migration should have proper error handling to catch and log any potential issues.

+ try {
    await client.query(`
      DROP TABLE IF EXISTS "EmailVerification";
    `)
+ } catch (error) {
+   console.error('Error dropping EmailVerification table:', error)
+ }
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
export async function down() {
const client = new Client(getPgConfig())
await client.connect()
await client.query(`
DROP TABLE IF EXISTS "EmailVerification";
`)
await client.end()
export async function down() {
const client = new Client(getPgConfig())
await client.connect()
try {
await client.query(`
DROP TABLE IF EXISTS "EmailVerification";
`)
} catch (error) {
console.error('Error dropping EmailVerification table:', error)
}
await client.end()
}

Comment on lines 26 to 33
const pg = getKysely()
const verificationToken = (
await pg
.selectFrom('EmailVerification')
.select('token')
.where('email', '=', email)
.executeTakeFirstOrThrow(() => new Error(`No verification token found for ${email}`))
).token
Copy link
Contributor

Choose a reason for hiding this comment

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

Add error handling for database operations.

The function should handle potential errors when retrieving the verification token from PostgreSQL.

-  const verificationToken = (
-    await pg
-      .selectFrom('EmailVerification')
-      .select('token')
-      .where('email', '=', email)
-      .executeTakeFirstOrThrow(() => new Error(`No verification token found for ${email}`))
-  ).token
+  let verificationToken;
+  try {
+    verificationToken = (
+      await pg
+        .selectFrom('EmailVerification')
+        .select('token')
+        .where('email', '=', email)
+        .executeTakeFirstOrThrow(() => new Error(`No verification token found for ${email}`))
+    ).token;
+  } catch (error) {
+    console.error('Error retrieving verification token:', error);
+    throw error;
+  }
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 pg = getKysely()
const verificationToken = (
await pg
.selectFrom('EmailVerification')
.select('token')
.where('email', '=', email)
.executeTakeFirstOrThrow(() => new Error(`No verification token found for ${email}`))
).token
let verificationToken;
try {
verificationToken = (
await pg
.selectFrom('EmailVerification')
.select('token')
.where('email', '=', email)
.executeTakeFirstOrThrow(() => new Error(`No verification token found for ${email}`))
).token;
} catch (error) {
console.error('Error retrieving verification token:', error);
throw error;
}

Comment on lines 159 to 165
export const _suggestedActionsByUserId = foreignKeyLoaderMaker(
'_suggestedActions',
'userId',
async (userIds) => {
return selectSuggestedAction().where('userId', 'in', userIds).execute()
}
)
Copy link
Contributor

Choose a reason for hiding this comment

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

Add error handling for database operations.

The function should handle potential errors when querying the database for suggested actions.

-  async (userIds) => {
-    return selectSuggestedAction().where('userId', 'in', userIds).execute()
-  }
+  async (userIds) => {
+    try {
+      return await selectSuggestedAction().where('userId', 'in', userIds).execute();
+    } catch (error) {
+      console.error('Error retrieving suggested actions:', error);
+      throw error;
+    }
+  }
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
export const _suggestedActionsByUserId = foreignKeyLoaderMaker(
'_suggestedActions',
'userId',
async (userIds) => {
return selectSuggestedAction().where('userId', 'in', userIds).execute()
}
)
export const _suggestedActionsByUserId = foreignKeyLoaderMaker(
'_suggestedActions',
'userId',
async (userIds) => {
try {
return await selectSuggestedAction().where('userId', 'in', userIds).execute();
} catch (error) {
console.error('Error retrieving suggested actions:', error);
throw error;
}
}
)

@github-actions github-actions bot added size/m and removed size/l labels Aug 1, 2024
@mattkrick mattkrick merged commit 3bc68e0 into master Aug 2, 2024
7 checks passed
@mattkrick mattkrick deleted the chore/SuggestedAction-phase2 branch August 2, 2024 21:33
@github-actions github-actions bot mentioned this pull request Aug 2, 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