Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 364
db performance improvements and job resilience #200
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
Merged
Uh oh!
There was an error while loading. Please reload this page.
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
b8a9513
replace upsert with seperate create many and raw update many calls
msukkari 176d02e
add bulk repo status update and queue addition with priority
msukkari f9c0849
add support for managed redis
msukkari 372e3a4
add note for changing raw sql on schema change
msukkari 45dfd5b
Merge branch 'v3' into msukkarieh/perf
msukkari File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,12 +1,11 @@ | ||
| import { Connection, ConnectionSyncStatus, PrismaClient, Prisma } from "@sourcebot/db"; | ||
| import { Connection, ConnectionSyncStatus, PrismaClient, Prisma, Repo } from "@sourcebot/db"; | ||
| import { Job, Queue, Worker } from 'bullmq'; | ||
| import { Settings, WithRequired } from "./types.js"; | ||
| import { ConnectionConfig } from "@sourcebot/schemas/v3/connection.type"; | ||
| import { createLogger } from "./logger.js"; | ||
| import os from 'os'; | ||
| import { Redis } from 'ioredis'; | ||
| import { RepoData, compileGithubConfig, compileGitlabConfig, compileGiteaConfig, compileGerritConfig } from "./repoCompileUtils.js"; | ||
| import { CONFIG_REPO_UPSERT_TIMEOUT_MS } from "./environment.js"; | ||
| interface IConnectionManager { | ||
| scheduleConnectionSync: (connection: Connection) => Promise<void>; | ||
| @@ -23,15 +22,18 @@ type JobPayload = { | ||
| }; | ||
| export class ConnectionManager implements IConnectionManager { | ||
| private queue = new Queue<JobPayload>(QUEUE_NAME); | ||
| private worker: Worker; | ||
| private queue: Queue<JobPayload>; | ||
| private logger = createLogger('ConnectionManager'); | ||
| constructor( | ||
| private db: PrismaClient, | ||
| private settings: Settings, | ||
| redis: Redis, | ||
| ) { | ||
| this.queue = new Queue<JobPayload>(QUEUE_NAME, { | ||
| connection: redis, | ||
| }); | ||
| const numCores = os.cpus().length; | ||
| this.worker = new Worker(QUEUE_NAME, this.runSyncJob.bind(this), { | ||
| connection: redis, | ||
| @@ -113,6 +115,7 @@ export class ConnectionManager implements IConnectionManager { | ||
| // appear in the repoData array above, and so the RepoToConnection record won't be re-created. | ||
| // Repos that have no RepoToConnection records are considered orphaned and can be deleted. | ||
| await this.db.$transaction(async (tx) => { | ||
| const deleteStart = performance.now(); | ||
| await tx.connection.update({ | ||
| where: { | ||
| id: job.data.connectionId, | ||
| @@ -123,21 +126,124 @@ export class ConnectionManager implements IConnectionManager { | ||
| } | ||
| } | ||
| }); | ||
| const deleteDuration = performance.now() - deleteStart; | ||
| this.logger.info(`Deleted all RepoToConnection records for connection ${job.data.connectionId} in ${deleteDuration}ms`); | ||
| await Promise.all(repoData.map((repo) => { | ||
| return tx.repo.upsert({ | ||
| where: { | ||
| external_id_external_codeHostUrl: { | ||
| external_id: repo.external_id, | ||
| external_codeHostUrl: repo.external_codeHostUrl, | ||
| }, | ||
| const existingRepos: Repo[] = await tx.repo.findMany({ | ||
| where: { | ||
| external_id: { | ||
| in: repoData.map(repo => repo.external_id), | ||
| }, | ||
| create: repo, | ||
| update: repo as Prisma.RepoUpdateInput, | ||
| external_codeHostUrl: { | ||
| in: repoData.map(repo => repo.external_codeHostUrl), | ||
| }, | ||
| }, | ||
| }); | ||
| const existingRepoKeys = existingRepos.map(repo => `${repo.external_id}-${repo.external_codeHostUrl}`); | ||
| const existingRepoData = repoData.filter(repo => existingRepoKeys.includes(`${repo.external_id}-${repo.external_codeHostUrl}`)); | ||
| const [toCreate, toUpdate] = repoData.reduce<[Prisma.RepoCreateManyInput[], Prisma.RepoUpdateManyMutationInput[]]>(([toCreate, toUpdate], repo) => { | ||
| const existingRepo = existingRepoData.find((r: RepoData) => r.external_id === repo.external_id && r.external_codeHostUrl === repo.external_codeHostUrl); | ||
| if (existingRepo) { | ||
| // @note: make sure to reflect any changes here in the raw sql update below | ||
| const updateRepo: Prisma.RepoUpdateManyMutationInput = { | ||
msukkari marked this conversation as resolved.
Uh oh!There was an error while loading. Please reload this page. | ||
| name: repo.name, | ||
| cloneUrl: repo.cloneUrl, | ||
| imageUrl: repo.imageUrl, | ||
| isFork: repo.isFork, | ||
| isArchived: repo.isArchived, | ||
| metadata: repo.metadata, | ||
| external_id: repo.external_id, | ||
| external_codeHostType: repo.external_codeHostType, | ||
| external_codeHostUrl: repo.external_codeHostUrl, | ||
| } | ||
| toUpdate.push(updateRepo); | ||
| } else { | ||
| const createRepo: Prisma.RepoCreateManyInput = { | ||
| name: repo.name, | ||
| cloneUrl: repo.cloneUrl, | ||
| imageUrl: repo.imageUrl, | ||
| isFork: repo.isFork, | ||
| isArchived: repo.isArchived, | ||
| metadata: repo.metadata, | ||
| orgId: job.data.orgId, | ||
| external_id: repo.external_id, | ||
| external_codeHostType: repo.external_codeHostType, | ||
| external_codeHostUrl: repo.external_codeHostUrl, | ||
| } | ||
| toCreate.push(createRepo); | ||
| } | ||
| return [toCreate, toUpdate]; | ||
| }, [[], []]); | ||
| if (toCreate.length > 0) { | ||
| const createStart = performance.now(); | ||
| const createdRepos = await tx.repo.createManyAndReturn({ | ||
| data: toCreate, | ||
| }); | ||
| })); | ||
| }, { timeout: parseInt(CONFIG_REPO_UPSERT_TIMEOUT_MS) }); | ||
| await tx.repoToConnection.createMany({ | ||
| data: createdRepos.map(repo => ({ | ||
| repoId: repo.id, | ||
| connectionId: job.data.connectionId, | ||
| })), | ||
| }); | ||
| const createDuration = performance.now() - createStart; | ||
| this.logger.info(`Created ${toCreate.length} repos in ${createDuration}ms`); | ||
| } | ||
| if (toUpdate.length > 0) { | ||
| const updateStart = performance.now(); | ||
| // Build values string for update query | ||
| const updateValues = toUpdate.map(repo => `( | ||
| '${repo.name}', | ||
| '${repo.cloneUrl}', | ||
| ${repo.imageUrl ? `'${repo.imageUrl}'` : 'NULL'}, | ||
| ${repo.isFork}, | ||
| ${repo.isArchived}, | ||
| '${JSON.stringify(repo.metadata)}'::jsonb, | ||
| '${repo.external_id}', | ||
| '${repo.external_codeHostType}', | ||
| '${repo.external_codeHostUrl}' | ||
| )`).join(','); | ||
| // Update repos and get their IDs in one quercy | ||
| const updateSql = ` | ||
| WITH updated AS ( | ||
| UPDATE "Repo" r | ||
| SET | ||
| name = v.name, | ||
| "cloneUrl" = v.clone_url, | ||
| "imageUrl" = v.image_url, | ||
| "isFork" = v.is_fork, | ||
| "isArchived" = v.is_archived, | ||
| metadata = v.metadata, | ||
| "updatedAt" = NOW() | ||
| FROM ( | ||
| VALUES ${updateValues} | ||
| ) AS v(name, clone_url, image_url, is_fork, is_archived, metadata, external_id, external_code_host_type, external_code_host_url) | ||
| WHERE r.external_id = v.external_id | ||
| AND r."external_codeHostUrl" = v.external_code_host_url | ||
| RETURNING r.id | ||
| ) | ||
| SELECT id FROM updated | ||
| `; | ||
| const updatedRepoIds = await tx.$queryRawUnsafe<{id: number}[]>(updateSql); | ||
| // Insert repo-connection mappings | ||
| const createConnectionSql = ` | ||
| INSERT INTO "RepoToConnection" ("repoId", "connectionId", "addedAt") | ||
| SELECT id, ${job.data.connectionId}, NOW() | ||
| FROM unnest(ARRAY[${updatedRepoIds.map(r => r.id).join(',')}]) AS id | ||
| `; | ||
| await tx.$executeRawUnsafe(createConnectionSql); | ||
| const updateDuration = performance.now() - updateStart; | ||
| this.logger.info(`Updated ${toUpdate.length} repos in ${updateDuration}ms`); | ||
| } | ||
| }); | ||
msukkari marked this conversation as resolved.
Uh oh!There was an error while loading. Please reload this page. | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.