diff --git a/plugins/github/server/api/github.ts b/plugins/github/server/api/github.ts index 793be354b8..993b630b94 100644 --- a/plugins/github/server/api/github.ts +++ b/plugins/github/server/api/github.ts @@ -2,6 +2,7 @@ import Router from "koa-router"; import find from "lodash/find"; import { IntegrationService, IntegrationType } from "@shared/types"; import { parseDomain } from "@shared/utils/domains"; +import { createContext } from "@server/context"; import Logger from "@server/logging/Logger"; import auth from "@server/middlewares/authentication"; import { transaction } from "@server/middlewares/transaction"; @@ -88,30 +89,27 @@ router.get( }, { transaction } ); - await Integration.create( - { - service: IntegrationService.GitHub, - type: IntegrationType.Embed, - userId: user.id, - teamId: user.teamId, - authenticationId: authentication.id, - settings: { - github: { - installation: { - id: installationId!, - account: { - id: installation.account?.id, - name: - // @ts-expect-error Property 'login' does not exist on type - installation.account?.login, - avatarUrl: installation.account?.avatar_url, - }, + await Integration.createWithCtx(createContext({ user, transaction }), { + service: IntegrationService.GitHub, + type: IntegrationType.Embed, + userId: user.id, + teamId: user.teamId, + authenticationId: authentication.id, + settings: { + github: { + installation: { + id: installationId!, + account: { + id: installation.account?.id, + name: + // @ts-expect-error Property 'login' does not exist on type + installation.account?.login, + avatarUrl: installation.account?.avatar_url, }, }, }, }, - { transaction } - ); + }); ctx.redirect(GitHubUtils.url); } ); diff --git a/plugins/github/server/github.ts b/plugins/github/server/github.ts index 1767adbc1b..f5bb4a3f76 100644 --- a/plugins/github/server/github.ts +++ b/plugins/github/server/github.ts @@ -40,8 +40,8 @@ const requestPlugin = (octokit: Octokit) => ({ }, }), - requestRepos: async () => - octokit.request("GET /installation/repositories", { + requestRepos: () => + octokit.paginate(octokit.rest.apps.listReposAccessibleToInstallation, { headers: { Accept: "application/vnd.github+json", "X-GitHub-Api-Version": "2022-11-28", diff --git a/plugins/github/server/issue.ts b/plugins/github/server/issue.ts index 3d11870e04..283960a15e 100644 --- a/plugins/github/server/issue.ts +++ b/plugins/github/server/issue.ts @@ -1,30 +1,38 @@ +import { Endpoints } from "@octokit/types"; +import Logger from "@server/logging/Logger"; +import { Integration, User } from "@server/models"; +import { CreateIssueResponse, IssueProvider } from "@server/types"; import { IssueSource } from "@shared/schema"; import { IntegrationService, IntegrationType, UnfurlResourceType, } from "@shared/types"; -import Logger from "@server/logging/Logger"; -import { Integration, User } from "@server/models"; -import { CreateIssueResponse, IssueProvider } from "@server/types"; import { GitHub } from "./github"; +// This is needed to account for Octokit paginate response type mismatch. +type ReposForInstallation = + Endpoints["GET /installation/repositories"]["response"]["data"]["repositories"]; + export class GitHubIssueProvider { public static listRepos: IssueProvider["listSources"] = async ( - actor: User + integration: Integration ): Promise => { - const integrations = (await Integration.findAll({ - where: { - service: IntegrationService.GitHub, - teamId: actor.teamId, - }, - })) as Integration[]; - - const integrationRepos = await Promise.all( - integrations.map(async (integration) => this.getRepos(integration)) + const client = await GitHub.authenticateAsInstallation( + integration.settings.github!.installation.id ); - return integrationRepos.flat(); + const repos = + (await client.requestRepos()) as unknown as ReposForInstallation; + + const sources = repos.map((repo) => ({ + id: String(repo.id), + name: repo.name, + account: { id: String(repo.owner.id), name: repo.owner.login }, + service: IntegrationService.GitHub, + })); + + return sources; }; public static createIssue: IssueProvider["createIssue"] = async ( diff --git a/server/migrations/20250408192616-add-issueSources-to-integrations.js b/server/migrations/20250408192616-add-issueSources-to-integrations.js new file mode 100644 index 0000000000..69e2b5bd23 --- /dev/null +++ b/server/migrations/20250408192616-add-issueSources-to-integrations.js @@ -0,0 +1,15 @@ +"use strict"; + +/** @type {import('sequelize-cli').Migration} */ +module.exports = { + async up(queryInterface, Sequelize) { + queryInterface.addColumn("integrations", "issueSources", { + type: Sequelize.JSONB, + allowNull: true, + }); + }, + + async down(queryInterface, Sequelize) { + queryInterface.removeColumn("integrations", "issueSources"); + }, +}; diff --git a/server/models/Integration.ts b/server/models/Integration.ts index fc67a61969..9f52293d3e 100644 --- a/server/models/Integration.ts +++ b/server/models/Integration.ts @@ -13,6 +13,7 @@ import { IsIn, AfterDestroy, } from "sequelize-typescript"; +import { IssueSource } from "@shared/schema"; import { IntegrationType, IntegrationService } from "@shared/types"; import type { IntegrationSettings } from "@shared/types"; import Collection from "@server/models/Collection"; @@ -53,6 +54,9 @@ class Integration extends ParanoidModel< @Column(DataType.ARRAY(DataType.STRING)) events: string[]; + @Column(DataType.JSONB) + issueSources: IssueSource[] | null; + // associations @BelongsTo(() => User, "userId") diff --git a/server/queues/processors/IntegrationCreatedProcessor.ts b/server/queues/processors/IntegrationCreatedProcessor.ts index cdf5d7e0cb..2cdef25efd 100644 --- a/server/queues/processors/IntegrationCreatedProcessor.ts +++ b/server/queues/processors/IntegrationCreatedProcessor.ts @@ -3,6 +3,7 @@ import { Integration } from "@server/models"; import BaseProcessor from "@server/queues/processors/BaseProcessor"; import { IntegrationEvent, Event } from "@server/types"; import { CacheHelper } from "@server/utils/CacheHelper"; +import CacheIssueSourcesTask from "../tasks/CacheIssueSourcesTask"; export default class IntegrationCreatedProcessor extends BaseProcessor { static applicableEvents: Event["name"][] = ["integrations.create"]; @@ -18,6 +19,12 @@ export default class IntegrationCreatedProcessor extends BaseProcessor { return; } + // Store the available issue sources in the integration record. + await CacheIssueSourcesTask.schedule({ + integrationId: integration.id, + actorId: event.actorId, + }); + // Clear the cache of unfurled data for the team as it may be stale now. await CacheHelper.clearData(CacheHelper.getUnfurlKey(integration.teamId)); } diff --git a/server/queues/tasks/CacheIssueSourcesTask.ts b/server/queues/tasks/CacheIssueSourcesTask.ts new file mode 100644 index 0000000000..a17da902ca --- /dev/null +++ b/server/queues/tasks/CacheIssueSourcesTask.ts @@ -0,0 +1,39 @@ +import { Integration, User } from "@server/models"; +import { sequelize } from "@server/storage/database"; +import { Hook, PluginManager } from "@server/utils/PluginManager"; +import BaseTask from "./BaseTask"; + +const plugins = PluginManager.getHooks(Hook.IssueProvider); + +type Props = { + integrationId: string; + actorId: string; +}; + +export default class CacheIssueSourcesTask extends BaseTask { + async perform({ integrationId, actorId }: Props) { + await sequelize.transaction(async (transaction) => { + const [integration, actor] = await Promise.all([ + Integration.findByPk(integrationId, { + transaction, + lock: transaction.LOCK.UPDATE, + }), + User.findByPk(actorId), + ]); + if (!integration || !actor) { + return; + } + + const plugin = plugins.find( + (p) => p.value.service === integration.service + ); + if (!plugin) { + return; + } + + const sources = await plugin.value.provider.listSources(integration); + integration.issueSources = sources; + await integration.save({ transaction }); + }); + } +} diff --git a/server/routes/api/issues/issues.ts b/server/routes/api/issues/issues.ts index ea8630025e..7c0135d079 100644 --- a/server/routes/api/issues/issues.ts +++ b/server/routes/api/issues/issues.ts @@ -1,10 +1,12 @@ import { InternalError, InvalidRequestError } from "@server/errors"; import auth from "@server/middlewares/authentication"; import validate from "@server/middlewares/validate"; +import { Integration } from "@server/models"; import presentUnfurl from "@server/presenters/unfurl"; import { APIContext } from "@server/types"; import { CacheHelper } from "@server/utils/CacheHelper"; import { Hook, PluginManager } from "@server/utils/PluginManager"; +import { IssueSource } from "@shared/schema"; import { UserRole } from "@shared/types"; import Router from "koa-router"; import * as T from "./schema"; @@ -18,12 +20,17 @@ router.post( async (ctx: APIContext) => { const { user } = ctx.state.auth; - const sources = await Promise.all( - plugins.map((plugin) => plugin.value.provider.listSources(user)) - ); + const integrations = await Integration.findAll({ + attributes: ["issueSources"], + where: { teamId: user.teamId }, + }); + + const sources = integrations + .flatMap((integration) => integration.issueSources) + .filter(Boolean) as IssueSource[]; ctx.body = { - data: sources.flat(), + data: sources, }; } ); diff --git a/server/types.ts b/server/types.ts index 044ad20176..6e8c4d5233 100644 --- a/server/types.ts +++ b/server/types.ts @@ -11,6 +11,7 @@ import { JSONValue, UnfurlResourceType, ProsemirrorData, + IntegrationType, } from "@shared/types"; import { BaseSchema } from "@server/routes/api/schema"; import { AccountProvisionerResult } from "./commands/accountProvisioner"; @@ -589,7 +590,9 @@ export type UninstallSignature = (integration: Integration) => Promise; export type CreateIssueResponse = Unfurl & { cacheKey: string }; export type IssueProvider = { - listSources: (actor: User) => Promise; + listSources: ( + integration: Integration + ) => Promise; createIssue: ( title: string, source: IssueSource,