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: migrate EmailVerification to pg #9492

Merged
merged 4 commits into from
Jul 25, 2024

Conversation

jordanh
Copy link
Contributor

@jordanh jordanh commented Mar 2, 2024

Description

Resolves #9491

Testing scenarios

  • Migrations

    • Migrate up 2, inspect EmailVerification on pg
    • Migrate down 2, verify pg table is destroyed and rethinkdb unchanged
  • Can verify email address with token

Final checklist

  • I checked the code review guidelines
  • I have added Metrics Representative as reviewer(s) if my PR invovles metrics/data/analytics related changes
  • I have performed a self-review of my code, the same way I'd do it for any other team member
  • I have tested all cases I listed in the testing scenarios and I haven't found any issues or regressions
  • Whenever I took a non-obvious choice I added a comment explaining why I did it this way
  • I added the label Skip Maintainer Review Indicating the PR only requires reviewer review and can be merged right after it's approved if the PR introduces only minor changes, does not contain any architectural changes or does not introduce any new patterns and I think one review is sufficient'
  • PR title is human readable and could be used in changelog

Summary by CodeRabbit

  • New Features
    • Transitioned email verification processes from RethinkDB to PostgreSQL for improved performance and reliability.
    • Introduced a new migration for managing the "EmailVerification" table in PostgreSQL, enhancing data management capabilities.
  • Bug Fixes
    • Improved error handling and data integrity for email verification and sign-up processes.

@jordanh jordanh requested a review from mattkrick March 2, 2024 06:34
@github-actions github-actions bot requested a review from tghanken March 2, 2024 06:34
@github-actions github-actions bot added the size/m label Mar 2, 2024
@jordanh
Copy link
Contributor Author

jordanh commented Mar 2, 2024

Sasha fell asleep early, and I felt itchy

