Files
deepseek-harness/packages/experimental/forge-gitlab/src/provider.ts
T
LegGasai cb44a3c2ee feat(forge): read, review, and bind GitLab merge requests (#8317)
* feat(forge): let providers declare their hosts, names, sign-in, and review decisions

Prepare the forge contract for a second provider:

- ForgeProvider lists the hosts it serves and names itself (label,
  changeRequestNoun); registering a provider that lists a host another
  registered provider lists throws, so each URL has at most one provider.
  ctx.forge.describe(forge) returns the family's ForgeDescription.
- ForgeReadiness carries the sign-in command, which the panel's sign-in
  banner shows instead of building `gh auth login` for the github family.
- ForgeReviewData lists the review decisions the host lets the reader
  record; the review dialog offers only those instead of hardcoding the
  GitHub rule that a pull request's author may only comment.
- ForgeReviewThread.original may name a later commit the host carried the
  thread to while its lines stayed unchanged.
- The changes view names the code host and its word for a change request
  from the entry's ForgeDescription instead of hardcoding GitHub and PR.

The GitHub provider declares its configured hosts, GitHub, pull requests,
`gh auth login --hostname <host>`, and reads viewerDidAuthor for the
review decisions. Upgrade guide: forge-provider-hosts.

* feat(forge-gitlab): read GitLab merge requests through the GitLab CLI

Add the experimental forge-gitlab provider. It serves the configured
GitLab hosts through glab: status batches over GraphQL, head-pinned
patches from merge request diff versions, commit listings, merge bases,
pipeline jobs, closing issues, and review threads mapped from REST
discussions, including outdated threads' hunks.

The forge bundle composes the provider, disabled by default.

* feat(forge-gitlab): write GitLab reviews, retry pipelines, request reviews, and rebase

The GitLab provider now writes through glab as well as reading:
comments start discussions at positions derived from the head's diff
version, pending replies and comments are draft notes that a review
publishes with its summary and review state, and approving checks the
head through GitLab's sha parameter. Review reads carry the signed-in
user's rights from GraphQL, their draft notes as the pending review,
and the decisions GitLab lets them record.

Snapshots name the head pipeline as every job's rerun, offer rebase as
the branch update, and follow GitLab's permissions for reruns and
review requests. updateBranch's contract now states how a provider
whose host takes no expected head checks it.

* feat(forge): let forge providers register the commands that bind change requests

forge-session no longer recognizes gh commands by itself. A provider now
registers a declarative ForgeCommandRule through
ctx.forgeSession.registerCommands: its executable, creation and reference
subcommands, change request page path, JSON URL members, declared
options, and a pure select that maps one parsed reference command to a
URL or a read-only lookup. forge-github registers gh and forge-gitlab
registers glab, which adds glab mr create, view, update, and checkout,
including numbers with -R: a full project URL binds directly, and other
repository forms resolve through glab mr view in the call's shell.

forge-session keeps the shared parts: the literal shell tokenizer,
option parsing, output reading, lookups, and the projection. The
forgeChangeRequests state version derives from the recognized rules, so
a changed rule set refolds every Session, including commands that ran
before the provider loaded. Ending a registration keeps its rule
recognized until restart, so unloading providers at shutdown does not
rewrite every checkpoint.

* refactor(forge-gitlab): publish the GitLab provider as @deepseek-ai/dsh-forge-gitlab

New experimental packages omit the experimental prefix so that promotion
keeps their npm name. Register the directory in
EXPERIMENTAL_PACKAGE_NAME_EXCEPTIONS instead of growing the legacy
prefixed list, and rename every dependency, configuration row, path
mapping, and document that names the package.

* fix(forge-gitlab): keep review writes, comment positions, and reads within GitLab's facts and the limits

- After GitLab refuses a publication, read the drafts again: delete
  them only when all remain, since GitLab can publish them before it
  refuses the summary, and report the outcome as unknown otherwise.
  A rollback that leaves drafts reports how many may remain.
- Place comments on files GitLab collapsed through the diff compared
  from their texts, and let a file's new path name it over another
  file's old path after chained renames.
- Keep the final newline of raw file reads.
- Apply maxOutputBytes to the complete review result, and report a
  read whose rights stop early or skip a discussion's later notes as
  truncated.
- Serve a version over maxCachedVersionBytes without keeping it.
- Resolve uploaded avatars GitLab names by their path on the host.
- Schedule bounded reads through p-limit.

* fix(forge-session): run lookups only for live command rules and keep the projection registered

- Reference lookups use the rules of live registrations, so a disposed
  provider's rule still folds but starts no gh or glab process.
- A failed re-registration registers the projection again with the
  earlier rules, so clients keep its view; an error is logged only when
  that fails too.
- Document the startup re-registration, test that the checkpointed
  state version survives a real Loader start, shutdown, and restart,
  and record that starting without a provider removes the bindings only
  its commands made.
- Describe the changes view's pending review and single comment
  without naming GitHub, which keeps its own rule in forge-github, and
  render registerCommands as code in the generated service reference.

* fix(forge-bundle): name GitLab merge requests in the bundle description

The bundle now follows GitLab merge requests as well as GitHub pull
requests, so the description's first sentence in every locale names
both kinds of change request.

* feat(forge): bind the change requests that gh api and glab api requests name

Models often read a merge request through `glab api` or a pull request
through `gh api` instead of `glab mr view` or `gh pr view`, which left
the change request unbound. A command rule now declares raw API request
subcommands beside its reference subcommands, each group with its own
options, since `-f` is a value of `gh api` and a flag of
`gh pr checkout`.

An API request binds, as referenced, only the change request its REST
path names, such as `projects/group%2Fapp/merge_requests/7/changes` or
`repos/octo/demo/pulls/7/files`; its output is not read, since one
request can list many change requests. A path whose host the command
names binds directly, and one without a host, or with the current
repository's placeholders, resolves through the CLI's view command in
the call's shell. The gh and glab rules move to version 2.

* docs(forge): add forge-gitlab and the forge-session peers to the module graph

Regenerate docs/module-graph for the renamed GitLab provider and the
optional forge-session peer of both providers.

* test(web): refresh the forge bundle description in the recommended plugin catalog

The creation recommendation recording carries every recommended
plugin's description; refresh it for the forge bundle description that
now names GitLab merge requests and the glab sign-in.

* chore(forge-gitlab): carry the 0.2.2-rc.3 release version and move upgrade guides to v0.2.2-rc.3
2026-11-13 07:56:57 +00:00

478 lines
25 KiB
TypeScript

/** GitLab implementation of the forge provider contract, read and written through the GitLab CLI on the host. */
import { changeRequestKey } from '@deepseek-ai/dsh-experimental-forge'
import type {
BranchUpdateRequest, ChangeRequestIssue, ChangeRequestKey, ChangeRequestRef, ChangeRequestSnapshot, ForgeActionFailure, ForgeCommitList,
ForgeFailure, ForgeProvider, ForgeReadiness, ForgeRepository, ForgeRerunRequest, ForgeReviewData, ForgeReviewerCandidate,
ForgeReviewersRequest, ForgeReviewRequest, ForgeReviewResult, ForgeReviewWrite, ForgeReviewWriteResult, MergeRequest,
} from '@deepseek-ai/dsh-experimental-forge'
import { z } from 'zod'
import { GitLabApi } from './api.ts'
import { readCommits } from './commits.ts'
import { comparePatch, fileTextOf, isCommit, mergeBaseOf, newestVersion, textPatch, versionFileDiffs, versionPatch } from './diff.ts'
import type { GlabRunner } from './glab.ts'
import { gitLabReviewerCandidates, requestGitLabReviews, rerunGitLabChecks, updateGitLabBranch } from './overview.ts'
import { pool } from './pool.ts'
import type { VersionFile } from './position.ts'
import { readReviewThreads } from './review.ts'
import type { PositionFile } from './review.ts'
import {
closingIssuesOf, JOB_PAGE, jobsPageSchema, JOBS_QUERY, needsMergeCheck, POLL_JOBS, projectSchema, snapshotOf, statusQuery,
} from './status.ts'
import type { JobNode, MergeRequestNode } from './status.ts'
import { checkedProject, encodedPath, mergeRequestPath, parseMergeRequestUrl, parseRemoteUrl, repositoryOf } from './urls.ts'
import { submitGitLabReview, writeGitLabReview } from './writes.ts'
import type { VersionFiles } from './writes.ts'
/** Closing issues one snapshot lists, as many as the GitHub provider lists. */
const CLOSING_ISSUES = 25
/** Open merge requests a head lookup returns. */
const HEAD_LOOKUP = 20
/** Bounds of the provider's reads and caches. */
export interface GitLabLimits {
/** Maximum combined JSON bytes one check read or review read keeps. */
readonly maxOutputBytes: number
/** Most review threads one review read returns. */
readonly maxReviewThreads: number
/** Most commits one commit listing returns. */
readonly maxCommits: number
/** Most merge requests one status query reads. */
readonly statusBatchSize: number
/** Most `glab` processes one status fetch runs at once. */
readonly maxConcurrentRequests: number
/** Most bytes of diff version patches kept for the hunks of outdated threads and the positions of new comments. */
readonly maxCachedVersionBytes: number
}
/** The issues a merge request closes, kept until its update time changes. */
interface ClosingIssues {
readonly updatedAt: string
readonly issues: readonly ChangeRequestIssue[]
readonly truncated: boolean
}
/** Changed files of one diff by their path on either side. */
type FilePatches = ReadonlyMap<string, VersionFile>
/** The per-file patches of one diff, kept for outdated threads and comment positions. */
interface CachedFiles {
readonly bytes: number
readonly files: FilePatches
}
/** Reads and writes GitLab.com and self-managed GitLab merge requests through a `glab` runner. */
export class GitLabProvider implements ForgeProvider {
readonly forge = 'gitlab'
readonly hosts: readonly string[]
readonly label = 'GitLab'
readonly changeRequestNoun = 'merge-request'
private readonly served: ReadonlySet<string>
private readonly api: GitLabApi
/** Closing issues by merge request; one entry per merge request this provider polled. */
private readonly closing = new Map<ChangeRequestKey, ClosingIssues>()
/** Diff version patches by merge request and version, least recently read first. */
private readonly versions = new Map<string, CachedFiles>()
/** Cache fills in flight, so concurrent threads on one file read it once. */
private readonly filling = new Map<string, Promise<FilePatches | undefined>>()
private versionBytes = 0
/**
* @param glab - runner that executes `glab` on the host.
* @param hosts - host names this provider serves, such as `gitlab.com` and self-managed hosts.
* @param limits - read and cache bounds.
*/
constructor(glab: GlabRunner, hosts: readonly string[], private readonly limits: GitLabLimits) {
this.api = new GitLabApi(glab)
this.hosts = [...new Set(hosts.map(host => host.toLowerCase()))]
this.served = new Set(this.hosts)
}
repositoryFromRemote(url: string): ForgeRepository | undefined {
const location = parseRemoteUrl(url)
return location === undefined || !this.served.has(location.host) ? undefined : repositoryOf(location)
}
changeRequestFromUrl(url: string): ChangeRequestRef | undefined {
const parsed = parseMergeRequestUrl(url)
return parsed === undefined || !this.served.has(parsed.host) ? undefined : { repository: repositoryOf(parsed), number: parsed.number }
}
changeRequestUrl(ref: ChangeRequestRef): string {
const { host, owner, name } = ref.repository
return `https://${host}/${owner}/${name}/-/merge_requests/${ref.number}`
}
async fetch(
refs: readonly ChangeRequestRef[], signal: AbortSignal,
): Promise<ReadonlyMap<ChangeRequestKey, ChangeRequestSnapshot | ForgeFailure>> {
const results = new Map<ChangeRequestKey, ChangeRequestSnapshot | ForgeFailure>()
const chunks: ChangeRequestRef[][] = []
const byHost = new Map<string, ChangeRequestRef[]>()
for (const ref of refs) {
const failure = this.hostFailure(ref.repository.host)
if (failure !== undefined) results.set(changeRequestKey(ref), failure)
else byHost.set(ref.repository.host, [...byHost.get(ref.repository.host) ?? [], ref])
}
for (const group of byHost.values()) {
const size = this.limits.statusBatchSize
for (let index = 0; index < group.length; index += size) chunks.push(group.slice(index, index + size))
}
await pool(chunks, this.limits.maxConcurrentRequests, async (chunk) => {
for (const [key, result] of await this.status(chunk, POLL_JOBS, signal)) results.set(key, result)
})
return results
}
async fetchChecks(ref: ChangeRequestRef, signal: AbortSignal): Promise<ChangeRequestSnapshot | ForgeFailure> {
const failure = this.hostFailure(ref.repository.host)
if (failure !== undefined) return failure
// oxlint-disable-next-line typescript/no-non-null-assertion -- status returns one result for each requested ref.
return (await this.status([ref], JOB_PAGE, signal, true)).get(changeRequestKey(ref))!
}
async findByHead(repository: ForgeRepository, branch: string, signal: AbortSignal): Promise<readonly ChangeRequestRef[]> {
const failure = this.hostFailure(repository.host)
if (failure !== undefined) throw new Error(failure.message)
const project = encodeURIComponent(checkedProject({ repository, number: 1 }))
const [settings, listing] = await Promise.all([
this.api.rest(repository.host, `projects/${project}`, signal),
this.api.rest(repository.host, `projects/${project}/merge_requests?state=opened&source_branch=${encodeURIComponent(branch)}`
+ `&order_by=created_at&sort=desc&per_page=${HEAD_LOOKUP}`, signal),
])
if (!settings.ok) throw new Error(`forge-gitlab: head branch lookup failed: ${settings.failure.message}`)
if (!listing.ok) throw new Error(`forge-gitlab: head branch lookup failed: ${listing.failure.message}`)
const defaults = z.object({ default_branch: z.string().nullable() }).safeParse(settings.body)
const requests = z.array(z.object({ iid: z.number(), source_project_id: z.number(), target_project_id: z.number() }))
.safeParse(listing.body)
if (!defaults.success || !requests.success) throw new Error('forge-gitlab: unexpected GitLab response to the head branch lookup')
if (defaults.data.default_branch === branch) return []
return requests.data.filter(request => request.source_project_id === request.target_project_id)
.map(request => ({ repository, number: request.iid }))
}
async readiness(host: string, signal: AbortSignal): Promise<ForgeReadiness> {
const failure = this.hostFailure(host)
if (failure !== undefined) return { state: 'unavailable', message: failure.message, signIn: null }
const read = await this.api.rest(host, 'user', signal)
if (read.ok) return { state: 'ready', message: null, signIn: null }
if (read.failure.code === 'unauthenticated') {
return { state: 'unauthenticated', message: read.failure.message, signIn: { command: `glab auth login --hostname ${host}` } }
}
return { state: 'unavailable', message: read.failure.message, signIn: null }
}
/** Mark a draft merge request ready through the GraphQL `mergeRequestSetDraft` mutation; a ready one stays ready. */
async markReady(ref: ChangeRequestRef, signal: AbortSignal): Promise<ForgeActionFailure | undefined> {
const refused = this.writable(ref, null)
if (refused !== undefined) return refused
const query = 'mutation($path: ID!, $iid: String!) { mergeRequestSetDraft(input: { projectPath: $path, iid: $iid, draft: false }) { errors } }'
const written = await this.api.mutate(ref.repository.host, query, { path: checkedProject(ref), iid: String(ref.number) }, 'mergeRequestSetDraft', signal)
return 'ok' in written ? undefined : written
}
/**
* Merge through the REST merge endpoint with `sha` set to the confirmed head, so GitLab refuses with HTTP 409 once
* the head moved; the method chooses squashing, and the merge request's own setting decides whether GitLab deletes the
* head branch.
*/
async merge(ref: ChangeRequestRef, request: MergeRequest, signal: AbortSignal): Promise<ForgeActionFailure | undefined> {
const refused = this.writable(ref, request.headSha)
if (refused !== undefined) return refused
const written = await this.api.write(ref.repository.host, [
'-X', 'PUT', `${mergeRequestPath(ref)}/merge`, '-f', `sha=${request.headSha}`, '-F', `squash=${request.method === 'squash'}`,
], signal)
if (written.ok) return undefined
return written.status === 409 ? { code: 'stale', message: written.failure.message } : written.failure
}
/**
* Publish a comment or a complete review through discussions and draft notes after a check of the head.
* @see submitGitLabReview
*/
async submitReview(ref: ChangeRequestRef, request: ForgeReviewRequest, signal: AbortSignal): Promise<ForgeReviewResult> {
const refused = this.writable(ref, request.headSha)
if (refused !== undefined) return { ok: false, code: 'failed', message: refused.message }
return await submitGitLabReview(this.api, this.filesOf(ref, signal), ref, request, signal)
}
/**
* Write to the discussions or the draft notes of a merge request after a check of the head.
* @see writeGitLabReview
*/
async writeReview(ref: ChangeRequestRef, write: ForgeReviewWrite, signal: AbortSignal): Promise<ForgeReviewWriteResult> {
const refused = this.writable(ref, write.headSha)
if (refused !== undefined) return { ok: false, code: 'failed', message: refused.message }
return await writeGitLabReview(this.api, this.filesOf(ref, signal), ref, write, signal)
}
/**
* Retry the failed jobs of the head pipeline once none of its jobs is pending.
* @see rerunGitLabChecks
*/
async rerunChecks(ref: ChangeRequestRef, request: ForgeRerunRequest, signal: AbortSignal): Promise<ForgeActionFailure | undefined> {
const read = async (): Promise<ChangeRequestSnapshot | ForgeFailure> => await this.fetchChecks(ref, signal)
return this.writable(ref, request.headSha) ?? await rerunGitLabChecks(this.api, read, ref, request, signal)
}
async requestReviews(
ref: ChangeRequestRef, request: ForgeReviewersRequest, signal: AbortSignal,
): Promise<ForgeActionFailure | undefined> {
return this.writable(ref, null) ?? await requestGitLabReviews(this.api, ref, request, signal)
}
async reviewerCandidates(
ref: ChangeRequestRef, query: string, signal: AbortSignal,
): Promise<readonly ForgeReviewerCandidate[] | ForgeFailure> {
const failure = this.hostFailure(ref.repository.host)
if (failure !== undefined) return failure
return await gitLabReviewerCandidates(this.api, ref, query, signal)
}
async updateBranch(ref: ChangeRequestRef, request: BranchUpdateRequest, signal: AbortSignal): Promise<ForgeActionFailure | undefined> {
return this.writable(ref, request.headSha) ?? await updateGitLabBranch(this.api, ref, request, signal)
}
/**
* Read the patch of the newest diff version, which GitLab records for every push, once it is at `headSha`; `base` is
* not needed because the version names its own merge base.
*/
async diff(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise<string | ForgeFailure> {
const failure = this.hostFailure(ref.repository.host)
if (failure !== undefined) return failure
if (!isCommit(headSha)) throw new Error(`forge-gitlab: invalid head commit ${JSON.stringify(headSha)}`)
const version = await newestVersion(this.api, ref, headSha, signal)
if ('code' in version) return version
return await versionPatch(this.api, ref, version, async (commit, path) => await fileTextOf(this.api, ref, commit, path, signal), signal)
}
async fileText(ref: ChangeRequestRef, commit: string, path: string, signal: AbortSignal): Promise<string | ForgeFailure> {
const failure = this.hostFailure(ref.repository.host)
if (failure !== undefined) return failure
if (!isCommit(commit)) throw new Error(`forge-gitlab: invalid commit ${JSON.stringify(commit)}`)
return await fileTextOf(this.api, ref, commit, path, signal)
}
fileUrl(ref: ChangeRequestRef, commit: string, path: string): string {
const { host, owner, name } = ref.repository
return `https://${host}/${owner}/${name}/-/blob/${commit}/${encodedPath(path)}`
}
async commits(ref: ChangeRequestRef, signal: AbortSignal): Promise<ForgeCommitList | ForgeFailure> {
const failure = this.hostFailure(ref.repository.host)
if (failure !== undefined) return failure
return await readCommits(this.api, ref, this.limits.maxCommits, signal)
}
async compare(ref: ChangeRequestRef, base: string, head: string, signal: AbortSignal): Promise<string | ForgeFailure> {
const failure = this.hostFailure(ref.repository.host)
if (failure !== undefined) return failure
if (!isCommit(base) || !isCommit(head)) throw new Error(`forge-gitlab: invalid commits ${JSON.stringify(`${base}..${head}`)}`)
const readText = async (commit: string, path: string): Promise<string | ForgeFailure> =>
await fileTextOf(this.api, ref, commit, path, signal)
return await comparePatch(this.api, ref, base, head, readText, signal)
}
async mergeBase(ref: ChangeRequestRef, base: string, head: string, signal: AbortSignal): Promise<string | ForgeFailure> {
const failure = this.hostFailure(ref.repository.host)
if (failure !== undefined) return failure
if (!isCommit(base) || !isCommit(head)) throw new Error(`forge-gitlab: invalid commits ${JSON.stringify(`${base}..${head}`)}`)
return await mergeBaseOf(this.api, ref, base, head, signal)
}
async readReview(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise<ForgeReviewData | ForgeFailure> {
const failure = this.hostFailure(ref.repository.host)
if (failure !== undefined) return failure
return await readReviewThreads(this.api, ref, headSha, this.limits, async file => await this.positionPatch(ref, file, signal), signal)
}
/**
* Read the status of merge requests on one host with one GraphQL query, halving the batch while GitLab refuses it as
* too complex, then read each one's closing issues unless its update time is the one they were read at.
*/
private async status(
refs: readonly ChangeRequestRef[], jobs: number, signal: AbortSignal, allJobs = false,
): Promise<ReadonlyMap<ChangeRequestKey, ChangeRequestSnapshot | ForgeFailure>> {
const results = new Map<ChangeRequestKey, ChangeRequestSnapshot | ForgeFailure>()
// oxlint-disable-next-line typescript/no-non-null-assertion -- callers pass at least one ref, all on one host.
const host = refs[0]!.repository.host
const variables: Record<string, unknown> = { jobs }
refs.forEach((ref, index) => { variables[`p${index}`] = checkedProject(ref); variables[`i${index}`] = String(ref.number) })
const read = await this.api.graphql(host, statusQuery(refs.length), variables, signal)
if (!read.ok) {
if (read.failure.code === 'too-large' && refs.length > 1) {
const half = Math.ceil(refs.length / 2)
for (const part of [refs.slice(0, half), refs.slice(half)]) {
for (const [key, result] of await this.status(part, jobs, signal, allJobs)) results.set(key, result)
}
return results
}
for (const ref of refs) results.set(changeRequestKey(ref), read.failure)
return results
}
const data = z.record(z.string(), z.unknown()).parse(read.body)
for (const [index, ref] of refs.entries()) {
const key = changeRequestKey(ref)
const project = projectSchema.safeParse(data[`m${index}`])
if (!project.success) results.set(key, { code: 'unavailable', message: 'unexpected GitLab response to the status read' })
else if (project.data === null || project.data.mergeRequest === null) results.set(key, { code: 'not-found', message: `merge request ${ref.number} was not found` })
else results.set(key, await this.snapshot(ref, project.data.mergeRequestsFfOnlyEnabled, project.data.mergeRequest, allJobs, signal))
}
return results
}
/**
* Complete one merge request's snapshot with the rest of its jobs, when asked for, and its closing issues, asking GitLab
* to check its conflicts when it has not since a change.
*/
private async snapshot(
ref: ChangeRequestRef, fastForwardOnly: boolean, node: MergeRequestNode, allJobs: boolean, signal: AbortSignal,
): Promise<ChangeRequestSnapshot | ForgeFailure> {
const jobs: JobNode[] = [...node.headPipeline?.jobs?.nodes ?? []]
let page = node.headPipeline?.jobs?.pageInfo
let bytes = Buffer.byteLength(JSON.stringify(node))
while (allJobs && page?.hasNextPage === true) {
const cursor = page.endCursor
if (cursor == null) return { code: 'unavailable', message: 'GitLab job pagination did not advance' }
const variables = { path: checkedProject(ref), iid: String(ref.number), cursor }
const read = await this.api.graphql(ref.repository.host, JOBS_QUERY, variables, signal)
if (!read.ok) return read.failure
bytes += Buffer.byteLength(JSON.stringify(read.body))
if (bytes > this.limits.maxOutputBytes) return { code: 'too-large', message: `the checks of merge request ${ref.number} exceed maxOutputBytes` }
const parsed = jobsPageSchema.safeParse(read.body)
const next = parsed.success ? parsed.data.project?.mergeRequest : undefined
if (next == null || next.headPipeline?.jobs == null) return { code: 'unavailable', message: 'unexpected GitLab response to the job read' }
if (next.diffRefs?.headSha !== node.diffRefs?.headSha) return { code: 'unavailable', message: 'the merge request head moved while its checks were read' }
jobs.push(...next.headPipeline.jobs.nodes)
page = next.headPipeline.jobs.pageInfo
}
// A REST read asks GitLab to check the merge request again, whose outcome a later poll reads; the snapshot reports unknown.
if (needsMergeCheck(node)) await this.api.rest(ref.repository.host, mergeRequestPath(ref), signal)
const closing = await this.closingIssues(ref, node.updatedAt, signal)
return snapshotOf({
ref, fastForwardOnly, node, jobs, jobsTruncated: page?.hasNextPage ?? false,
closingIssues: closing.issues, closingIssuesTruncated: closing.truncated,
})
}
/**
* The issues a merge request closes. GitLab derives them from its description and commit messages, and changing
* either changes its update time, so a list read at the same update time is reused. A failed read keeps the last
* list, or none, marked truncated.
*/
private async closingIssues(ref: ChangeRequestRef, updatedAt: string, signal: AbortSignal): Promise<ClosingIssues> {
const key = changeRequestKey(ref)
const kept = this.closing.get(key)
if (kept?.updatedAt === updatedAt) return kept
const read = await this.api.rest(ref.repository.host, `${mergeRequestPath(ref)}/closes_issues?per_page=${CLOSING_ISSUES + 1}`, signal)
const listed = read.ok ? closingIssuesOf(read.body, CLOSING_ISSUES) : undefined
if (listed === undefined) return { updatedAt, issues: kept?.issues ?? [], truncated: true }
const entry = { updatedAt, issues: listed.issues, truncated: listed.truncated }
this.closing.set(key, entry)
return entry
}
/**
* One file's patch in the diff a thread position names: from the diff version when GitLab keeps its files, else by
* comparing the file's text at the position's merge base and head, where a missing file reads as empty. Both never
* change, so they are kept, least recently read dropped first, until they pass `maxCachedVersionBytes`.
*/
private async positionPatch(ref: ChangeRequestRef, file: PositionFile, signal: AbortSignal): Promise<string | null> {
if (file.version !== null) {
const files = await this.versionFiles(ref, file.version, signal)
const patch = (files?.get(file.newPath) ?? files?.get(file.oldPath))?.diff
if (patch !== undefined && patch !== '') return patch
}
const files = await this.cached(`${changeRequestKey(ref)}:${file.baseSha}..${file.headSha}:${file.newPath}`, async () => {
const text = async (commit: string, path: string): Promise<string | undefined> => {
const read = await fileTextOf(this.api, ref, commit, path, signal)
return typeof read === 'string' ? read : read.code === 'not-found' ? '' : undefined
}
const [before, after] = await Promise.all([text(file.baseSha, file.oldPath), text(file.headSha, file.newPath)])
if (before === undefined || after === undefined) return undefined
const diff = textPatch(`a/${file.oldPath}`, `b/${file.newPath}`, before, after)
return new Map([[file.newPath, { oldPath: file.oldPath, newPath: file.newPath, diff }]])
})
return files?.get(file.newPath)?.diff ?? null
}
/**
* The changed files of one diff version by their path on either side, which never change, kept with the patches of
* outdated threads. A file's new path names it over another file's old path, so after `a → b` and `b → c` the path
* `b` names the first file.
*/
private async versionFiles(ref: ChangeRequestRef, version: number, signal: AbortSignal): Promise<FilePatches | undefined> {
return await this.cached(`${changeRequestKey(ref)}@${version}`, async () => {
const readText = async (commit: string, path: string) => await fileTextOf(this.api, ref, commit, path, signal)
const files = await versionFileDiffs(this.api, ref, version, readText, signal)
if (files === undefined) return undefined
const byOldPath = files.map(file => [file.oldPath, file] as const)
return new Map<string, VersionFile>([...byOldPath, ...files.map(file => [file.newPath, file] as const)])
})
}
/** Reads the changed files of the merge request's diff versions for comment positions. */
private filesOf(ref: ChangeRequestRef, signal: AbortSignal): VersionFiles {
return async version => await this.versionFiles(ref, version, signal)
}
/** Read one cache entry, or fill it from `read` unless the read fails; concurrent callers of one key share one fill. */
private async cached(key: string, read: () => Promise<FilePatches | undefined>): Promise<FilePatches | undefined> {
const kept = this.versions.get(key)
if (kept === undefined) {
const pending = this.filling.get(key)
if (pending !== undefined) return await pending
const filled = this.fill(key, read)
this.filling.set(key, filled)
try {
return await filled
} finally {
this.filling.delete(key)
}
}
this.versions.delete(key)
this.versions.set(key, kept)
return kept.files
}
/**
* Read and keep one cache entry, then drop the least recently read entries over the limit; an entry over the limit by
* itself serves this read only.
*/
private async fill(key: string, read: () => Promise<FilePatches | undefined>): Promise<FilePatches | undefined> {
const files = await read()
if (files === undefined) return undefined
// A file listed under both of its paths counts once.
const entry = { bytes: [...new Set(files.values())].reduce((total, file) => total + Buffer.byteLength(file.diff), 0), files }
if (entry.bytes > this.limits.maxCachedVersionBytes) return files
this.versionBytes += entry.bytes
this.versions.set(key, entry)
for (const [kept, old] of this.versions) {
if (this.versionBytes <= this.limits.maxCachedVersionBytes) break
this.versions.delete(kept)
this.versionBytes -= old.bytes
}
return files
}
/**
* Refuse a write to a host this provider does not serve.
* @throws when `headSha` is given and is not a full commit object name, which callers check before they write.
*/
private writable(ref: ChangeRequestRef, headSha: string | null): ForgeActionFailure | undefined {
const failure = this.hostFailure(ref.repository.host)
if (failure !== undefined) return { code: 'failed', message: failure.message }
if (headSha !== null && !isCommit(headSha)) throw new Error(`forge-gitlab: invalid head commit ${JSON.stringify(headSha)}`)
return undefined
}
private hostFailure(host: string): ForgeFailure | undefined {
return this.served.has(host.toLowerCase()) ? undefined : {
code: 'unavailable',
message: `forge-gitlab does not serve ${host}; add it to the provider's hosts setting`,
}
}
}