* 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
751 lines
37 KiB
TypeScript
751 lines
37 KiB
TypeScript
/** Registry of code-host providers with provider-neutral change requests and shared status polling. */
|
|
|
|
import { Context, Service } from '@deepseek-ai/cordis'
|
|
import z from '@deepseek-ai/schemastery'
|
|
import { deadline, MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout'
|
|
import { changeRequestKey } from './keys.ts'
|
|
import { nextPollDelay } from './schedule.ts'
|
|
import type {
|
|
BranchUpdateRequest, ChangeRequestKey, ChangeRequestListener, ChangeRequestRef, ChangeRequestSnapshot, ChangeRequestUpdate, Config,
|
|
ForgeCommitList, ForgeActionFailure, ForgeDescription, ForgeFailure, ForgeProvider, ForgeReadiness, ForgeRepository, ForgeRerunRequest,
|
|
ForgeReviewData,
|
|
ForgeReviewChange, ForgeReviewerCandidate, ForgeReviewersRequest, ForgeReviewRequest, ForgeReviewResult, ForgeReviewWrite,
|
|
ForgeReviewWriteResult,
|
|
ForgeViewedFiles, ForgeViewedRequest, MergeRequest,
|
|
} from './types.ts'
|
|
|
|
export { changeRequestKey } from './keys.ts'
|
|
export type * from './types.ts'
|
|
|
|
declare module '@deepseek-ai/cordis' {
|
|
interface Context {
|
|
forge: ForgeService
|
|
}
|
|
interface Events {
|
|
/**
|
|
* Announces a provider registration or withdrawal after the registry changes.
|
|
* Listener failures are logged without preventing other listeners from running.
|
|
* @param forge - family whose provider changed.
|
|
* @mode parallel
|
|
*/
|
|
'forge/providers-changed'(forge: string): void | Promise<void>
|
|
/**
|
|
* Announces a review change the host accepted through this service: a thread or pending-review write, a submitted
|
|
* review, or a viewed mark. Changes whose outcome is unknown, refused, stale, or unsupported are not announced.
|
|
* Listener failures are logged without preventing other listeners from running.
|
|
* @param ref - change request the change went to.
|
|
* @param change - what changed and the head commit it was made against.
|
|
* @mode parallel
|
|
*/
|
|
'forge/review-changed'(ref: ChangeRequestRef, change: ForgeReviewChange): void | Promise<void>
|
|
}
|
|
}
|
|
|
|
type FetchResults = ReadonlyMap<ChangeRequestKey, ChangeRequestSnapshot | ForgeFailure>
|
|
|
|
interface Registration {
|
|
readonly provider: ForgeProvider
|
|
readonly lifetime: AbortController
|
|
readonly pending: Set<Promise<void>>
|
|
}
|
|
|
|
interface Watch {
|
|
readonly key: ChangeRequestKey
|
|
readonly ref: ChangeRequestRef
|
|
readonly listeners: Set<ChangeRequestListener>
|
|
latest: ChangeRequestUpdate | undefined
|
|
/** Epoch milliseconds of the next poll; undefined while in flight or after a terminal state. */
|
|
dueAt: number | undefined
|
|
failures: number
|
|
/** Head commit whose `stale` diff or review read last polled at once, so further stale reads at it wait for the regular poll. */
|
|
staleHead: string | undefined
|
|
}
|
|
|
|
/**
|
|
* Registry of forge providers. Watchers of one change request share a single
|
|
* polling loop; each forge has at most one fetch in flight, which batches
|
|
* every due change request of that forge.
|
|
*/
|
|
export class ForgeService extends Service {
|
|
static Config: z<Config> = z.object({
|
|
activeIntervalMs: z.number().default(30_000),
|
|
idleIntervalMs: z.number().default(120_000),
|
|
maxBackoffMs: z.number().default(600_000),
|
|
fetchTimeoutMs: z.number().default(30_000),
|
|
})
|
|
|
|
private readonly config: Required<Config>
|
|
private readonly providers = new Map<string, Registration>()
|
|
private readonly watches = new Map<ChangeRequestKey, Watch>()
|
|
private readonly fetching = new Set<string>()
|
|
private readonly pending = new Set<Promise<void>>()
|
|
private readonly lifetime = new AbortController()
|
|
private timer: ReturnType<typeof setTimeout> | undefined
|
|
/**
|
|
* Poll what is due. A field rather than a method, so the timer runs it on
|
|
* the instance itself: a polling round started through a caller's `ctx.forge`
|
|
* would otherwise run on that caller's shadow receiver, and every later round
|
|
* would nest one more shadow until a property write overflows the stack.
|
|
*/
|
|
private readonly tick = (): void => {
|
|
this.timer = undefined
|
|
this.poll()
|
|
}
|
|
|
|
constructor(ctx: Context, config: Config) {
|
|
super(ctx, 'forge')
|
|
this.config = config as Required<Config>
|
|
for (const key of ['activeIntervalMs', 'idleIntervalMs', 'maxBackoffMs', 'fetchTimeoutMs'] as const) {
|
|
const value = this.config[key]
|
|
if (!Number.isSafeInteger(value) || value <= 0 || value > MAX_TIMER_DELAY_MS) {
|
|
throw new Error(`forge: ${key} must be a positive integer no greater than ${MAX_TIMER_DELAY_MS}`)
|
|
}
|
|
}
|
|
if (this.config.maxBackoffMs < this.config.activeIntervalMs) {
|
|
throw new Error('forge: maxBackoffMs must be greater than or equal to activeIntervalMs')
|
|
}
|
|
ctx.effect(() => async () => {
|
|
this.lifetime.abort(new Error('forge service disposed'))
|
|
clearTimeout(this.timer)
|
|
this.timer = undefined
|
|
await Promise.allSettled(this.pending)
|
|
}, 'forge: stop polling')
|
|
}
|
|
|
|
/**
|
|
* Register the provider of one forge family as an effect on the calling
|
|
* fiber. Watches of that forge receive an `unavailable` failure when the
|
|
* registration ends. Unregistering cancels and awaits its in-flight calls;
|
|
* results from the withdrawn registration are discarded.
|
|
* @param provider - provider to serve `provider.forge` on `provider.hosts`.
|
|
* @returns the disposer that unregisters the provider and waits for its calls to finish.
|
|
* @throws when another provider already serves the same forge or one of the same hosts, compared without case.
|
|
*/
|
|
register(provider: ForgeProvider): () => Promise<void> {
|
|
const dispose = this.ctx.effect(() => {
|
|
if (this.providers.has(provider.forge)) throw new Error(`forge: a provider for "${provider.forge}" is already registered`)
|
|
for (const { provider: other } of this.providers.values()) {
|
|
const taken = new Set(other.hosts.map(host => host.toLowerCase()))
|
|
const host = provider.hosts.find(candidate => taken.has(candidate.toLowerCase()))
|
|
if (host !== undefined) throw new Error(`forge: host "${host}" is already served by the "${other.forge}" provider`)
|
|
}
|
|
const registration: Registration = { provider, lifetime: new AbortController(), pending: new Set() }
|
|
this.providers.set(provider.forge, registration)
|
|
for (const watch of this.watches.values()) {
|
|
if (watch.ref.repository.forge === provider.forge) watch.dueAt = Date.now()
|
|
}
|
|
this.providersChanged(provider.forge)
|
|
this.schedule()
|
|
return async () => {
|
|
this.providers.delete(provider.forge)
|
|
registration.lifetime.abort(new Error(`forge: provider "${provider.forge}" was unregistered`))
|
|
for (const watch of [...this.watches.values()]) {
|
|
if (watch.ref.repository.forge === provider.forge) this.settle(watch, this.missing(provider.forge), undefined)
|
|
}
|
|
this.providersChanged(provider.forge)
|
|
this.schedule()
|
|
await Promise.allSettled(registration.pending)
|
|
}
|
|
}, `forge.register(${provider.forge})`)
|
|
return async () => { await dispose() }
|
|
}
|
|
|
|
/**
|
|
* Name a forge family and its change requests for readers.
|
|
* @param forge - forge family name, such as `github`.
|
|
* @returns the registered provider's description, or undefined when no provider serves the family.
|
|
*/
|
|
describe(forge: string): ForgeDescription | undefined {
|
|
const provider = this.providers.get(forge)?.provider
|
|
return provider === undefined ? undefined : { forge, label: provider.label, changeRequestNoun: provider.changeRequestNoun }
|
|
}
|
|
|
|
/**
|
|
* Map a Git remote URL to a repository through the provider that serves its host.
|
|
* @param url - fetch or push URL as Git reports it.
|
|
* @returns the repository, or undefined when no provider serves the URL.
|
|
*/
|
|
repositoryFromRemote(url: string): ForgeRepository | undefined {
|
|
for (const { provider } of this.providers.values()) {
|
|
const repository = provider.repositoryFromRemote(url)
|
|
if (repository !== undefined) return repository
|
|
}
|
|
return undefined
|
|
}
|
|
|
|
/**
|
|
* Map a change request web URL through the provider that serves its host.
|
|
* @param url - web URL of a pull or merge request.
|
|
* @returns the change request, or undefined when no provider serves the URL.
|
|
*/
|
|
changeRequestFromUrl(url: string): ChangeRequestRef | undefined {
|
|
for (const { provider } of this.providers.values()) {
|
|
const ref = provider.changeRequestFromUrl(url)
|
|
if (ref !== undefined) return ref
|
|
}
|
|
return undefined
|
|
}
|
|
|
|
/**
|
|
* Build the canonical web URL of a change request.
|
|
* @param ref - change request served by a registered provider.
|
|
* @returns the provider's canonical URL.
|
|
* @throws when no provider serves the change request's forge.
|
|
*/
|
|
changeRequestUrl(ref: ChangeRequestRef): string {
|
|
return this.provider(ref.repository.forge).changeRequestUrl(ref)
|
|
}
|
|
|
|
/**
|
|
* Find open change requests whose head is `branch`, excluding the default branch and forks.
|
|
* @param repository - repository served by a registered provider.
|
|
* @param branch - head branch name on the host.
|
|
* @param signal - cancellation for the lookup.
|
|
* @returns matching change requests, newest first as the provider reports them.
|
|
* @throws when no provider serves the repository's forge or the lookup fails.
|
|
*/
|
|
async findByHead(repository: ForgeRepository, branch: string, signal: AbortSignal): Promise<readonly ChangeRequestRef[]> {
|
|
return await this.invoke(this.registration(repository.forge), signal,
|
|
(provider, operation) => provider.findByHead(repository, branch, operation))
|
|
}
|
|
|
|
/**
|
|
* Report whether the provider can reach the repository's host with current credentials.
|
|
* @param repository - repository served by a registered provider.
|
|
* @param signal - cancellation for the probe.
|
|
* @returns the provider's readiness for the host.
|
|
* @throws when no provider serves the repository's forge.
|
|
*/
|
|
async readiness(repository: ForgeRepository, signal: AbortSignal): Promise<ForgeReadiness> {
|
|
return await this.invoke(this.registration(repository.forge), signal,
|
|
(provider, operation) => provider.readiness(repository.host, operation))
|
|
}
|
|
|
|
/**
|
|
* Mark a draft change request ready for review, then poll it at once when it is watched.
|
|
* @param ref - change request served by a registered provider.
|
|
* @param signal - cancellation of the request.
|
|
* @returns undefined once the host accepted the change, or why it did not.
|
|
* @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts.
|
|
*/
|
|
async markReady(ref: ChangeRequestRef, signal: AbortSignal): Promise<ForgeActionFailure | undefined> {
|
|
const failure = await this.invoke(this.registration(ref.repository.forge), signal,
|
|
(provider, operation) => provider.markReady(ref, operation))
|
|
this.refresh(ref)
|
|
return failure
|
|
}
|
|
|
|
/**
|
|
* Merge a change request while its head is still `request.headSha`, then
|
|
* poll it at once when it is watched.
|
|
* @param ref - change request served by a registered provider.
|
|
* @param request - merge method and the head commit the user confirmed.
|
|
* @param signal - cancellation of the request.
|
|
* @returns undefined once the host merged it, or why it did not.
|
|
* @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts.
|
|
*/
|
|
async merge(ref: ChangeRequestRef, request: MergeRequest, signal: AbortSignal): Promise<ForgeActionFailure | undefined> {
|
|
const failure = await this.invoke(this.registration(ref.repository.forge), signal,
|
|
(provider, operation) => provider.merge(ref, request, operation))
|
|
this.refresh(ref)
|
|
return failure
|
|
}
|
|
|
|
/**
|
|
* Rerun the failed checks of a change request's head commit while the head is still `request.headSha`, then poll it
|
|
* at once when it is watched.
|
|
* @param ref - change request served by a registered provider.
|
|
* @param request - the head commit whose checks the user saw.
|
|
* @param signal - cancellation of the request.
|
|
* @returns undefined once the host accepted the rerun, or why it did not; a provider that reruns no checks fails.
|
|
* @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts.
|
|
*/
|
|
async rerunChecks(ref: ChangeRequestRef, request: ForgeRerunRequest, signal: AbortSignal): Promise<ForgeActionFailure | undefined> {
|
|
return await this.act(ref, signal, provider => provider.rerunChecks?.bind(provider), 'reruns no checks',
|
|
(action, operation) => action(ref, request, operation))
|
|
}
|
|
|
|
/**
|
|
* Request reviews of a change request from more reviewers, then poll it at once when it is watched.
|
|
* @param ref - change request served by a registered provider.
|
|
* @param request - the reviewers to ask.
|
|
* @param signal - cancellation of the request.
|
|
* @returns undefined once the host accepted the request, or why it did not; a provider that requests no reviews fails.
|
|
* @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts.
|
|
*/
|
|
async requestReviews(
|
|
ref: ChangeRequestRef, request: ForgeReviewersRequest, signal: AbortSignal,
|
|
): Promise<ForgeActionFailure | undefined> {
|
|
return await this.act(ref, signal,
|
|
provider => provider.reviewerCandidates === undefined ? undefined : provider.requestReviews?.bind(provider), 'requests no reviews',
|
|
(action, operation) => action(ref, request, operation))
|
|
}
|
|
|
|
/**
|
|
* List accounts a review of a change request can be requested from.
|
|
* @param ref - change request served by a registered provider.
|
|
* @param query - text the login or name contains; empty for the host's suggestions and first accounts.
|
|
* @param signal - cancellation of the read.
|
|
* @returns the accounts, the host's suggestions first, or why the host did not list them; a provider that requests no
|
|
* reviews returns `unsupported`.
|
|
* @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts.
|
|
*/
|
|
async reviewerCandidates(
|
|
ref: ChangeRequestRef, query: string, signal: AbortSignal,
|
|
): Promise<readonly ForgeReviewerCandidate[] | ForgeFailure> {
|
|
return await this.invoke(this.registration(ref.repository.forge), signal,
|
|
(provider, operation) => provider.reviewerCandidates === undefined || provider.requestReviews === undefined
|
|
? Promise.resolve({ code: 'unsupported', message: 'This provider requests no reviews' } as const)
|
|
: provider.reviewerCandidates(ref, query, operation))
|
|
}
|
|
|
|
/**
|
|
* Bring the base branch's new commits into a change request's head branch while its head is still
|
|
* `request.headSha`, then poll it at once when it is watched.
|
|
* @param ref - change request served by a registered provider.
|
|
* @param request - update method and the head commit the user confirmed.
|
|
* @param signal - cancellation of the request.
|
|
* @returns undefined once the host accepted the update, or why it did not; a provider that updates no branches fails.
|
|
* @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts.
|
|
*/
|
|
async updateBranch(ref: ChangeRequestRef, request: BranchUpdateRequest, signal: AbortSignal): Promise<ForgeActionFailure | undefined> {
|
|
return await this.act(ref, signal, provider => provider.updateBranch?.bind(provider), 'updates no branches',
|
|
(action, operation) => action(ref, request, operation))
|
|
}
|
|
|
|
/**
|
|
* Read complete check details independently of periodic polling.
|
|
* @param ref - change request served by a registered provider.
|
|
* @param signal - cancellation of the detail view.
|
|
* @returns a complete snapshot or the provider's failure; unsupported providers return unavailable.
|
|
* @throws on cancellation, provider disposal, or expiry of this read's own `fetchTimeoutMs` deadline.
|
|
*/
|
|
async fetchChecks(ref: ChangeRequestRef, signal: AbortSignal): Promise<ChangeRequestSnapshot | ForgeFailure> {
|
|
using timeout = deadline(signal, this.config.fetchTimeoutMs, 'FORGE_FETCH_TIMEOUT')
|
|
return await this.invoke(this.registration(ref.repository.forge), timeout.signal,
|
|
(provider, operation) => provider.fetchChecks?.(ref, operation)
|
|
?? Promise.resolve({ code: 'unavailable', message: 'This provider does not support complete check reads' } as const))
|
|
}
|
|
|
|
/**
|
|
* Read the changes of a change request at one head commit as its host
|
|
* computes them. The first `stale` failure at a head commit polls a watched
|
|
* change request again at once, so its next status names the current head;
|
|
* later stale reads at the same commit wait for the regular poll, which
|
|
* bounds the reads while the host's answers disagree. When the latest status of a watched change request names
|
|
* `headSha`, its `baseSha` goes to the provider, which may then read the patch while it confirms the head.
|
|
* @param ref - change request served by a registered provider.
|
|
* @param headSha - head commit the patch must describe, usually the head of the latest status.
|
|
* @param signal - cancellation of the read.
|
|
* @returns one unified patch with `a/` and `b/` path prefixes, or why the host did not provide it at `headSha`.
|
|
* @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts.
|
|
*/
|
|
async diff(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise<string | ForgeFailure> {
|
|
const latest = this.watches.get(changeRequestKey(ref))?.latest
|
|
const base = latest !== undefined && 'snapshot' in latest && latest.snapshot.headSha === headSha ? latest.snapshot.baseSha : undefined
|
|
const result = await this.invoke(this.registration(ref.repository.forge), signal,
|
|
(provider, operation) => provider.diff(ref, headSha, operation, base))
|
|
if (typeof result !== 'string') this.staleRead(ref, headSha, result.code)
|
|
return result
|
|
}
|
|
|
|
/**
|
|
* Read the review threads of a change request at one head commit. A
|
|
* `stale` failure polls a watched change request again as {@link ForgeService.diff} does.
|
|
* @param ref - change request served by a registered provider.
|
|
* @param headSha - head commit the threads must be read at, usually the head of the displayed diff.
|
|
* @param signal - cancellation of the read.
|
|
* @returns the threads read at `headSha`, or why the host did not provide them; `unsupported` when the provider cannot read reviews.
|
|
* @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts.
|
|
*/
|
|
async readReview(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise<ForgeReviewData | ForgeFailure> {
|
|
const result = await this.invoke(this.registration(ref.repository.forge), signal,
|
|
(provider, operation) => provider.readReview?.(ref, headSha, operation)
|
|
?? Promise.resolve({ code: 'unsupported', message: 'This provider does not support review reads' } as const))
|
|
if ('code' in result) this.staleRead(ref, headSha, result.code)
|
|
return result
|
|
}
|
|
|
|
/**
|
|
* Write to the review threads or the pending review of a change request while its head is still `write.headSha`, then
|
|
* poll the change request at once when it is watched, unless the provider cannot write reviews. A `stale` result polls
|
|
* it as a stale read does; a write the host took is announced with `forge/review-changed`.
|
|
* @param ref - change request served by a registered provider.
|
|
* @param write - the write and the head commit the user saw.
|
|
* @param signal - cancellation of the write.
|
|
* @returns whether the host took the write; `unsupported` when the provider cannot write reviews, and `unknown` when the
|
|
* outcome must be checked on the host before the write is tried again.
|
|
* @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts.
|
|
*/
|
|
async writeReview(ref: ChangeRequestRef, write: ForgeReviewWrite, signal: AbortSignal): Promise<ForgeReviewWriteResult> {
|
|
const result = await this.invoke(this.registration(ref.repository.forge), signal,
|
|
(provider, operation) => provider.writeReview?.(ref, write, operation)
|
|
?? Promise.resolve({ ok: false, code: 'unsupported', message: 'This provider does not support review writes' } as const))
|
|
if (!result.ok && result.code === 'stale') this.staleRead(ref, write.headSha, result.code)
|
|
else if (result.ok || result.code !== 'unsupported') this.refresh(ref)
|
|
if (result.ok) this.reviewChanged(ref, { kind: 'write', write: write.kind, headSha: write.headSha })
|
|
return result
|
|
}
|
|
|
|
/**
|
|
* Read the signed-in user's viewed marks on the files of a change request at one head commit. A `stale` failure
|
|
* polls a watched change request again as {@link ForgeService.diff} does.
|
|
* @param ref - change request served by a registered provider.
|
|
* @param headSha - head commit the marks must be read at, usually the head of the displayed diff.
|
|
* @param signal - cancellation of the read.
|
|
* @returns the marks read at `headSha`, why the host did not provide them, or undefined when the provider keeps no
|
|
* viewed marks.
|
|
* @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts.
|
|
*/
|
|
async viewedFiles(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise<ForgeViewedFiles | ForgeFailure | undefined> {
|
|
const result = await this.invoke(this.registration(ref.repository.forge), signal,
|
|
(provider, operation) => provider.viewedFiles === undefined || provider.setViewed === undefined
|
|
? Promise.resolve(undefined) : provider.viewedFiles(ref, headSha, operation))
|
|
if (result !== undefined && 'code' in result) this.staleRead(ref, headSha, result.code)
|
|
return result
|
|
}
|
|
|
|
/**
|
|
* Set or clear the signed-in user's viewed mark on one file of a change request while its head is still
|
|
* `request.headSha`. A `stale` failure polls a watched change request again as {@link ForgeService.diff} does; a saved
|
|
* mark is announced with `forge/review-changed`.
|
|
* @param ref - change request served by a registered provider.
|
|
* @param request - the file, its mark, and the head commit the user saw.
|
|
* @param signal - cancellation of the request.
|
|
* @returns undefined once the host saved the mark, or why it did not; a provider that keeps no viewed marks fails.
|
|
* @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts.
|
|
*/
|
|
async setViewed(ref: ChangeRequestRef, request: ForgeViewedRequest, signal: AbortSignal): Promise<ForgeActionFailure | undefined> {
|
|
const failure = await this.invoke(this.registration(ref.repository.forge), signal,
|
|
(provider, operation) => provider.viewedFiles === undefined || provider.setViewed === undefined
|
|
? Promise.resolve({ code: 'failed', message: 'This provider keeps no viewed marks' } as const)
|
|
: provider.setViewed(ref, request, operation))
|
|
if (failure?.code === 'stale') this.staleRead(ref, request.headSha, failure.code)
|
|
if (failure === undefined) this.reviewChanged(ref, { kind: 'viewed', path: request.path, viewed: request.viewed, headSha: request.headSha })
|
|
return failure
|
|
}
|
|
|
|
/**
|
|
* List the commits of a change request at its current head.
|
|
* @param ref - change request served by a registered provider.
|
|
* @param signal - cancellation of the read.
|
|
* @returns the commits, why the host did not provide them, or undefined when the provider does not read commits.
|
|
* @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts.
|
|
*/
|
|
async commits(ref: ChangeRequestRef, signal: AbortSignal): Promise<ForgeCommitList | ForgeFailure | undefined> {
|
|
return await this.invoke(this.registration(ref.repository.forge), signal,
|
|
(provider, operation) => provider.commits === undefined || provider.compare === undefined
|
|
? Promise.resolve(undefined) : provider.commits(ref, operation))
|
|
}
|
|
|
|
/**
|
|
* Read the changes between two commits of a change request's repository.
|
|
* @param ref - change request served by a registered provider.
|
|
* @param base - full object name of the commit compared from.
|
|
* @param head - full object name of a commit that descends from `base`.
|
|
* @param signal - cancellation of the read.
|
|
* @returns one unified patch with `a/` and `b/` path prefixes, or why the host did not provide it; a provider that
|
|
* does not read commits returns `unavailable`.
|
|
* @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts.
|
|
*/
|
|
async compare(ref: ChangeRequestRef, base: string, head: string, signal: AbortSignal): Promise<string | ForgeFailure> {
|
|
return await this.invoke(this.registration(ref.repository.forge), signal,
|
|
(provider, operation) => provider.commits === undefined || provider.compare === undefined
|
|
? Promise.resolve({ code: 'unavailable', message: 'This provider does not read commits' } as const)
|
|
: provider.compare(ref, base, head, operation))
|
|
}
|
|
|
|
/**
|
|
* Find the merge base of two commits of a change request's repository: the commit whose files the old side of the
|
|
* change request's diff shows when `base` is the snapshot's `baseSha` and `head` its `headSha`.
|
|
* @param ref - change request served by a registered provider.
|
|
* @param base - full object name of the base commit.
|
|
* @param head - full object name of the head commit.
|
|
* @param signal - cancellation of the read.
|
|
* @returns the merge base's full object name, or why the host did not provide it; `unsupported` when the provider
|
|
* cannot name merge bases.
|
|
* @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts.
|
|
*/
|
|
async mergeBase(ref: ChangeRequestRef, base: string, head: string, signal: AbortSignal): Promise<string | ForgeFailure> {
|
|
return await this.invoke(this.registration(ref.repository.forge), signal,
|
|
(provider, operation) => provider.mergeBase?.(ref, base, head, operation)
|
|
?? Promise.resolve({ code: 'unsupported', message: 'This provider does not name merge bases' } as const))
|
|
}
|
|
|
|
/**
|
|
* Publish one comment or a completed review, then refresh the watched status; a publication the host took is announced
|
|
* with `forge/review-changed`.
|
|
* @param ref - change request served by a registered provider.
|
|
* @param request - explicitly selected commit, comments, and review decision.
|
|
* @param signal - request cancellation.
|
|
* @returns a publication URL or a failure, including an unknown write outcome.
|
|
*/
|
|
async submitReview(ref: ChangeRequestRef, request: ForgeReviewRequest, signal: AbortSignal): Promise<ForgeReviewResult> {
|
|
const result = await this.invoke(this.registration(ref.repository.forge), signal,
|
|
(provider, operation) => provider.submitReview?.(ref, request, operation)
|
|
?? Promise.resolve({ ok: false, code: 'unsupported', message: 'This provider does not support review submission' } as const))
|
|
this.refresh(ref)
|
|
if (result.ok) this.reviewChanged(ref, { kind: 'submit', headSha: request.headSha })
|
|
return result
|
|
}
|
|
|
|
/**
|
|
* Read the text of one file at a commit of a change request's repository.
|
|
* @param ref - change request served by a registered provider.
|
|
* @param commit - commit object name.
|
|
* @param path - path relative to the repository root.
|
|
* @param signal - cancellation of the read.
|
|
* @returns the text, or why the host did not provide it.
|
|
* @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts.
|
|
*/
|
|
async fileText(ref: ChangeRequestRef, commit: string, path: string, signal: AbortSignal): Promise<string | ForgeFailure> {
|
|
return await this.invoke(this.registration(ref.repository.forge), signal,
|
|
(provider, operation) => provider.fileText(ref, commit, path, operation))
|
|
}
|
|
|
|
/**
|
|
* Build the web page of one file at a commit of a change request's repository.
|
|
* @param ref - change request served by a registered provider.
|
|
* @param commit - commit object name.
|
|
* @param path - path relative to the repository root.
|
|
* @returns the provider's URL.
|
|
* @throws when no provider serves the change request's forge.
|
|
*/
|
|
fileUrl(ref: ChangeRequestRef, commit: string, path: string): string {
|
|
return this.provider(ref.repository.forge).fileUrl(ref, commit, path)
|
|
}
|
|
|
|
/**
|
|
* Watch one change request as an effect on the calling fiber. The first
|
|
* watcher starts polling at once; listeners receive every later result,
|
|
* and `latest` returns the current one. Polling stops when the last watcher
|
|
* leaves. Listeners must not throw; a thrown error is logged and skipped.
|
|
* @param ref - change request to poll.
|
|
* @param listener - receives each polling result.
|
|
* @returns the disposer that stops this watch.
|
|
*/
|
|
watch(ref: ChangeRequestRef, listener: ChangeRequestListener): () => void {
|
|
const key = changeRequestKey(ref)
|
|
const dispose = this.ctx.effect(() => {
|
|
let watch = this.watches.get(key)
|
|
if (watch === undefined) {
|
|
watch = { key, ref, listeners: new Set(), latest: undefined, dueAt: Date.now(), failures: 0, staleHead: undefined }
|
|
this.watches.set(key, watch)
|
|
this.schedule()
|
|
}
|
|
const owned = watch
|
|
owned.listeners.add(listener)
|
|
return () => {
|
|
owned.listeners.delete(listener)
|
|
if (owned.listeners.size === 0 && this.watches.get(key) === owned) {
|
|
this.watches.delete(key)
|
|
this.schedule()
|
|
}
|
|
}
|
|
}, 'forge.watch()')
|
|
return () => void dispose()
|
|
}
|
|
|
|
/**
|
|
* Poll a watched change request at once, including after a terminal state.
|
|
* A fetch already in flight is followed immediately by another fetch; an
|
|
* unwatched change request is unchanged.
|
|
* @param ref - change request to poll.
|
|
*/
|
|
refresh(ref: ChangeRequestRef): void {
|
|
const watch = this.watches.get(changeRequestKey(ref))
|
|
if (watch === undefined) return
|
|
watch.dueAt = Date.now()
|
|
this.schedule()
|
|
}
|
|
|
|
/**
|
|
* Read the latest polling result of a watched change request.
|
|
* @param ref - change request to read.
|
|
* @returns the latest result, or undefined before the first result or without a watch.
|
|
*/
|
|
latest(ref: ChangeRequestRef): ChangeRequestUpdate | undefined {
|
|
return this.watches.get(changeRequestKey(ref))?.latest
|
|
}
|
|
|
|
/** Poll a watched change request at once after the first `stale` read or write at `headSha`; later ones wait for the regular poll. */
|
|
private staleRead(ref: ChangeRequestRef, headSha: string, code: ForgeFailure['code']): void {
|
|
const watch = this.watches.get(changeRequestKey(ref))
|
|
if (code !== 'stale' || watch === undefined || watch.staleHead === headSha) return
|
|
watch.staleHead = headSha
|
|
this.refresh(ref)
|
|
}
|
|
|
|
/**
|
|
* Run one optional provider action, then poll the change request at once when it is watched and the provider has the
|
|
* action.
|
|
* @param ref - change request served by a registered provider.
|
|
* @param signal - cancellation of the action.
|
|
* @param pick - the provider's action, or undefined when it lacks the capability.
|
|
* @param missing - what a provider without the action does not do, for its failure.
|
|
* @param run - calls the action.
|
|
* @returns the action's failure, or undefined once the host accepted it.
|
|
*/
|
|
private async act<A>(
|
|
ref: ChangeRequestRef,
|
|
signal: AbortSignal,
|
|
pick: (provider: ForgeProvider) => A | undefined,
|
|
missing: string,
|
|
run: (action: A, signal: AbortSignal) => Promise<ForgeActionFailure | undefined>,
|
|
): Promise<ForgeActionFailure | undefined> {
|
|
// Null stands for a provider without the action, which the host was never asked about.
|
|
const failure = await this.invoke(this.registration(ref.repository.forge), signal, (provider, operation) => {
|
|
const action = pick(provider)
|
|
return action === undefined ? Promise.resolve(null) : run(action, operation)
|
|
})
|
|
if (failure === null) return { code: 'failed', message: `This provider ${missing}` }
|
|
this.refresh(ref)
|
|
return failure
|
|
}
|
|
|
|
private provider(forge: string): ForgeProvider {
|
|
return this.registration(forge).provider
|
|
}
|
|
|
|
private providersChanged(forge: string): void {
|
|
this.announce('provider change', () => this.ctx.parallel('forge/providers-changed', forge))
|
|
}
|
|
|
|
private reviewChanged(ref: ChangeRequestRef, change: ForgeReviewChange): void {
|
|
this.announce('review change', () => this.ctx.parallel('forge/review-changed', ref, change))
|
|
}
|
|
|
|
/**
|
|
* Start one parallel dispatch unless the service stopped, keeping it among the work disposal waits for and logging
|
|
* listener failures.
|
|
*/
|
|
private announce(what: string, dispatch: () => Promise<void>): void {
|
|
if (this.lifetime.signal.aborted) return
|
|
const task = dispatch().catch((error: unknown) => {
|
|
this.ctx.logger.warn(`forge: ${what} listener failed: ${String(error)}`)
|
|
})
|
|
this.pending.add(task)
|
|
void task.then(() => this.pending.delete(task))
|
|
}
|
|
|
|
private registration(forge: string): Registration {
|
|
const registration = this.providers.get(forge)
|
|
if (registration === undefined) throw new Error(`forge: ${this.missing(forge).message}`)
|
|
return registration
|
|
}
|
|
|
|
private async invoke<T>(
|
|
registration: Registration,
|
|
signal: AbortSignal,
|
|
action: (provider: ForgeProvider, signal: AbortSignal) => Promise<T>,
|
|
): Promise<T> {
|
|
const operation = AbortSignal.any([signal, this.lifetime.signal, registration.lifetime.signal])
|
|
operation.throwIfAborted()
|
|
const completion = Promise.withResolvers<void>()
|
|
registration.pending.add(completion.promise)
|
|
this.pending.add(completion.promise)
|
|
try {
|
|
const result = await action(registration.provider, operation)
|
|
operation.throwIfAborted()
|
|
return result
|
|
} finally {
|
|
registration.pending.delete(completion.promise)
|
|
this.pending.delete(completion.promise)
|
|
completion.resolve()
|
|
}
|
|
}
|
|
|
|
private missing(forge: string): ForgeFailure {
|
|
return { code: 'unavailable', message: `no provider is registered for "${forge}"` }
|
|
}
|
|
|
|
private schedule(): void {
|
|
clearTimeout(this.timer)
|
|
this.timer = undefined
|
|
if (this.lifetime.signal.aborted) return
|
|
let next: number | undefined
|
|
for (const watch of this.watches.values()) {
|
|
if (watch.dueAt === undefined || this.fetching.has(watch.ref.repository.forge)) continue
|
|
next = next === undefined ? watch.dueAt : Math.min(next, watch.dueAt)
|
|
}
|
|
if (next === undefined) return
|
|
this.timer = setTimeout(this.tick, Math.max(0, next - Date.now()))
|
|
}
|
|
|
|
private poll(): void {
|
|
const now = Date.now()
|
|
const due = new Map<string, Watch[]>()
|
|
for (const watch of this.watches.values()) {
|
|
const forge = watch.ref.repository.forge
|
|
if (watch.dueAt === undefined || watch.dueAt > now || this.fetching.has(forge)) continue
|
|
const batch = due.get(forge)
|
|
if (batch === undefined) due.set(forge, [watch])
|
|
else batch.push(watch)
|
|
}
|
|
for (const [forge, batch] of due) {
|
|
const task = this.fetch(forge, batch)
|
|
this.pending.add(task)
|
|
void task.then(() => this.pending.delete(task))
|
|
}
|
|
this.schedule()
|
|
}
|
|
|
|
/** Fetch one forge's batch; never rejects. */
|
|
private async fetch(forge: string, batch: readonly Watch[]): Promise<void> {
|
|
this.fetching.add(forge)
|
|
for (const watch of batch) watch.dueAt = undefined
|
|
let results: FetchResults | undefined
|
|
let failure: ForgeFailure | undefined
|
|
const registration = this.providers.get(forge)
|
|
try {
|
|
if (registration === undefined) {
|
|
failure = this.missing(forge)
|
|
} else {
|
|
using timeout = deadline(this.lifetime.signal, this.config.fetchTimeoutMs, 'FORGE_FETCH_TIMEOUT')
|
|
results = await this.invoke(registration, timeout.signal,
|
|
(provider, operation) => provider.fetch(batch.map(watch => watch.ref), operation))
|
|
}
|
|
} catch (error) {
|
|
failure = { code: 'unavailable', message: error instanceof Error ? error.message : String(error) }
|
|
} finally {
|
|
this.fetching.delete(forge)
|
|
}
|
|
if (this.lifetime.signal.aborted) return
|
|
if (registration !== this.providers.get(forge)) {
|
|
this.schedule()
|
|
return
|
|
}
|
|
for (const watch of batch) {
|
|
if (this.watches.get(watch.key) !== watch) continue
|
|
const result = failure ?? results?.get(watch.key) ?? { code: 'unavailable', message: `provider returned no result for ${watch.key}` }
|
|
this.settle(watch, result, watch.dueAt)
|
|
}
|
|
this.schedule()
|
|
}
|
|
|
|
private settle(watch: Watch, result: ChangeRequestSnapshot | ForgeFailure, refreshAt: number | undefined): void {
|
|
const fetchedAt = Date.now()
|
|
let update: ChangeRequestUpdate
|
|
if ('code' in result) {
|
|
watch.failures++
|
|
update = { key: watch.key, fetchedAt, failure: result }
|
|
} else {
|
|
watch.failures = 0
|
|
update = { key: watch.key, fetchedAt, snapshot: result }
|
|
}
|
|
watch.latest = update
|
|
const delay = nextPollDelay(result, watch.failures, this.config)
|
|
// A refresh requested after this fetch started needs a subsequent fetch, even for a terminal result.
|
|
watch.dueAt = refreshAt ?? (delay === undefined ? undefined : fetchedAt + delay)
|
|
for (const listener of [...watch.listeners]) {
|
|
try {
|
|
listener(update)
|
|
} catch (error) {
|
|
this.ctx.logger.warn(`forge: change request listener failed: ${String(error)}`)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
export default ForgeService
|