Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/delete-unlinked-mirrors.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@swirls/shuttle': minor
---

Shuttle's app now deletes an organization's Code Storage copy of a GitHub repository, with the work sessions saved there, as soon as none of its folders links the repository: when it is unlinked from its last folder, when its GitHub account is disconnected, when the GitHub App is uninstalled, and when the repository is taken out of what the App may access. For hosts: `@swirls/shuttle/git` adds `deleteCodeStorageRepo(client, repoName)`, and `normalizeWebhook` reads GitHub's `installation_repositories` `removed` delivery as a new kind, `installation.repos.removed`, with the `fullNames` removed, so a host that switches over `NormalizedWebhook` exhaustively has one more kind to handle. `@swirls/shuttle/react` adds `UnlinkRepoDialog` and `unlinkDeletesSavedWork(tree, folderId, repo)` for asking before an unlink that deletes saved work, and the GitHub access panel's disconnect dialog now says when it does.
42 changes: 37 additions & 5 deletions apps/web/src/routes/_app/folders.$folderId.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ import {
SignInGate,
StartAttachments,
startWorkspaceSession,
unlinkDeletesSavedWork,
UnlinkRepoDialog,
useAgentGate,
useDefaultHarness,
usePullInbox,
Expand Down Expand Up @@ -53,6 +55,8 @@ export const Route = createFileRoute('/_app/folders/$folderId')({
const DEMO_GOAL = 'Add a zod schema for greet() and cover it with a small test.'
const REPO_PREVIEW = 8

type LinkedRepo = WorkspaceFolder['repos'][number]

function FolderPage() {
const { folderId } = Route.useParams()
const workspace = useWorkspace()
Expand Down Expand Up @@ -125,9 +129,12 @@ function FolderWorkspace({ tree, folder }: { tree: WorkspaceTree; folder: Worksp

// The chip goes when the workspace's events say the repository is unlinked.
const unlinkRepo = useMutation(api.workspace.repos.unlink.mutationOptions())
// The repository an unlink is asking about, while its dialog is open.
const [unlinking, setUnlinking] = useState<LinkedRepo | null>(null)
const busy = startSession.isPending
// One line under the composer reports whichever of the two was tried last.
const error = startSession.error ?? unlinkRepo.error
// One line under the composer reports whichever of the two was tried last. An unlink that asked
// first reports in its dialog instead.
const error = startSession.error ?? (unlinking === null ? unlinkRepo.error : null)

function start() {
const trimmed = goal.trim()
Expand All @@ -147,9 +154,16 @@ function FolderWorkspace({ tree, folder }: { tree: WorkspaceTree; folder: Worksp
}
}

function unlink(repoId: string) {
function unlink(repo: LinkedRepo) {
startSession.reset()
unlinkRepo.mutate({ folderId: folder.folderId, repoId })
unlinkRepo.reset()

// Taking the last link away deletes Shuttle's copy and the work saved there, so it asks first.
if (unlinkDeletesSavedWork(tree, folder.folderId, repo)) {
setUnlinking(repo)
} else {
unlinkRepo.mutate({ folderId: folder.folderId, repoId: repo.id })
}
}

return (
Expand All @@ -176,7 +190,7 @@ function FolderWorkspace({ tree, folder }: { tree: WorkspaceTree; folder: Worksp
<RepoChip
key={repo.id}
repo={repo}
onRemove={folder.archived ? undefined : () => unlink(repo.id)}
onRemove={folder.archived ? undefined : () => unlink(repo)}
/>
))}
{hiddenRepos > 0 ? (
Expand Down Expand Up @@ -333,6 +347,24 @@ function FolderWorkspace({ tree, folder }: { tree: WorkspaceTree; folder: Worksp
tree={tree}
linked={folder.repos}
/>

{unlinking !== null ? (
<UnlinkRepoDialog
repo={unlinking}
pending={unlinkRepo.isPending}
error={unlinkRepo.error?.message ?? null}
onCancel={() => {
unlinkRepo.reset()
setUnlinking(null)
}}
onConfirm={() =>
unlinkRepo.mutate(
{ folderId: folder.folderId, repoId: unlinking.id },
{ onSuccess: () => setUnlinking(null) },
)
}
/>
) : null}
</div>
)
}
19 changes: 16 additions & 3 deletions apps/worker/src/api/workspace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ import { DEVICE_ID } from '@shuttle/runner-protocol'

import { getAuth } from '../auth/auth'
import type { ShuttleEnv } from '../env'
import { deleteMirrors, readFolderLinks, unlinkedMirrors } from '../github/repo-links'
import { GITHUB_NOT_CONNECTED, githubTokenOf } from '../github/user-token'
import { installationConnected } from '../tenancy/installations'
import { api, badRequest, notFound } from './base'
Expand Down Expand Up @@ -635,15 +636,27 @@ export const workspaceRouter = {
return { folderId, repo: linked }
}),

/**
* Unlinks a repository from a folder. If that was the organization's last link to it, its
* Code Storage mirror is deleted first, with the work sessions saved there: a mirror that
* cannot be deleted leaves the link in place, to be tried again.
*/
unlink: workspace.repos.unlink.handler(async ({ input, context: { env, actor } }) => {
const { orgId } = actor
const { folderId, repoId } = input

await ensureWorkspaceQuietly(env, orgId)

const tree = await readWorkspaceFolders(env, orgId)
const folder = tree.folders[folderId]
const repo = folder?.repos.find((item) => item.id === repoId)
const links = await readFolderLinks(env, orgId)
const link = links.find((item) => item.folderId === folderId && item.repo.id === repoId)
const repo = link?.repo
const fullName = repo === undefined ? null : githubFullName(repo)

if (fullName !== null) {
const kept = links.filter((item) => item !== link).map((item) => item.repo)

await deleteMirrors(env, unlinkedMirrors(orgId, [fullName], kept))
}

const stub = loomsStub(env.LOOMS_RUN, workspaceRunId(env, orgId))
await stub.signal([unlinkRepo({ folderId, repoId })])
Expand Down
160 changes: 94 additions & 66 deletions apps/worker/src/github/accounts.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,15 @@
import { z } from 'zod'

import { RepoRefZ } from '@shuttle/api'
import { githubFullName, githubOrigin, readRepoRef } from '@shuttle/core/repo-ref'
import { githubFullName, githubOrigin, type RepoRef } from '@shuttle/core/repo-ref'
import { ensureWorkspaceQuietly } from '@shuttle/engine/bootstrap'
import { workspaceRunId } from '@shuttle/engine/config'
import { loomsStub } from '@shuttle/engine/looms-stub'
import { connectGithub, disconnectGithub, unlinkRepo } from '@shuttle/engine/workspace/module'
import type { GithubAccount } from '@shuttle/git/github/client'
import type { EventInput } from '@swirls/looms/core'

import { syncRepoPolicy } from '../api/workspace'
import type { ShuttleEnv } from '../env'
import { connectInstallation, disconnectInstallation } from '../tenancy/installations'
import { deleteMirrors, readFolderLinks, unlinkedMirrors } from './repo-links'

/**
* Connecting a GitHub App installation to an organization, and taking it away again.
Expand Down Expand Up @@ -41,46 +40,19 @@ export async function connectAccount(
])
}

/** The repositories each folder links, read strictly: a tree that cannot be read is an error. */
const FoldersProjection = z.object({
value: z
.object({
folders: z
.record(
z.string(),
z.object({
// A `RepoRef`, or the record a link of an earlier release kept.
repos: z.array(
z.union([
RepoRefZ,
z.object({
installationId: z.number(),
owner: z.string(),
name: z.string(),
fullName: z.string(),
defaultBranch: z.string(),
private: z.boolean(),
}),
]),
),
}),
)
.optional(),
})
.nullish(),
})

/**
* Disconnects the installation from the organization, and unlinks its repositories from the
* organization's folders, which could no longer be reached. Returns what was unlinked.
* organization's folders, which could no longer be reached. The organization's Code Storage
* mirror of each goes too (`repo-links.ts`). Returns what was unlinked.
*
* The App stays installed on GitHub and other organizations keep their connection. Sessions
* already running hold the repositories they started with, and are left alone.
* already running hold the repositories they started with, and are left alone, but the work they
* saved on a deleted mirror is gone.
*
* The workspace is changed before the table, and the table row goes last, so a failure part of
* the way leaves the installation connected and the whole thing can be done again. Reading the
* folders must succeed: guessing "none" would disconnect the account and leave its
* repositories linked for good. A repository linked in the instant between the read and the
* The mirrors are deleted first, then the workspace is changed, and the table row goes last, so a
* failure part of the way leaves the installation connected and the whole thing can be done
* again. Reading the folders must succeed: guessing "none" would disconnect the account and leave
* its repositories linked for good. A repository linked in the instant between the read and the
* end is the one thing this misses; it stays linked until someone unlinks it.
*/
export async function disconnectAccount(
Expand All @@ -91,47 +63,103 @@ export async function disconnectAccount(
): Promise<UnlinkedRepo[]> {
await ensureWorkspaceQuietly(env, orgId)

const runId = workspaceRunId(env, orgId)
const stub = loomsStub(env.LOOMS_RUN, runId)

const response = await stub.fetch(
new Request(`https://shuttle.internal/runs/${runId}/projections/workspaceTree`),
const unlinked = await unlinkRepos(
env,
orgId,
(repo) => githubOrigin(repo)?.installationId === installationId,
[disconnectGithub({ installationId })],
)

if (!response.ok) {
throw new Error(`could not read the workspace's folders (${response.status})`)
}
await disconnectInstallation(db, installationId, orgId)
await followUnlinked(env, orgId, installationId, unlinked)

const folders = FoldersProjection.parse(await response.json()).value?.folders ?? {}
return unlinked
}

/**
* Unlinks the repositories named in `fullNames` (each `owner/name`) from the organization's
* folders, and deletes its mirror of each: GitHub says the App may no longer access them, so they
* could no longer be reached. The account stays connected. Returns what was unlinked.
*
* The mirror of a named repository that no folder links is deleted all the same, so a delivery
* sent again after a failure finishes what the first one started.
*/
export async function removeRepos(
env: ShuttleEnv,
orgId: string,
installationId: number,
fullNames: readonly string[],
): Promise<UnlinkedRepo[]> {
await ensureWorkspaceQuietly(env, orgId)

const linked = Object.entries(folders).flatMap(([folderId, folder]) =>
folder.repos.flatMap((persisted) => {
const repo = readRepoRef(persisted)
const removed = new Set(fullNames.map((fullName) => fullName.toLowerCase()))

return repo !== null && githubOrigin(repo)?.installationId === installationId
? [{ folderId, repoId: repo.id, fullName: githubFullName(repo) ?? repo.label }]
: []
}),
const unlinked = await unlinkRepos(
env,
orgId,
(repo) => removed.has(githubFullName(repo)?.toLowerCase() ?? ''),
[],
fullNames,
)

const unlinked: UnlinkedRepo[] = linked.map(({ folderId, fullName }) => ({ folderId, fullName }))
await followUnlinked(env, orgId, installationId, unlinked)

await stub.signal([
...linked.map(({ folderId, repoId }) => unlinkRepo({ folderId, repoId })),
disconnectGithub({ installationId }),
])
return unlinked
}

await disconnectInstallation(db, installationId, orgId)
/**
* Takes every link to a repository `gone` picks out of the organization's folders, with `also`
* signalled in the same step. The mirrors that leaves with no link, and those of `named`, are
* deleted first: if one cannot be, this throws with every link still in place.
*/
async function unlinkRepos(
env: ShuttleEnv,
orgId: string,
gone: (repo: RepoRef) => boolean,
also: readonly EventInput[],
named: readonly string[] = [],
): Promise<UnlinkedRepo[]> {
const links = await readFolderLinks(env, orgId)
const linked = links.filter(({ repo }) => githubOrigin(repo) !== null && gone(repo))
const kept = links.filter((link) => !linked.includes(link)).map(({ repo }) => repo)

const unlinked: UnlinkedRepo[] = linked.map(({ folderId, repo }) => ({
folderId,
fullName: githubFullName(repo) ?? repo.label,
}))

await deleteMirrors(
env,
unlinkedMirrors(orgId, [...named, ...unlinked.map((repo) => repo.fullName)], kept),
)

const signals = [
...linked.map(({ folderId, repo }) => unlinkRepo({ folderId, repoId: repo.id })),
...also,
]

if (signals.length > 0) {
await loomsStub(env.LOOMS_RUN, workspaceRunId(env, orgId)).signal(signals)
}

return unlinked
}

// With no folder left, the pull request inbox stops following each repository. The account
// is already disconnected, so a failure here is logged and not reported as one.
/**
* With no folder left, the pull request inbox stops following each repository. The links are
* already gone, so a failure here is logged and not reported as one.
*/
async function followUnlinked(
env: ShuttleEnv,
orgId: string,
installationId: number,
unlinked: readonly UnlinkedRepo[],
): Promise<void> {
for (const fullName of new Set(unlinked.map((repo) => repo.fullName))) {
try {
await syncRepoPolicy(env, orgId, fullName, installationId)
} catch (error) {
console.error('github disconnect: could not update the pull request inbox', fullName, error)
console.error('github: could not update the pull request inbox', fullName, error)
}
}

return unlinked
}
Loading
Loading