@@ -55,9 +57,9 @@ const signUpVerified = async (email: string) => {
expect(verifyEmail).toMatchObject({
data: {
verifyEmail: {
authToken: expect.toBeString(),
Copy link
Contributor Author

Choose a reason for hiding this comment

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

I was getting TS failures here

@@ -153,7 +155,7 @@ test.skip('autoJoin on multiple teams does not create duplicate `OrganizationUse
const newEmail = `${faker.internet.userName()}@${domain}`.toLowerCase()
const {user: newUser} = await signUpVerified(newEmail)

expect(newUser.tms).toIncludeSameMembers(teamIds)
expect(newUser.tms).toEqual(expect.arrayContaining(teamIds))
Copy link
Contributor Author

Choose a reason for hiding this comment

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

and here...

@@ -12,16 +10,14 @@ interface Input {
}

export default class EmailVerification {
id: string
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Once again, id is now managed by PG

@jordanh jordanh force-pushed the chore/9491/migrate-emailverification branch from d67de35 to 98755f9 Compare March 3, 2024 17:55
.selectFrom('EmailVerification')
.selectAll()
.where('token', '=', verificationToken)
.executeTakeFirst()) as EmailVerification) || null
Copy link
Member

Choose a reason for hiding this comment

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

+1 no need to coerce to EmailVerification || null since kysely knows the return type

Copy link
Contributor

coderabbitai bot commented Jul 25, 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 0 minutes and 10 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 d171d43 and d30454c.

Walkthrough

The changes encompass a migration of the EmailVerification functionality from RethinkDB to PostgreSQL. This transition involves updating various components to interact with the new database technology, enhancing the reliability and clarity of the email verification process while maintaining existing logic. The updates include revised database queries, changes in data handling, and the introduction of migration scripts for effective data management.

Changes

Files Change Summary
packages/server/__tests__/autoJoin.test.ts, packages/server/email/createEmailVerification.ts, packages/server/email/createEmailVerficationForExistingUser.ts, packages/server/graphql/public/mutations/signUpWithPassword.ts, packages/server/graphql/public/mutations/verifyEmail.ts Transitioned from RethinkDB to PostgreSQL for various functionalities, updating query syntax and connection handling to enhance email verification processes.
packages/server/database/types/EmailVerification.ts Updated Input interface and EmailVerification class by removing the id property, simplifying instance creation.
packages/server/postgres/migrations/1709351538000_addEmailVerification.ts, packages/server/postgres/migrations/1709351575000_moveEmailVerification.ts, packages/server/postgres/migrations/1721868364099_addEmailVerification.ts Introduced migration scripts to create the EmailVerification table in PostgreSQL and transfer data from RethinkDB, ensuring proper indexing and batch processing.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Server
    participant Database

    User->>Server: Sign Up Request
    Server->>Database: Check Email Verifications
    Database-->>Server: Return Verification Status
    Server->>Database: Insert New User
    Database-->>Server: Confirm User Insertion
    Server-->>User: Send Confirmation Email
Loading

Assessment against linked issues

Objective Addressed Explanation
All future table operations interact with pg (9491)
Existing data migrated from rethink to pg (9491)

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

Outside diff range, codebase verification and nitpick comments (2)
packages/server/postgres/migrations/1709351575000_moveEmailVerification.ts (2)

8-66: up function approved with a suggestion.

The function correctly handles the migration of data from RethinkDB to PostgreSQL.

Consider adding logging to improve traceability and debugging.

+  console.log('Starting migration of EmailVerification data');
+  console.log('Creating indexes in RethinkDB');
+  console.log('Fetching data in batches from RethinkDB');
+  console.log('Inserting data into PostgreSQL');
+  console.log('Migration completed successfully');

68-76: down function approved with a suggestion.

The function correctly handles the rollback of migration.

Consider adding logging to improve traceability and debugging.

+  console.log('Starting rollback of EmailVerification migration');
+  console.log('Deleting data from PostgreSQL');
+  console.log('Dropping indexes in RethinkDB');
+  console.log('Rollback completed successfully');

Signed-off-by: Matt Krick <[email protected]>
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, codebase verification and nitpick comments (1)
packages/server/email/createEmailVerification.ts (1)

Update Required: Function Call Mismatch

The function createEmailVerification is called with incorrect parameters in autoJoin.test.ts. The new implementation expects password, invitationToken, pseudoId, and redirectTo, but the test file only provides email and password.

  • File: packages/server/__tests__/autoJoin.test.ts
  • Line: await createEmailVerification({email, password})

Please update the test file to match the new function signature.

Analysis chain

Line range hint 15-18:
LGTM! But verify the function usage in the codebase.

The code changes are approved.

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

Scripts executed

The following scripts were executed for the analysis:

Script:

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

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

Length of output: 3179

Comment on lines +38 to +49
const pg = getKysely()
await pg
.insertInto('EmailVerification')
.values({
email,
token: verifiedEmailToken,
hashedPassword,
pseudoId,
invitationToken,
expiration: new Date(Date.now() + Threshold.EMAIL_VERIFICATION_LIFESPAN)
})
.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 database operations.

The insertion operation should handle potential errors to avoid unhandled promise rejections.

-  await pg
+  try {
+    await pg
     .insertInto('EmailVerification')
     .values({
       email,
       token: verifiedEmailToken,
       hashedPassword,
       pseudoId,
       invitationToken,
       expiration: new Date(Date.now() + Threshold.EMAIL_VERIFICATION_LIFESPAN)
     })
     .execute()
+  } catch (error) {
+    return {error: {message: 'Database error: Unable to save verification data'}}
+  }
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()
await pg
.insertInto('EmailVerification')
.values({
email,
token: verifiedEmailToken,
hashedPassword,
pseudoId,
invitationToken,
expiration: new Date(Date.now() + Threshold.EMAIL_VERIFICATION_LIFESPAN)
})
.execute()
const pg = getKysely()
try {
await pg
.insertInto('EmailVerification')
.values({
email,
token: verifiedEmailToken,
hashedPassword,
pseudoId,
invitationToken,
expiration: new Date(Date.now() + Threshold.EMAIL_VERIFICATION_LIFESPAN)
})
.execute()
} catch (error) {
return {error: {message: 'Database error: Unable to save verification data'}}
}

Comment on lines +45 to +51
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 database operations.

The table drop operation should handle potential errors to avoid unhandled promise rejections.

-  const client = new Client(getPgConfig())
-  await client.connect()
-  await client.query(`
-    DROP TABLE IF EXISTS "EmailVerification";
-  `)
-  await client.end()
+  const client = new Client(getPgConfig())
+  try {
+    await client.connect()
+    await client.query(`
+      DROP TABLE IF EXISTS "EmailVerification";
+    `)
+  } catch (error) {
+    console.error('Database error:', error)
+    throw error
+  } finally {
+    await client.end()
+  }
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())
try {
await client.connect()
await client.query(`
DROP TABLE IF EXISTS "EmailVerification";
`)
} catch (error) {
console.error('Database error:', error)
throw error
} finally {
await client.end()
}
}

Comment on lines +8 to +28
export async function up() {
await connectRethinkDB()
const pg = new Kysely<any>({
dialect: new PostgresDialect({
pool: getPg()
})
})
await sql`
CREATE TABLE "EmailVerification" (
"id" INT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
"email" "citext" NOT NULL,
"expiration" TIMESTAMP WITH TIME ZONE NOT NULL,
"token" VARCHAR(100) NOT NULL,
"hashedPassword" VARCHAR(100),
"invitationToken" VARCHAR(100),
"pseudoId" VARCHAR(100)
);

CREATE INDEX IF NOT EXISTS "idx_EmailVerification_email" ON "EmailVerification"("email");
CREATE INDEX IF NOT EXISTS "idx_EmailVerification_token" ON "EmailVerification"("token");
`.execute(pg)
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 database operations.

The table creation and data migration operations should handle potential errors to avoid unhandled promise rejections.

-  await connectRethinkDB()
-  const pg = new Kysely<any>({
-    dialect: new PostgresDialect({
-      pool: getPg()
-    })
-  })
-  await sql`
-    CREATE TABLE "EmailVerification" (
-      "id" INT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
-      "email" "citext" NOT NULL,
-      "expiration" TIMESTAMP WITH TIME ZONE NOT NULL,
-      "token" VARCHAR(100) NOT NULL,
-      "hashedPassword" VARCHAR(100),
-      "invitationToken" VARCHAR(100),
-      "pseudoId" VARCHAR(100)
-    );
-    CREATE INDEX IF NOT EXISTS "idx_EmailVerification_email" ON "EmailVerification"("email");
-    CREATE INDEX IF NOT EXISTS "idx_EmailVerification_token" ON "EmailVerification"("token");
-  `.execute(pg)
-  const rData = await r.table('EmailVerification').coerceTo('array').run()
-  const insertData = rData.map((row) => {
-    const {email, expiration, hashedPassword, token, invitationToken, pseudoId} = row
-    return {
-      email,
-      expiration,
-      hashedPassword,
-      token,
-      invitationToken,
-      pseudoId
-    }
-  })
-  await pg.insertInto('EmailVerification').values(insertData).execute()
+  try {
+    await connectRethinkDB()
+    const pg = new Kysely<any>({
+      dialect: new PostgresDialect({
+        pool: getPg()
+      })
+    })
+    await sql`
+      CREATE TABLE "EmailVerification" (
+        "id" INT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
+        "email" "citext" NOT NULL,
+        "expiration" TIMESTAMP WITH TIME ZONE NOT NULL,
+        "token" VARCHAR(100) NOT NULL,
+        "hashedPassword" VARCHAR(100),
+        "invitationToken" VARCHAR(100),
+        "pseudoId" VARCHAR(100)
+      );
+      CREATE INDEX IF NOT EXISTS "idx_EmailVerification_email" ON "EmailVerification"("email");
+      CREATE INDEX IF NOT EXISTS "idx_EmailVerification_token" ON "EmailVerification"("token");
+    `.execute(pg)
+    const rData = await r.table('EmailVerification').coerceTo('array').run()
+    const insertData = rData.map((row) => {
+      const {email, expiration, hashedPassword, token, invitationToken, pseudoId} = row
+      return {
+        email,
+        expiration,
+        hashedPassword,
+        token,
+        invitationToken,
+        pseudoId
+      }
+    })
+    await pg.insertInto('EmailVerification').values(insertData).execute()
+  } catch (error) {
+    console.error('Database error:', 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 async function up() {
await connectRethinkDB()
const pg = new Kysely<any>({
dialect: new PostgresDialect({
pool: getPg()
})
})
await sql`
CREATE TABLE "EmailVerification" (
"id" INT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
"email" "citext" NOT NULL,
"expiration" TIMESTAMP WITH TIME ZONE NOT NULL,
"token" VARCHAR(100) NOT NULL,
"hashedPassword" VARCHAR(100),
"invitationToken" VARCHAR(100),
"pseudoId" VARCHAR(100)
);
CREATE INDEX IF NOT EXISTS "idx_EmailVerification_email" ON "EmailVerification"("email");
CREATE INDEX IF NOT EXISTS "idx_EmailVerification_token" ON "EmailVerification"("token");
`.execute(pg)
export async function up() {
try {
await connectRethinkDB()
const pg = new Kysely<any>({
dialect: new PostgresDialect({
pool: getPg()
})
})
await sql`
CREATE TABLE "EmailVerification" (
"id" INT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
"email" "citext" NOT NULL,
"expiration" TIMESTAMP WITH TIME ZONE NOT NULL,
"token" VARCHAR(100) NOT NULL,
"hashedPassword" VARCHAR(100),
"invitationToken" VARCHAR(100),
"pseudoId" VARCHAR(100)
);
CREATE INDEX IF NOT EXISTS "idx_EmailVerification_email" ON "EmailVerification"("email");
CREATE INDEX IF NOT EXISTS "idx_EmailVerification_token" ON "EmailVerification"("token");
`.execute(pg)
const rData = await r.table('EmailVerification').coerceTo('array').run()
const insertData = rData.map((row) => {
const {email, expiration, hashedPassword, token, invitationToken, pseudoId} = row
return {
email,
expiration,
hashedPassword,
token,
invitationToken,
pseudoId
}
})
await pg.insertInto('EmailVerification').values(insertData).execute()
} catch (error) {
console.error('Database error:', error)
throw error
}
}

Comment on lines +18 to +24
const pg = getKysely()
const now = new Date()
const emailVerification = (await r
.table('EmailVerification')
.getAll(verificationToken, {index: 'token'})
.nth(0)
.default(null)
.run()) as EmailVerification
const emailVerification = await pg
.selectFrom('EmailVerification')
.selectAll()
.where('token', '=', verificationToken)
.executeTakeFirst()
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 database operations.

The database query operation should handle potential errors to avoid unhandled promise rejections.

-  const emailVerification = await pg
-    .selectFrom('EmailVerification')
-    .selectAll()
-    .where('token', '=', verificationToken)
-    .executeTakeFirst()
+  let emailVerification
+  try {
+    emailVerification = await pg
+      .selectFrom('EmailVerification')
+      .selectAll()
+      .where('token', '=', verificationToken)
+      .executeTakeFirst()
+  } catch (error) {
+    return {error: {message: 'Database error: Unable to verify email'}}
+  }
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 now = new Date()
const emailVerification = (await r
.table('EmailVerification')
.getAll(verificationToken, {index: 'token'})
.nth(0)
.default(null)
.run()) as EmailVerification
const emailVerification = await pg
.selectFrom('EmailVerification')
.selectAll()
.where('token', '=', verificationToken)
.executeTakeFirst()
const pg = getKysely()
const now = new Date()
let emailVerification
try {
emailVerification = await pg
.selectFrom('EmailVerification')
.selectAll()
.where('token', '=', verificationToken)
.executeTakeFirst()
} catch (error) {
return {error: {message: 'Database error: Unable to verify email'}}
}

Signed-off-by: Matt Krick <[email protected]>
@mattkrick mattkrick merged commit a653a61 into master Jul 25, 2024
7 checks passed
@mattkrick mattkrick deleted the chore/9491/migrate-emailverification branch July 25, 2024 20:50
@github-actions github-actions bot mentioned this pull request Jul 26, 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.

chore: migrate EmailVerification to pg (1/1)
2 participants