The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import { isSshRemoteUrl } from "@t3tools/shared/sourceControl"; |
| 2 | import { parseDiffFilePaths } from "@t3tools/source-control-core/server/diffFileRevisions"; |
| 3 | import * as Cache from "effect/Cache"; |
| 4 | import * as Cause from "effect/Cause"; |
| 5 | import * as Clock from "effect/Clock"; |
| 6 | import * as Context from "effect/Context"; |
| 7 | import * as DateTime from "effect/DateTime"; |
| 8 | import * as Duration from "effect/Duration"; |
| 9 | import * as Effect from "effect/Effect"; |
| 10 | import * as Exit from "effect/Exit"; |
| 11 | import * as Layer from "effect/Layer"; |
| 12 | import * as PubSub from "effect/PubSub"; |
| 13 | import * as Option from "effect/Option"; |
| 14 | import * as Schema from "effect/Schema"; |
| 15 | import type * as Scope from "effect/Scope"; |
| 16 | import * as Stream from "effect/Stream"; |
| 17 | import * as SubscriptionRef from "effect/SubscriptionRef"; |
| 18 | import { |
| 19 | PullRequestOperationError, |
| 20 | PullRequestUnavailableError, |
| 21 | resolvePullRequestAuthorFilter, |
| 22 | type OrchestrationProjectShell, |
| 23 | type ProjectId, |
| 24 | type PullRequestAction, |
| 25 | type PullRequestActionInput, |
| 26 | type PullRequestActivity, |
| 27 | type PullRequestCommentInput, |
| 28 | type PullRequestCommentUpdateInput, |
| 29 | type PullRequestDetail, |
| 30 | type PullRequestPreview, |
| 31 | type PullRequestChecks, |
| 32 | type PullRequestDiffFileContentsInput, |
| 33 | type PullRequestDiffFileContentsResult, |
| 34 | type PullRequestDiffStat, |
| 35 | type PullRequestDiffInput, |
| 36 | type PullRequestChangeBreakdown, |
| 37 | type PullRequestFilesViewedResult, |
| 38 | type PullRequestDiffResult, |
| 39 | type PullRequestInvalidateInput, |
| 40 | type PullRequestReportStateInput, |
| 41 | type PullRequestListEntry, |
| 42 | type PullRequestListFilters, |
| 43 | type PullRequestListInput, |
| 44 | type PullRequestListProjectError, |
| 45 | type PullRequestListResult, |
| 46 | type PullRequestListStatsInput, |
| 47 | type PullRequestFilterOptions, |
| 48 | type PullRequestFilterOptionsInput, |
| 49 | type PullRequestActor, |
| 50 | type PullRequestReferenceCandidate, |
| 51 | type PullRequestLabel, |
| 52 | type PullRequestListStatsResult, |
| 53 | type PullRequestProviderSummary, |
| 54 | type PullRequestReactionInput, |
| 55 | type PullRequestRef, |
| 56 | type PullRequestRoutingResult, |
| 57 | type PullRequestRoutingIdentityInput, |
| 58 | type PullRequestRoutingIdentityResult, |
| 59 | type PullRequestReviewVerdict, |
| 60 | type PullRequestReviewerCandidateList, |
| 61 | type PullRequestReviewerCandidatesInput, |
| 62 | type PullRequestReviewerRequestInput, |
| 63 | type PullRequestLabelCandidateList, |
| 64 | type PullRequestLabelChangeInput, |
| 65 | type PullRequestSetFilesViewedInput, |
| 66 | type PullRequestState, |
| 67 | type PullRequestSubmitReviewInput, |
| 68 | PullRequestStack, |
| 69 | PullRequestSummary, |
| 70 | type PullRequestThreadReplyInput, |
| 71 | type PullRequestThreadResolutionInput, |
| 72 | type PullRequestThreadCommentsInput, |
| 73 | type PullRequestThreadCommentsResult, |
| 74 | type PullRequestUpdateInput, |
| 75 | type SourceControlProviderInfo, |
| 76 | SourceControlProviderKind, |
| 77 | type ThreadPullRequestKey, |
| 78 | } from "@t3tools/contracts"; |
| 79 | import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; |
| 80 | import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts"; |
| 81 | |
| 82 | import * as ProjectService from "../project/ProjectService.ts"; |
| 83 | import * as ServerSettings from "../serverSettings.ts"; |
| 84 | import * as PullRequestFilesViewed from "../persistence/PullRequestFilesViewed.ts"; |
| 85 | import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts"; |
| 86 | import * as SourceControlProviderRegistry from "../sourceControl/SourceControlProviderRegistry.ts"; |
| 87 | import type { SourceControlProviderContext } from "@t3tools/source-control-core/server/SourceControlProvider"; |
| 88 | import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit"; |
| 89 | import { |
| 90 | type ProviderChangeRequest, |
| 91 | type ProviderChangeRequestDetail, |
| 92 | type ProviderCheckLog, |
| 93 | type ProviderCheckRerun, |
| 94 | type ProviderDiffFilePaths, |
| 95 | type ProviderFilterOptionPage, |
| 96 | type ProviderListCursor, |
| 97 | type ProviderChangeRequestSummary, |
| 98 | type ProviderChangeRequestWatchFingerprint, |
| 99 | type PullRequestProviderApi, |
| 100 | PullRequestProviderError, |
| 101 | } from "@t3tools/source-control-core/server/PullRequestProvider"; |
| 102 | import * as PullRequestReadCache from "./PullRequestReadCache.ts"; |
| 103 | import * as PullRequestProviderRegistry from "./PullRequestProviderRegistry.ts"; |
| 104 | import * as ViewedFiles from "./pullRequestViewedFiles.ts"; |
| 105 | import { toChangeBreakdown } from "./pullRequestChangeBreakdown.ts"; |
| 106 | |
| 107 | export interface PullRequestMergeEvent extends PullRequestRef { |
| 108 | readonly mergedAt: string; |
| 109 | } |
| 110 | |
| 111 | type PullRequestReading = Pick< |
| 112 | PullRequestSummary, |
| 113 | "state" | "isDraft" | "updatedAt" | "observedAt" |
| 114 | >; |
| 115 | |
| 116 | function supersedesReading(current: PullRequestReading | undefined, next: PullRequestReading) { |
| 117 | if (current === undefined) return true; |
| 118 | if (current.state === "merged" && next.state !== "merged") return false; |
| 119 | if (next.updatedAt !== current.updatedAt) return next.updatedAt > current.updatedAt; |
| 120 | return (next.observedAt ?? -Infinity) >= (current.observedAt ?? -Infinity); |
| 121 | } |
| 122 | |
| 123 | // Providers request one extra row; 99 stays within GitHub/GitLab's 100-row API limit. |
| 124 | const DEFAULT_REPOSITORY_LIST_LIMIT = 99; |
| 125 | const REPOSITORY_CONCURRENCY = 12; |
| 126 | const REPOSITORY_SEARCH_CHUNK = 100; |
| 127 | const FILTERED_LIST_READS = 5; |
| 128 | |
| 129 | // Host reads spawn CLIs and hit low quotas; briefly share results and identical in-flight reads. |
| 130 | const LIST_CACHE_TTL = Duration.seconds(30); |
| 131 | const DETAIL_CACHE_TTL = Duration.seconds(60); |
| 132 | const MERGED_DETAIL_CACHE_TTL = Duration.minutes(10); |
| 133 | const detailTimeToLive = (state: PullRequestState | undefined) => |
| 134 | state === "merged" ? MERGED_DETAIL_CACHE_TTL : DETAIL_CACHE_TTL; |
| 135 | const CHECKS_CACHE_TTL = Duration.seconds(15); |
| 136 | const REPORTED_STATE_DEDUPE_MS = 5 * 60 * 1_000; |
| 137 | const DIFF_CACHE_TTL = Duration.seconds(60); |
| 138 | const COMMIT_DIFF_CACHE_TTL = Duration.minutes(10); |
| 139 | const LIST_STATS_CACHE_TTL = Duration.seconds(60); |
| 140 | const FILES_VIEWED_CACHE_TTL = Duration.seconds(15); |
| 141 | const DIFF_STALE_WINDOW = Duration.minutes(10); |
| 142 | const DIFF_SWEEP_INTERVAL = Duration.minutes(1); |
| 143 | const VIEWER_CACHE_TTL = Duration.minutes(10); |
| 144 | const STALE_DETAIL_WINDOW = Duration.minutes(10); |
| 145 | const isPullRequestProviderError = Schema.is(PullRequestProviderError); |
| 146 | const LIST_CACHE_CAPACITY = 64; |
| 147 | const LIST_STATS_CACHE_CAPACITY = 32; |
| 148 | const DETAIL_CACHE_CAPACITY = 128; |
| 149 | const DIFF_CACHE_CAPACITY = 128; |
| 150 | // Each holder stays within this UTF-16 patch budget as well as its entry-count bound. |
| 151 | const DIFF_CACHE_PATCH_BUDGET_BYTES = 32 * 1024 * 1024; |
| 152 | const canCacheDiff = (value: PullRequestDiffResult) => |
| 153 | value.patch.length * 2 <= DIFF_CACHE_PATCH_BUDGET_BYTES; |
| 154 | const diffCacheEvictions = (entries: Iterable<readonly [string, PullRequestDiffResult]>) => { |
| 155 | let bytes = 0; |
| 156 | const evictions: string[] = []; |
| 157 | for (const [key, value] of Array.from(entries).toReversed()) { |
| 158 | const size = value.patch.length * 2; |
| 159 | if (bytes + size > DIFF_CACHE_PATCH_BUDGET_BYTES) { |
| 160 | evictions.push(key); |
| 161 | } else { |
| 162 | bytes += size; |
| 163 | } |
| 164 | } |
| 165 | return evictions; |
| 166 | }; |
| 167 | const FILES_VIEWED_CACHE_CAPACITY = 128; |
| 168 | const VIEWER_CACHE_CAPACITY = 32; |
| 169 | |
| 170 | export type PullRequestError = PullRequestUnavailableError | PullRequestOperationError; |
| 171 | |
| 172 | const routingCredential = Context.Reference<{ |
| 173 | readonly credentialFingerprint: string; |
| 174 | readonly viewer: string; |
| 175 | } | null>("t3/PullRequestService/routingCredential", { defaultValue: () => null }); |
| 176 | const credentialNamespace = Symbol("pullRequestCredentialNamespace"); |
| 177 | type CredentialRef = PullRequestRef & { readonly [credentialNamespace]?: string }; |
| 178 | |
| 179 | export class PullRequestService extends Context.Service< |
| 180 | PullRequestService, |
| 181 | { |
| 182 | readonly list: ( |
| 183 | input: PullRequestListInput, |
| 184 | ) => Effect.Effect<PullRequestListResult, PullRequestError>; |
| 185 | readonly listStats: ( |
| 186 | input: PullRequestListStatsInput, |
| 187 | ) => Effect.Effect<PullRequestListStatsResult, PullRequestError>; |
| 188 | readonly filterOptions: ( |
| 189 | input: PullRequestFilterOptionsInput, |
| 190 | ) => Effect.Effect<PullRequestFilterOptions, PullRequestError>; |
| 191 | readonly routing: ( |
| 192 | input: PullRequestRef, |
| 193 | ) => Effect.Effect<PullRequestRoutingResult, PullRequestError>; |
| 194 | readonly routingIdentity: ( |
| 195 | input: PullRequestRoutingIdentityInput, |
| 196 | ) => Effect.Effect<PullRequestRoutingIdentityResult, PullRequestError>; |
| 197 | readonly withRoutingCredential: <A, E, R>( |
| 198 | input: PullRequestRef, |
| 199 | operation: Effect.Effect<A, E, R>, |
| 200 | ) => Effect.Effect<A, E | PullRequestError, R>; |
| 201 | readonly summary: ( |
| 202 | input: PullRequestRef, |
| 203 | options?: { |
| 204 | readonly recoverTransientFailure?: boolean; |
| 205 | /** Registration preflights must reach the provider despite a successful cached read. */ |
| 206 | readonly bypassCache?: boolean; |
| 207 | }, |
| 208 | ) => Effect.Effect<PullRequestSummary, PullRequestError>; |
| 209 | /** Whether the reference's host batches summary reads; false when it cannot be resolved. */ |
| 210 | readonly batchesReads: (input: PullRequestRef) => Effect.Effect<boolean>; |
| 211 | readonly stack: ( |
| 212 | input: PullRequestRef, |
| 213 | options?: { |
| 214 | readonly includeDetails?: boolean; |
| 215 | /** A merge pins these heads, so it must not read them from the cache. */ |
| 216 | readonly bypassCache?: boolean; |
| 217 | }, |
| 218 | ) => Effect.Effect<PullRequestStack | null, PullRequestError>; |
| 219 | readonly subscribeMerges: Effect.Effect< |
| 220 | Stream.Stream<PullRequestMergeEvent>, |
| 221 | never, |
| 222 | Scope.Scope |
| 223 | >; |
| 224 | readonly subscribeStateChanges: Effect.Effect< |
| 225 | Stream.Stream<ThreadPullRequestKey>, |
| 226 | never, |
| 227 | Scope.Scope |
| 228 | >; |
| 229 | readonly reportState: ( |
| 230 | input: PullRequestReportStateInput, |
| 231 | ) => Effect.Effect<void, PullRequestError>; |
| 232 | readonly subscribeRefreshes: Stream.Stream<number>; |
| 233 | readonly subscribeLinkedThreadRefreshes: Stream.Stream<number>; |
| 234 | /** Wakes linked-thread readers only; other pull request reads don't depend on thread links. */ |
| 235 | readonly notifyLinkedThreadsChanged: Effect.Effect<void>; |
| 236 | readonly refreshAfterTurn: ( |
| 237 | projectId: ProjectId, |
| 238 | options?: { readonly pushed?: boolean }, |
| 239 | ) => Effect.Effect<void>; |
| 240 | /** Project and remote lookups inside `effect` read once per filter, e.g. across one sync sweep. */ |
| 241 | readonly withSharedProjectReads: <A, E, R>( |
| 242 | effect: Effect.Effect<A, E, R>, |
| 243 | ) => Effect.Effect<A, E, R>; |
| 244 | readonly detail: (input: PullRequestRef) => Effect.Effect<PullRequestDetail, PullRequestError>; |
| 245 | readonly preview: ( |
| 246 | input: PullRequestRef, |
| 247 | ) => Effect.Effect<PullRequestPreview, PullRequestError>; |
| 248 | readonly checks: ( |
| 249 | input: PullRequestRef, |
| 250 | ) => Effect.Effect<PullRequestChecks | null, PullRequestError>; |
| 251 | readonly watchFingerprint: ( |
| 252 | input: PullRequestRef, |
| 253 | ) => Effect.Effect<ProviderChangeRequestWatchFingerprint | null, PullRequestError>; |
| 254 | readonly activity: ( |
| 255 | input: PullRequestRef, |
| 256 | ) => Effect.Effect<PullRequestActivity, PullRequestError>; |
| 257 | /** Emits when the host reports a change; empty where the host has no event feed. */ |
| 258 | readonly changes: (input: PullRequestRef) => Stream.Stream<void>; |
| 259 | /** Whether the project's checkout is on a forge T3 reads change requests from. */ |
| 260 | readonly servesProject: (projectId: ProjectId) => Effect.Effect<boolean>; |
| 261 | readonly threadComments: ( |
| 262 | input: PullRequestThreadCommentsInput, |
| 263 | ) => Effect.Effect<PullRequestThreadCommentsResult, PullRequestError>; |
| 264 | readonly diff: ( |
| 265 | input: PullRequestDiffInput, |
| 266 | ) => Effect.Effect<PullRequestDiffResult, PullRequestError>; |
| 267 | readonly diffFileContents: ( |
| 268 | input: PullRequestDiffFileContentsInput, |
| 269 | ) => Effect.Effect<PullRequestDiffFileContentsResult, PullRequestError>; |
| 270 | readonly filesViewed: ( |
| 271 | input: PullRequestRef, |
| 272 | ) => Effect.Effect<PullRequestFilesViewedResult, PullRequestError>; |
| 273 | readonly setFilesViewed: ( |
| 274 | input: PullRequestSetFilesViewedInput, |
| 275 | ) => Effect.Effect<void, PullRequestError>; |
| 276 | readonly changeBreakdown: ( |
| 277 | input: PullRequestRef, |
| 278 | ) => Effect.Effect<PullRequestChangeBreakdown, PullRequestError>; |
| 279 | readonly runAction: ( |
| 280 | input: PullRequestActionInput, |
| 281 | ) => Effect.Effect<PullRequestSummary | undefined, PullRequestError>; |
| 282 | /** Tails of the failing checks' logs, or only the named check's. */ |
| 283 | readonly checkLogs: ( |
| 284 | input: PullRequestRef & { readonly check?: string; readonly tailLines: number }, |
| 285 | ) => Effect.Effect<ReadonlyArray<ProviderCheckLog>, PullRequestError>; |
| 286 | /** Re-runs the failing checks, or only the named check. */ |
| 287 | readonly rerunChecks: ( |
| 288 | input: PullRequestRef & { readonly check?: string }, |
| 289 | ) => Effect.Effect<ReadonlyArray<ProviderCheckRerun>, PullRequestError>; |
| 290 | readonly update: (input: PullRequestUpdateInput) => Effect.Effect<void, PullRequestError>; |
| 291 | readonly comment: (input: PullRequestCommentInput) => Effect.Effect<void, PullRequestError>; |
| 292 | readonly updateComment: ( |
| 293 | input: PullRequestCommentUpdateInput, |
| 294 | ) => Effect.Effect<void, PullRequestError>; |
| 295 | readonly submitReview: ( |
| 296 | input: PullRequestSubmitReviewInput, |
| 297 | ) => Effect.Effect<void, PullRequestError>; |
| 298 | readonly replyToThread: ( |
| 299 | input: PullRequestThreadReplyInput, |
| 300 | ) => Effect.Effect<void, PullRequestError>; |
| 301 | readonly setThreadResolution: ( |
| 302 | input: PullRequestThreadResolutionInput, |
| 303 | ) => Effect.Effect<void, PullRequestError>; |
| 304 | readonly setReaction: ( |
| 305 | input: PullRequestReactionInput, |
| 306 | ) => Effect.Effect<void, PullRequestError>; |
| 307 | readonly reviewerCandidates: ( |
| 308 | input: PullRequestReviewerCandidatesInput, |
| 309 | ) => Effect.Effect<PullRequestReviewerCandidateList, PullRequestError>; |
| 310 | readonly requestReviewers: ( |
| 311 | input: PullRequestReviewerRequestInput, |
| 312 | ) => Effect.Effect<void, PullRequestError>; |
| 313 | readonly labelCandidates: ( |
| 314 | input: PullRequestRef, |
| 315 | ) => Effect.Effect<PullRequestLabelCandidateList, PullRequestError>; |
| 316 | readonly setLabels: ( |
| 317 | input: PullRequestLabelChangeInput, |
| 318 | ) => Effect.Effect<void, PullRequestError>; |
| 319 | readonly invalidate: ( |
| 320 | input: PullRequestInvalidateInput, |
| 321 | options?: { readonly notifyReaders?: boolean }, |
| 322 | ) => Effect.Effect<void>; |
| 323 | } |
| 324 | >()("t3/pullRequest/PullRequestService") {} |
| 325 | |
| 326 | const VERDICT_LABELS: Record<PullRequestReviewVerdict, string> = { |
| 327 | comment: "review", |
| 328 | approve: "approve", |
| 329 | "request-changes": "request changes on", |
| 330 | }; |
| 331 | |
| 332 | const ACTION_ACCESS_REFUSALS: Record<PullRequestAction, string> = { |
| 333 | merge: "You need write access on this repository to merge.", |
| 334 | ready: |
| 335 | "You need write access on this repository, or to have opened this change request, to mark it ready for review.", |
| 336 | draft: |
| 337 | "You need write access on this repository, or to have opened this change request, to return it to a draft.", |
| 338 | close: |
| 339 | "You need write access on this repository, or to have opened this change request, to close it.", |
| 340 | "update-branch": |
| 341 | "You need write access on this repository, or to have opened this change request, to update its branch.", |
| 342 | reopen: |
| 343 | "You need write access on this repository, or to have opened this change request, to reopen it.", |
| 344 | "enable-auto-merge": |
| 345 | "Auto-merge needs write access on this repository, and the repository has to allow it.", |
| 346 | "disable-auto-merge": |
| 347 | "You need write access on this repository to stop it being merged for you once it is ready.", |
| 348 | revert: "You need write access on this repository to open a revert pull request.", |
| 349 | "delete-branch": "You need write access on the source repository to delete its branch.", |
| 350 | "approve-workflows": |
| 351 | "You need write access on this repository to approve workflows from a fork pull request.", |
| 352 | }; |
| 353 | |
| 354 | const REVIEWER_REQUEST_REFUSAL = "You need write access on this repository to ask for a review."; |
| 355 | const LABEL_CHANGE_REFUSAL = "You need triage access on this repository to change its labels."; |
| 356 | |
| 357 | export interface SupportedProject { |
| 358 | readonly cursorKey: string; |
| 359 | readonly project: OrchestrationProjectShell; |
| 360 | readonly api: PullRequestProviderApi; |
| 361 | readonly repository: string; |
| 362 | readonly host: string; |
| 363 | /** Unlike Azure repository names, remotes are unique across an organization. */ |
| 364 | readonly remote: string; |
| 365 | readonly repositoryKey: string | null; |
| 366 | } |
| 367 | |
| 368 | interface WorkspaceProjects { |
| 369 | readonly supported: ReadonlyArray<SupportedProject>; |
| 370 | readonly unimplemented: ReadonlyMap< |
| 371 | string, |
| 372 | { readonly kind: SourceControlProviderKind; readonly projectCount: number } |
| 373 | >; |
| 374 | readonly viewerRoots: ReadonlyMap<string, ReadonlyArray<string>>; |
| 375 | readonly refinedProjectIdsByHost: ReadonlyMap<string, ReadonlyArray<ProjectId>>; |
| 376 | } |
| 377 | |
| 378 | // Inherited by fibers forked inside the scope, so it is closed, not just dropped, when the scope ends. |
| 379 | const sharedProjectReads = Context.Reference<{ |
| 380 | open: boolean; |
| 381 | readonly reads: Map<string, Effect.Effect<WorkspaceProjects, PullRequestError>>; |
| 382 | } | null>("t3/PullRequestService/sharedProjectReads", { defaultValue: () => null }); |
| 383 | |
| 384 | interface RepositoryBatch { |
| 385 | readonly key: string; |
| 386 | readonly entries: ReadonlyArray<PullRequestListEntry>; |
| 387 | readonly errors: ReadonlyArray<PullRequestListProjectError>; |
| 388 | readonly truncated: boolean; |
| 389 | readonly nextCursor: string | null; |
| 390 | } |
| 391 | |
| 392 | interface ListCursor extends ProviderListCursor { |
| 393 | readonly seenAt: ReadonlyArray<number>; |
| 394 | } |
| 395 | |
| 396 | const LIST_CURSOR_PATTERN = |
| 397 | /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2}))\|(\d{1,9})\|(\d{1,9}(?:,\d{1,9})*)?(?:\|([\w.:~+-]{1,128}))?$/; |
| 398 | |
| 399 | function parseListCursor(raw: string): ListCursor | null { |
| 400 | const match = LIST_CURSOR_PATTERN.exec(raw); |
| 401 | if (match === null) return null; |
| 402 | const seenAt = match[3]; |
| 403 | return { |
| 404 | updatedBefore: match[1]!, |
| 405 | delivered: Number(match[2]), |
| 406 | seenAt: seenAt === undefined ? [] : seenAt.split(",").map(Number), |
| 407 | ...(match[4] === undefined ? {} : { resumeAfter: match[4] }), |
| 408 | }; |
| 409 | } |
| 410 | |
| 411 | function listCursorKey(host: string, repository: string): string { |
| 412 | return `${host} ${repository.toLowerCase()}`; |
| 413 | } |
| 414 | |
| 415 | // Preserve exclusions across slices sharing a timestamp to avoid redelivery. |
| 416 | function nextListCursor( |
| 417 | previous: ListCursor | undefined, |
| 418 | fetched: ReadonlyArray<ProviderChangeRequest>, |
| 419 | delivered: ReadonlyArray<ProviderChangeRequest>, |
| 420 | /** A provider may consume malformed offset-paged rows that never appear in `delivered`. */ |
| 421 | cursorAdvance = delivered.length, |
| 422 | resumeAfter?: string, |
| 423 | ): string | null { |
| 424 | if (fetched.length === 0) return null; |
| 425 | // Use all fetched rows: a slice containing only duplicates must still advance to older rows. |
| 426 | const oldest = fetched.reduce((left, right) => (right.updatedAt < left.updatedAt ? right : left)); |
| 427 | return listCursorAt(previous, oldest.updatedAt, fetched, cursorAdvance, resumeAfter); |
| 428 | } |
| 429 | |
| 430 | function listCursorAt( |
| 431 | previous: ListCursor | undefined, |
| 432 | boundary: string, |
| 433 | fetched: ReadonlyArray<ProviderChangeRequest>, |
| 434 | deliveredCount: number, |
| 435 | resumeAfter?: string, |
| 436 | ): string { |
| 437 | const seenAt = new Set([ |
| 438 | ...(previous?.updatedBefore === boundary ? previous.seenAt : []), |
| 439 | ...fetched.filter((item) => item.updatedAt === boundary).map((item) => item.number), |
| 440 | ]); |
| 441 | const cursor = `${boundary}|${(previous?.delivered ?? 0) + deliveredCount}|${[...seenAt].join(",")}`; |
| 442 | return resumeAfter === undefined ? cursor : `${cursor}|${resumeAfter}`; |
| 443 | } |
| 444 | |
| 445 | function isProviderUnusable(error: PullRequestProviderError): boolean { |
| 446 | return error.reason === "missing-tool" || error.reason === "unauthenticated"; |
| 447 | } |
| 448 | |
| 449 | type UnavailableRequirementOf = ( |
| 450 | kind: SourceControlProviderKind, |
| 451 | ) => PullRequestProviderApi["unavailableRequirement"]; |
| 452 | |
| 453 | function unavailableRequirement( |
| 454 | requirementOf: UnavailableRequirementOf, |
| 455 | error: PullRequestProviderError, |
| 456 | ): string | undefined { |
| 457 | const requirement = requirementOf(error.provider); |
| 458 | if (requirement === undefined) return undefined; |
| 459 | return error.reason === "missing-tool" ? requirement.missing : requirement.unauthenticated; |
| 460 | } |
| 461 | |
| 462 | function providerDetail( |
| 463 | requirementOf: UnavailableRequirementOf, |
| 464 | error: PullRequestProviderError, |
| 465 | ): string { |
| 466 | if (!isProviderUnusable(error)) return error.detail; |
| 467 | return unavailableRequirement(requirementOf, error) ?? error.detail; |
| 468 | } |
| 469 | |
| 470 | function toPullRequestErrorWith( |
| 471 | requirementOf: UnavailableRequirementOf, |
| 472 | ): (operation: string) => (error: PullRequestProviderError) => PullRequestError { |
| 473 | return (operation) => (error) => { |
| 474 | if (isProviderUnusable(error)) { |
| 475 | const requirement = unavailableRequirement(requirementOf, error); |
| 476 | return new PullRequestUnavailableError({ |
| 477 | reason: error.reason === "missing-tool" ? "cli-missing" : "cli-unauthenticated", |
| 478 | provider: error.provider, |
| 479 | ...(requirement === undefined ? {} : { requirement }), |
| 480 | cause: error, |
| 481 | }); |
| 482 | } |
| 483 | return new PullRequestOperationError({ |
| 484 | operation, |
| 485 | detail: error.detail, |
| 486 | ...(error.reason === "not-found" ? { reason: "not-found" as const } : {}), |
| 487 | cause: error, |
| 488 | }); |
| 489 | }; |
| 490 | } |
| 491 | |
| 492 | function withRateLimitBackoff( |
| 493 | api: PullRequestProviderApi, |
| 494 | host: string, |
| 495 | limits: SourceControlRateLimit.SourceControlRateLimit["Service"], |
| 496 | options?: { readonly viewerAllowsPause: boolean }, |
| 497 | ): PullRequestProviderApi { |
| 498 | const key = { provider: api.kind, host }; |
| 499 | const protect = <A>( |
| 500 | operation: string, |
| 501 | effect: Effect.Effect<A, PullRequestProviderError>, |
| 502 | alwaysInteractive: boolean, |
| 503 | ) => |
| 504 | SourceControlRateLimit.Interactive.pipe( |
| 505 | Effect.map((callerInteractive) => alwaysInteractive || callerInteractive), |
| 506 | Effect.flatMap((allowPaused) => |
| 507 | limits.check(key, allowPaused ? { allowPaused: true } : undefined).pipe( |
| 508 | Effect.mapError( |
| 509 | (error) => |
| 510 | new PullRequestProviderError({ |
| 511 | provider: api.kind, |
| 512 | operation, |
| 513 | reason: "rate-limited", |
| 514 | detail: error.detail, |
| 515 | retryAt: error.retryAt, |
| 516 | cause: error, |
| 517 | }), |
| 518 | ), |
| 519 | Effect.flatMap((lease) => |
| 520 | effect.pipe( |
| 521 | Effect.provideService(SourceControlRateLimit.Interactive, allowPaused), |
| 522 | Effect.tap(() => limits.recordSuccess({ ...key, lease })), |
| 523 | Effect.tapError((error) => |
| 524 | error.reason === "rate-limited" |
| 525 | ? limits.recordRateLimit({ |
| 526 | ...key, |
| 527 | lease, |
| 528 | ...(error.retryAt === undefined ? {} : { retryAt: error.retryAt }), |
| 529 | }) |
| 530 | : Effect.void, |
| 531 | ), |
| 532 | ), |
| 533 | ), |
| 534 | ), |
| 535 | ), |
| 536 | ); |
| 537 | const wrap = |
| 538 | <Args extends ReadonlyArray<unknown>, A>( |
| 539 | operation: string, |
| 540 | call: (...args: Args) => Effect.Effect<A, PullRequestProviderError>, |
| 541 | alwaysInteractive = false, |
| 542 | ) => |
| 543 | (...args: Args) => |
| 544 | protect(operation, call(...args), alwaysInteractive); |
| 545 | const interactive = <Args extends ReadonlyArray<unknown>, A>( |
| 546 | operation: string, |
| 547 | call: (...args: Args) => Effect.Effect<A, PullRequestProviderError>, |
| 548 | ) => wrap(operation, call, true); |
| 549 | |
| 550 | const wrapped = { |
| 551 | kind: api.kind, |
| 552 | capabilities: api.capabilities, |
| 553 | ...(api.mergeMessageRewrite === undefined |
| 554 | ? {} |
| 555 | : { mergeMessageRewrite: api.mergeMessageRewrite }), |
| 556 | ...(api.unavailableRequirement === undefined |
| 557 | ? {} |
| 558 | : { unavailableRequirement: api.unavailableRequirement }), |
| 559 | ...(api.repositoryKey === undefined ? {} : { repositoryKey: api.repositoryKey }), |
| 560 | ...(api.servesHost === undefined ? {} : { servesHost: api.servesHost }), |
| 561 | ...(api.readsPublicHostWithoutCheckout === undefined |
| 562 | ? {} |
| 563 | : { readsPublicHostWithoutCheckout: api.readsPublicHostWithoutCheckout }), |
| 564 | ...(api.batchesReads === undefined ? {} : { batchesReads: api.batchesReads }), |
| 565 | getViewer: |
| 566 | options?.viewerAllowsPause === true |
| 567 | ? interactive("getViewer", api.getViewer) |
| 568 | : wrap("getViewer", api.getViewer), |
| 569 | ...(api.getRoutingIdentity === undefined ? {} : { getRoutingIdentity: api.getRoutingIdentity }), |
| 570 | ...(api.withVerifiedCredential === undefined |
| 571 | ? {} |
| 572 | : { withVerifiedCredential: api.withVerifiedCredential }), |
| 573 | listChangeRequests: wrap("listChangeRequests", api.listChangeRequests), |
| 574 | ...(api.listChangeRequestsAcross === undefined |
| 575 | ? {} |
| 576 | : { |
| 577 | listChangeRequestsAcross: wrap("listChangeRequestsAcross", api.listChangeRequestsAcross), |
| 578 | }), |
| 579 | ...(api.listChangeRequestStats === undefined |
| 580 | ? {} |
| 581 | : { |
| 582 | listChangeRequestStats: wrap("listChangeRequestStats", api.listChangeRequestStats), |
| 583 | }), |
| 584 | getChangeRequest: wrap("getChangeRequest", api.getChangeRequest), |
| 585 | ...(api.forgetChangeRequestReads === undefined |
| 586 | ? {} |
| 587 | : { forgetChangeRequestReads: api.forgetChangeRequestReads }), |
| 588 | ...(api.getChangeRequestPreview === undefined |
| 589 | ? {} |
| 590 | : { getChangeRequestPreview: wrap("getChangeRequestPreview", api.getChangeRequestPreview) }), |
| 591 | ...(api.getChangeRequestChecks === undefined |
| 592 | ? {} |
| 593 | : { getChangeRequestChecks: wrap("getChangeRequestChecks", api.getChangeRequestChecks) }), |
| 594 | ...(api.getChangeRequestSummary === undefined |
| 595 | ? {} |
| 596 | : { |
| 597 | getChangeRequestSummary: wrap("getChangeRequestSummary", api.getChangeRequestSummary), |
| 598 | }), |
| 599 | ...(api.getChangeRequestStack === undefined |
| 600 | ? {} |
| 601 | : { getChangeRequestStack: wrap("getChangeRequestStack", api.getChangeRequestStack) }), |
| 602 | ...(api.getChangeRequestWatchFingerprint === undefined |
| 603 | ? {} |
| 604 | : { |
| 605 | getChangeRequestWatchFingerprint: wrap( |
| 606 | "getChangeRequestWatchFingerprint", |
| 607 | api.getChangeRequestWatchFingerprint, |
| 608 | ), |
| 609 | }), |
| 610 | // A long-lived feed, not a read: the quota guard would hold its lease for hours. |
| 611 | ...(api.changeRequestEvents === undefined |
| 612 | ? {} |
| 613 | : { changeRequestEvents: api.changeRequestEvents }), |
| 614 | getChangeRequestActivity: wrap("getChangeRequestActivity", api.getChangeRequestActivity), |
| 615 | ...(api.getReviewThreadComments === undefined |
| 616 | ? {} |
| 617 | : { |
| 618 | getReviewThreadComments: wrap("getReviewThreadComments", api.getReviewThreadComments), |
| 619 | }), |
| 620 | getViewerPermissions: interactive("getViewerPermissions", api.getViewerPermissions), |
| 621 | getDiff: wrap("getDiff", api.getDiff), |
| 622 | ...(api.getDiffFilePaths === undefined |
| 623 | ? {} |
| 624 | : { getDiffFilePaths: wrap("getDiffFilePaths", api.getDiffFilePaths) }), |
| 625 | ...(api.getDiffFileContents === undefined |
| 626 | ? {} |
| 627 | : { getDiffFileContents: wrap("getDiffFileContents", api.getDiffFileContents) }), |
| 628 | ...(api.getFilesViewed === undefined |
| 629 | ? {} |
| 630 | : { getFilesViewed: wrap("getFilesViewed", api.getFilesViewed) }), |
| 631 | ...(api.getFileStats === undefined |
| 632 | ? {} |
| 633 | : { getFileStats: wrap("getFileStats", api.getFileStats) }), |
| 634 | ...(api.setFilesViewed === undefined |
| 635 | ? {} |
| 636 | : { setFilesViewed: interactive("setFilesViewed", api.setFilesViewed) }), |
| 637 | ...(api.getFileRevisions === undefined |
| 638 | ? {} |
| 639 | : { getFileRevisions: wrap("getFileRevisions", api.getFileRevisions) }), |
| 640 | runAction: interactive("runAction", api.runAction), |
| 641 | ...(api.getCheckLogs === undefined |
| 642 | ? {} |
| 643 | : { getCheckLogs: interactive("getCheckLogs", api.getCheckLogs) }), |
| 644 | ...(api.rerunChecks === undefined |
| 645 | ? {} |
| 646 | : { rerunChecks: interactive("rerunChecks", api.rerunChecks) }), |
| 647 | ...(api.updateChangeRequest === undefined |
| 648 | ? {} |
| 649 | : { |
| 650 | updateChangeRequest: interactive("updateChangeRequest", api.updateChangeRequest), |
| 651 | }), |
| 652 | comment: interactive("comment", api.comment), |
| 653 | ...(api.updateComment === undefined |
| 654 | ? {} |
| 655 | : { updateComment: interactive("updateComment", api.updateComment) }), |
| 656 | submitReview: interactive("submitReview", api.submitReview), |
| 657 | listReviewerCandidates: interactive("listReviewerCandidates", api.listReviewerCandidates), |
| 658 | setReviewerRequest: interactive("setReviewerRequest", api.setReviewerRequest), |
| 659 | ...(api.listLabelCandidates === undefined |
| 660 | ? {} |
| 661 | : { listLabelCandidates: interactive("listLabelCandidates", api.listLabelCandidates) }), |
| 662 | ...(api.setLabels === undefined ? {} : { setLabels: interactive("setLabels", api.setLabels) }), |
| 663 | ...(api.listRepositoryLabels === undefined |
| 664 | ? {} |
| 665 | : { listRepositoryLabels: interactive("listRepositoryLabels", api.listRepositoryLabels) }), |
| 666 | ...(api.searchRepositoryAuthors === undefined |
| 667 | ? {} |
| 668 | : { |
| 669 | searchRepositoryAuthors: interactive( |
| 670 | "searchRepositoryAuthors", |
| 671 | api.searchRepositoryAuthors, |
| 672 | ), |
| 673 | }), |
| 674 | ...(api.searchRepositoryReferences === undefined |
| 675 | ? {} |
| 676 | : { |
| 677 | searchRepositoryReferences: interactive( |
| 678 | "searchRepositoryReferences", |
| 679 | api.searchRepositoryReferences, |
| 680 | ), |
| 681 | }), |
| 682 | replyToThread: interactive("replyToThread", api.replyToThread), |
| 683 | setReaction: interactive("setReaction", api.setReaction), |
| 684 | setThreadResolution: interactive("setThreadResolution", api.setThreadResolution), |
| 685 | }; |
| 686 | // Optional provider methods must be forwarded too; returning the interface alone permits omissions. |
| 687 | return wrapped satisfies PullRequestProviderApi & |
| 688 | Record<Exclude<keyof PullRequestProviderApi, keyof typeof wrapped>, never>; |
| 689 | } |
| 690 | |
| 691 | const FILTER_OPTIONS_LIMIT = 100; |
| 692 | |
| 693 | /** |
| 694 | * Exact matches first, then names that begin with the query, then the rest, so a short query |
| 695 | * still puts the obvious answer at the top of a long list. |
| 696 | */ |
| 697 | function rankFilterOptions<A>( |
| 698 | pages: ReadonlyArray<ProviderFilterOptionPage<A>>, |
| 699 | input: { |
| 700 | readonly query: string | undefined; |
| 701 | readonly keyOf: (item: A) => string; |
| 702 | readonly textsOf: (item: A) => ReadonlyArray<string | null>; |
| 703 | /** Ties keep the hosts' order instead of sorting by key. */ |
| 704 | readonly hostOrder?: boolean; |
| 705 | }, |
| 706 | ): { readonly items: ReadonlyArray<A>; readonly truncated: boolean } { |
| 707 | const query = input.query?.trim().toLowerCase() ?? ""; |
| 708 | const unique = new Map<string, A>(); |
| 709 | for (const page of pages) { |
| 710 | for (const item of page.items) { |
| 711 | const key = input.keyOf(item).toLowerCase(); |
| 712 | if (!unique.has(key)) unique.set(key, item); |
| 713 | } |
| 714 | } |
| 715 | const rank = (item: A) => { |
| 716 | const texts = input.textsOf(item).flatMap((text) => (text ? [text.toLowerCase()] : [])); |
| 717 | if (query.length === 0) return 0; |
| 718 | if (texts.includes(query)) return 0; |
| 719 | if (texts.some((text) => text.startsWith(query))) return 1; |
| 720 | if (texts.some((text) => text.includes(query))) return 2; |
| 721 | return null; |
| 722 | }; |
| 723 | const ranked = [...unique.values()] |
| 724 | .flatMap((item) => { |
| 725 | const score = rank(item); |
| 726 | return score === null ? [] : [{ item, score, key: input.keyOf(item) }]; |
| 727 | }) |
| 728 | .toSorted( |
| 729 | (left, right) => |
| 730 | left.score - right.score || |
| 731 | (input.hostOrder === true |
| 732 | ? 0 |
| 733 | : left.key.localeCompare(right.key, undefined, { sensitivity: "base" })), |
| 734 | ); |
| 735 | return { |
| 736 | items: ranked.slice(0, FILTER_OPTIONS_LIMIT).map(({ item }) => item), |
| 737 | truncated: ranked.length > FILTER_OPTIONS_LIMIT || pages.some((page) => page.truncated), |
| 738 | }; |
| 739 | } |
| 740 | |
| 741 | const remoteHostKey = (recognized: SourceControlProviderInfo, remoteUrl: string) => |
| 742 | `${recognized.baseUrl}\n${isSshRemoteUrl(remoteUrl) ? "ssh" : "web"}`; |
| 743 | |
| 744 | /** An HTTP remote names its server's web host, port included. */ |
| 745 | function httpRemoteHost(remoteUrl: string): string | null { |
| 746 | try { |
| 747 | const remote = new URL(remoteUrl); |
| 748 | return remote.protocol === "http:" || remote.protocol === "https:" |
| 749 | ? remote.host.toLowerCase() |
| 750 | : null; |
| 751 | } catch { |
| 752 | return null; |
| 753 | } |
| 754 | } |
| 755 | |
| 756 | /** Whether `expected` names `head`: the full SHA, or a hex prefix of at least 7 characters. */ |
| 757 | export const isHeadSha = (head: string, expected: string) => { |
| 758 | const wanted = expected.toLowerCase(); |
| 759 | return /^[0-9a-f]{7,}$/.test(wanted) ? head.toLowerCase().startsWith(wanted) : head === expected; |
| 760 | }; |
| 761 | |
| 762 | // Capture before the provider read so a slow response keeps its original freshness through caches. |
| 763 | const observeRead = Effect.fnUntraced(function* <A, E, R>(read: Effect.Effect<A, E, R>) { |
| 764 | const observedAt = yield* Clock.currentTimeMillis; |
| 765 | return { value: yield* read, observedAt }; |
| 766 | }); |
| 767 | |
| 768 | export const make = Effect.gen(function* () { |
| 769 | const mergedPullRequests = yield* PubSub.sliding<PullRequestMergeEvent>(64); |
| 770 | const stateChanges = yield* PubSub.sliding<ThreadPullRequestKey>(64); |
| 771 | const pullRequestRefreshes = yield* SubscriptionRef.make(0); |
| 772 | const linkedThreadRefreshes = yield* SubscriptionRef.make(0); |
| 773 | const registry = yield* PullRequestProviderRegistry.PullRequestProviderRegistry; |
| 774 | const requirementOf: UnavailableRequirementOf = (kind) => |
| 775 | registry.get(kind)?.unavailableRequirement; |
| 776 | const toPullRequestError = toPullRequestErrorWith(requirementOf); |
| 777 | const serverSettings = yield* ServerSettings.ServerSettingsService; |
| 778 | const projects = yield* ProjectService.ProjectService; |
| 779 | const repositoryIdentities = yield* RepositoryIdentityResolver.RepositoryIdentityResolver; |
| 780 | const sourceControlProviders = yield* SourceControlProviderRegistry.SourceControlProviderRegistry; |
| 781 | const rateLimits = yield* SourceControlRateLimit.SourceControlRateLimit; |
| 782 | const filesViewedStore = yield* PullRequestFilesViewed.PullRequestFilesViewedRepository; |
| 783 | const readCache = yield* PullRequestReadCache.PullRequestReadCache; |
| 784 | const clock = yield* Clock.Clock; |
| 785 | |
| 786 | /** |
| 787 | * Where each project's remote is served from, by the remote's recognised base URL: a remote no |
| 788 | * definition placed is identified by the hosting CLIs, and a host whose remotes may not name |
| 789 | * its web server says which one does. One project per base URL and transport answers for all |
| 790 | * of them. |
| 791 | */ |
| 792 | const resolveRemoteHosts = Effect.fn("PullRequestService.resolveRemoteHosts")(function* ( |
| 793 | projects: ReadonlyArray<OrchestrationProjectShell>, |
| 794 | filter: Pick<PullRequestListInput, "projectId" | "host">, |
| 795 | ) { |
| 796 | type Candidate = { |
| 797 | readonly project: OrchestrationProjectShell; |
| 798 | readonly context: SourceControlProviderContext; |
| 799 | }; |
| 800 | const candidatesByKey = new Map<string, Candidate[]>(); |
| 801 | for (const project of projects) { |
| 802 | if (filter.projectId !== undefined && project.id !== filter.projectId) continue; |
| 803 | const identity = project.repositoryIdentity; |
| 804 | if ( |
| 805 | !identity || |
| 806 | identity.provider === undefined || |
| 807 | sourceControlDefinitions.repositorySelector(identity) === null |
| 808 | ) |
| 809 | continue; |
| 810 | if (identity.provider !== "unknown") { |
| 811 | const provider = yield* sourceControlProviders |
| 812 | .get(identity.provider) |
| 813 | .pipe(Effect.orElseSucceed(() => null)); |
| 814 | if (provider?.resolveRemoteWebHost === undefined) continue; |
| 815 | } |
| 816 | const host = sourceControlDefinitions.changeRequestHost(identity, "unknown"); |
| 817 | if ( |
| 818 | filter.host !== undefined && |
| 819 | host !== "unknown" && |
| 820 | host !== filter.host.toLowerCase() && |
| 821 | httpRemoteHost(identity.locator.remoteUrl) !== filter.host.toLowerCase() && |
| 822 | !isSshRemoteUrl(identity.locator.remoteUrl) |
| 823 | ) { |
| 824 | continue; |
| 825 | } |
| 826 | const { remoteName, remoteUrl } = identity.locator; |
| 827 | const recognized = sourceControlDefinitions.recognizeRemote(remoteUrl); |
| 828 | if (recognized === null) continue; |
| 829 | const candidate = { |
| 830 | project, |
| 831 | context: { |
| 832 | provider: |
| 833 | identity.provider === "unknown" |
| 834 | ? recognized |
| 835 | : { ...recognized, kind: identity.provider }, |
| 836 | remoteName, |
| 837 | remoteUrl, |
| 838 | ...(filter.host !== undefined && isSshRemoteUrl(remoteUrl) |
| 839 | ? { requestedHost: filter.host } |
| 840 | : {}), |
| 841 | }, |
| 842 | }; |
| 843 | const key = remoteHostKey(recognized, remoteUrl); |
| 844 | const candidates = candidatesByKey.get(key); |
| 845 | if (candidates === undefined) candidatesByKey.set(key, [candidate]); |
| 846 | else candidates.push(candidate); |
| 847 | } |
| 848 | |
| 849 | const resolveContext = (input: { |
| 850 | readonly cwd: string; |
| 851 | readonly context: SourceControlProviderContext; |
| 852 | }) => sourceControlProviders.resolveHandle(input).pipe(Effect.map((handle) => handle.context)); |
| 853 | type RemoteHost = { readonly kind: SourceControlProviderKind; readonly host: string | null }; |
| 854 | const resolveCandidate = ({ project, context }: Candidate) => |
| 855 | (context.provider.kind === "unknown" |
| 856 | ? resolveContext({ cwd: project.workspaceRoot, context }).pipe( |
| 857 | Effect.map((resolved) => |
| 858 | resolved === null || resolved.provider.kind === "unknown" |
| 859 | ? null |
| 860 | : { context: resolved, discovered: true }, |
| 861 | ), |
| 862 | ) |
| 863 | : Effect.succeed({ context, discovered: false }) |
| 864 | ).pipe( |
| 865 | Effect.flatMap((found) => |
| 866 | found === null |
| 867 | ? Effect.succeed(null) |
| 868 | : sourceControlProviders.get(found.context.provider.kind).pipe( |
| 869 | Effect.flatMap( |
| 870 | (provider) => |
| 871 | provider.resolveRemoteWebHost?.({ |
| 872 | cwd: project.workspaceRoot, |
| 873 | context: found.context, |
| 874 | // A remote discovery just placed is not looked up a second time. |
| 875 | resolveContext: found.discovered |
| 876 | ? () => Effect.succeed(found.context) |
| 877 | : resolveContext, |
| 878 | }) ?? Effect.succeed(null), |
| 879 | ), |
| 880 | Effect.orElseSucceed(() => null), |
| 881 | Effect.map((host): RemoteHost => ({ kind: found.context.provider.kind, host })), |
| 882 | ), |
| 883 | ), |
| 884 | Effect.orElseSucceed(() => null), |
| 885 | ); |
| 886 | |
| 887 | // An SSH remote whose web host one checkout could not name may be named by the next; a |
| 888 | // kind found without a host still stands if none can. |
| 889 | const resolveKey = Effect.fn("PullRequestService.resolveRemoteHost")(function* ( |
| 890 | candidates: ReadonlyArray<Candidate>, |
| 891 | ) { |
| 892 | let fallback: RemoteHost | null = null; |
| 893 | for (const candidate of candidates) { |
| 894 | const resolved = yield* resolveCandidate(candidate); |
| 895 | if (resolved === null) continue; |
| 896 | if (resolved.host !== null || !isSshRemoteUrl(candidate.context.remoteUrl)) { |
| 897 | return resolved; |
| 898 | } |
| 899 | fallback ??= resolved; |
| 900 | } |
| 901 | return fallback; |
| 902 | }); |
| 903 | |
| 904 | return yield* Effect.forEach( |
| 905 | candidatesByKey, |
| 906 | ([key, candidates]) => |
| 907 | resolveKey(candidates).pipe(Effect.map((resolved) => [key, resolved] as const)), |
| 908 | { concurrency: REPOSITORY_CONCURRENCY }, |
| 909 | ).pipe(Effect.map((resolved) => new Map(resolved))); |
| 910 | }); |
| 911 | |
| 912 | const listWorkspaceProjects = ( |
| 913 | filter: Pick<PullRequestListInput, "projectId" | "projectIds" | "host">, |
| 914 | ): Effect.Effect<WorkspaceProjects, PullRequestError> => |
| 915 | Effect.flatMap(sharedProjectReads, (shared) => { |
| 916 | if (shared === null || !shared.open) return readWorkspaceProjects(filter); |
| 917 | const key = JSON.stringify([filter.projectId, filter.projectIds, filter.host]); |
| 918 | const existing = shared.reads.get(key); |
| 919 | if (existing !== undefined) return existing; |
| 920 | return Effect.cached(readWorkspaceProjects(filter)).pipe( |
| 921 | Effect.tap((read) => Effect.sync(() => shared.reads.set(key, read))), |
| 922 | Effect.flatten, |
| 923 | ); |
| 924 | }); |
| 925 | |
| 926 | const withSharedProjectReads = <A, E, R>(effect: Effect.Effect<A, E, R>) => |
| 927 | Effect.suspend(() => { |
| 928 | const shared = { open: true, reads: new Map() }; |
| 929 | return effect.pipe( |
| 930 | Effect.provideService(sharedProjectReads, shared), |
| 931 | Effect.ensuring( |
| 932 | Effect.sync(() => { |
| 933 | shared.open = false; |
| 934 | shared.reads.clear(); |
| 935 | }), |
| 936 | ), |
| 937 | ); |
| 938 | }); |
| 939 | |
| 940 | const readWorkspaceProjects = ( |
| 941 | filter: Pick<PullRequestListInput, "projectId" | "projectIds" | "host">, |
| 942 | ): Effect.Effect<WorkspaceProjects, PullRequestError> => |
| 943 | (filter.projectId === undefined |
| 944 | ? projects.listShells( |
| 945 | filter.projectIds === undefined ? undefined : { projectIds: filter.projectIds }, |
| 946 | ) |
| 947 | : projects.getShell(filter.projectId).pipe(Effect.map(Option.toArray)) |
| 948 | ).pipe( |
| 949 | Effect.mapError( |
| 950 | (error) => |
| 951 | new PullRequestOperationError({ |
| 952 | operation: "listProjects", |
| 953 | detail: "The project list could not be read.", |
| 954 | cause: error, |
| 955 | }), |
| 956 | ), |
| 957 | Effect.flatMap((projects) => |
| 958 | Effect.forEach( |
| 959 | projects, |
| 960 | (project) => |
| 961 | project.repositoryIdentity != null |
| 962 | ? Effect.succeed(project) |
| 963 | : repositoryIdentities |
| 964 | .resolve(project.workspaceRoot) |
| 965 | .pipe(Effect.map((repositoryIdentity) => ({ ...project, repositoryIdentity }))), |
| 966 | { concurrency: REPOSITORY_CONCURRENCY }, |
| 967 | ), |
| 968 | ), |
| 969 | Effect.flatMap((projects) => |
| 970 | resolveRemoteHosts(projects, filter).pipe( |
| 971 | Effect.map((remoteHosts) => ({ remoteHosts, projects })), |
| 972 | ), |
| 973 | ), |
| 974 | Effect.map(({ remoteHosts, projects }) => { |
| 975 | const supported: SupportedProject[] = []; |
| 976 | const unimplemented = new Map< |
| 977 | string, |
| 978 | { kind: SourceControlProviderKind; projectCount: number } |
| 979 | >(); |
| 980 | const viewerRoots = new Map<string, string[]>(); |
| 981 | const refinedProjectIdsByHost = new Map<string, ProjectId[]>(); |
| 982 | const seen = new Set<string>(); |
| 983 | for (const project of projects) { |
| 984 | if (filter.projectId !== undefined && project.id !== filter.projectId) continue; |
| 985 | if (filter.projectIds !== undefined && !filter.projectIds.includes(project.id)) continue; |
| 986 | const identity = project.repositoryIdentity; |
| 987 | let kind = identity?.provider; |
| 988 | const repository = sourceControlDefinitions.repositorySelector( |
| 989 | project.repositoryIdentity, |
| 990 | ); |
| 991 | if (!identity || kind === undefined || repository === null) continue; |
| 992 | const recognized = sourceControlDefinitions.recognizeRemote(identity.locator.remoteUrl); |
| 993 | const remote = |
| 994 | recognized === null |
| 995 | ? undefined |
| 996 | : remoteHosts.get(remoteHostKey(recognized, identity.locator.remoteUrl)); |
| 997 | kind = remote?.kind ?? kind; |
| 998 | const host = remote?.host ?? sourceControlDefinitions.changeRequestHost(identity, kind); |
| 999 | if (filter.host !== undefined && host !== filter.host.toLowerCase()) { |
| 1000 | continue; |
| 1001 | } |
| 1002 | if (host !== sourceControlDefinitions.changeRequestHost(identity, identity.provider)) { |
| 1003 | const projectIds = refinedProjectIdsByHost.get(host); |
| 1004 | if (projectIds === undefined) refinedProjectIdsByHost.set(host, [project.id]); |
| 1005 | else projectIds.push(project.id); |
| 1006 | } |
| 1007 | const registered = registry.get(kind); |
| 1008 | const api = registered?.servesHost?.(host) === false ? null : registered; |
| 1009 | if (api !== null) { |
| 1010 | const roots = viewerRoots.get(host); |
| 1011 | if (roots === undefined) viewerRoots.set(host, [project.workspaceRoot]); |
| 1012 | else if (!roots.includes(project.workspaceRoot)) roots.push(project.workspaceRoot); |
| 1013 | } |
| 1014 | const repositoryKey = |
| 1015 | api?.repositoryKey?.({ canonicalKey: identity.canonicalKey }) ?? null; |
| 1016 | const key = listCursorKey(host, repositoryKey ?? repository); |
| 1017 | if (seen.has(key)) continue; |
| 1018 | seen.add(key); |
| 1019 | if (api === null) { |
| 1020 | const counted = unimplemented.get(host); |
| 1021 | if (counted === undefined) unimplemented.set(host, { kind, projectCount: 1 }); |
| 1022 | else counted.projectCount += 1; |
| 1023 | continue; |
| 1024 | } |
| 1025 | supported.push({ |
| 1026 | cursorKey: key, |
| 1027 | project, |
| 1028 | api: withRateLimitBackoff(api, host, rateLimits), |
| 1029 | repository, |
| 1030 | host, |
| 1031 | remote: |
| 1032 | repositoryKey ?? |
| 1033 | sourceControlDefinitions.repositoryKeyFromRemote(`https://${host}/${repository}`), |
| 1034 | repositoryKey: |
| 1035 | repositoryKey === null |
| 1036 | ? null |
| 1037 | : sourceControlDefinitions.canonicalRepositoryKey(repositoryKey.toLowerCase()), |
| 1038 | }); |
| 1039 | } |
| 1040 | return { supported, unimplemented, viewerRoots, refinedProjectIdsByHost }; |
| 1041 | }), |
| 1042 | ); |
| 1043 | |
| 1044 | // Azure derives organization from the checkout; require the matching repository. |
| 1045 | const requireProject = (ref: PullRequestRef): Effect.Effect<SupportedProject, PullRequestError> => |
| 1046 | listWorkspaceProjects({ projectId: ref.projectId }).pipe( |
| 1047 | Effect.flatMap(({ supported }): Effect.Effect<SupportedProject, PullRequestError> => { |
| 1048 | const own = supported[0]; |
| 1049 | const repository = ref.repository.trim(); |
| 1050 | const host = ref.host?.trim().toLowerCase(); |
| 1051 | if (own !== undefined && own.repository.toLowerCase() === repository.toLowerCase()) { |
| 1052 | if (host === undefined || host === own.host) return Effect.succeed(own); |
| 1053 | } |
| 1054 | if (host === undefined) { |
| 1055 | if (own === undefined) { |
| 1056 | return Effect.fail(new PullRequestUnavailableError({ reason: "provider-unsupported" })); |
| 1057 | } |
| 1058 | return Effect.fail( |
| 1059 | new PullRequestOperationError({ |
| 1060 | operation: "resolveRepository", |
| 1061 | detail: "The change request does not belong to the selected project.", |
| 1062 | }), |
| 1063 | ); |
| 1064 | } |
| 1065 | const referenceKey = `${host}/${repository}`.toLowerCase(); |
| 1066 | const repositoryKey = sourceControlDefinitions.canonicalRepositoryKey(referenceKey); |
| 1067 | // A host that spells one repository several ways (Azure's SSH and legacy clone hosts) |
| 1068 | // can differ from the browser URL's host. Compare the complete repository identity |
| 1069 | // before narrowing those checkouts by host. |
| 1070 | return listWorkspaceProjects( |
| 1071 | sourceControlDefinitions.findByRepositoryKey(referenceKey) ? {} : { host }, |
| 1072 | ).pipe( |
| 1073 | Effect.flatMap(({ supported }) => { |
| 1074 | const onHost = supported.filter((candidate) => candidate.host === host); |
| 1075 | const route = |
| 1076 | supported.find( |
| 1077 | (candidate) => |
| 1078 | candidate.repositoryKey !== null && candidate.repositoryKey === repositoryKey, |
| 1079 | ) ?? |
| 1080 | onHost.find( |
| 1081 | (candidate) => |
| 1082 | candidate.repositoryKey === null && |
| 1083 | candidate.repository.toLowerCase() === repository.toLowerCase(), |
| 1084 | ) ?? |
| 1085 | onHost.find((candidate) => candidate.repositoryKey === null); |
| 1086 | if (route === undefined) { |
| 1087 | return Effect.gen(function* () { |
| 1088 | const publicHost = sourceControlDefinitions.findByPublicHost(host); |
| 1089 | const api = publicHost === undefined ? null : registry.get(publicHost.kind); |
| 1090 | if (api?.readsPublicHostWithoutCheckout) { |
| 1091 | const selected = yield* projects.getShell(ref.projectId).pipe( |
| 1092 | Effect.mapError( |
| 1093 | (cause) => |
| 1094 | new PullRequestOperationError({ |
| 1095 | operation: "resolveRepository", |
| 1096 | detail: "The selected project could not be read.", |
| 1097 | cause, |
| 1098 | }), |
| 1099 | ), |
| 1100 | ); |
| 1101 | if (Option.isSome(selected)) { |
| 1102 | return { |
| 1103 | cursorKey: listCursorKey(host, repository), |
| 1104 | project: selected.value, |
| 1105 | api: withRateLimitBackoff(api, host, rateLimits), |
| 1106 | repository, |
| 1107 | host, |
| 1108 | remote: sourceControlDefinitions.repositoryKeyFromRemote( |
| 1109 | `https://${host}/${repository}`, |
| 1110 | ), |
| 1111 | repositoryKey: null, |
| 1112 | }; |
| 1113 | } |
| 1114 | } |
| 1115 | const owner = |
| 1116 | publicHost ?? sourceControlDefinitions.findByRepositoryKey(referenceKey); |
| 1117 | const readable = owner === undefined ? null : registry.get(owner.kind); |
| 1118 | if ( |
| 1119 | readable !== null && |
| 1120 | !readable.readsPublicHostWithoutCheckout && |
| 1121 | readable.servesHost?.(host) !== false |
| 1122 | ) { |
| 1123 | // Without repository keys, any checkout on the host routes the read. |
| 1124 | return yield* new PullRequestUnavailableError( |
| 1125 | readable.repositoryKey === undefined |
| 1126 | ? { reason: "repository-without-project", host } |
| 1127 | : { reason: "repository-without-project", repository }, |
| 1128 | ); |
| 1129 | } |
| 1130 | return yield* new PullRequestUnavailableError({ reason: "provider-unsupported" }); |
| 1131 | }); |
| 1132 | } |
| 1133 | return Effect.succeed( |
| 1134 | route.repositoryKey !== null || |
| 1135 | route.repository.toLowerCase() === repository.toLowerCase() |
| 1136 | ? route |
| 1137 | : { |
| 1138 | ...route, |
| 1139 | repository, |
| 1140 | remote: sourceControlDefinitions.repositoryKeyFromRemote( |
| 1141 | `https://${host}/${repository}`, |
| 1142 | ), |
| 1143 | }, |
| 1144 | ); |
| 1145 | }), |
| 1146 | ); |
| 1147 | }), |
| 1148 | ); |
| 1149 | |
| 1150 | const canonicalRef = Effect.fn("PullRequestService.canonicalRef")(function* < |
| 1151 | I extends PullRequestRef, |
| 1152 | >(input: I) { |
| 1153 | const project = yield* requireProject(input); |
| 1154 | return { |
| 1155 | ...input, |
| 1156 | projectId: project.project.id, |
| 1157 | host: project.host, |
| 1158 | repository: project.repository, |
| 1159 | }; |
| 1160 | }); |
| 1161 | |
| 1162 | // A failed read keeps the tools: their calls report the failure. |
| 1163 | const servesProject: PullRequestService["Service"]["servesProject"] = (projectId) => |
| 1164 | listWorkspaceProjects({ projectId }).pipe( |
| 1165 | Effect.map(({ supported }) => supported.length > 0), |
| 1166 | Effect.orElseSucceed(() => true), |
| 1167 | ); |
| 1168 | |
| 1169 | const changes: PullRequestService["Service"]["changes"] = (input) => |
| 1170 | Stream.unwrap( |
| 1171 | requireProject(input).pipe( |
| 1172 | Effect.map((project) => |
| 1173 | project.api.changeRequestEvents === undefined |
| 1174 | ? Stream.empty |
| 1175 | : project.api.changeRequestEvents({ |
| 1176 | cwd: project.project.workspaceRoot, |
| 1177 | repository: project.repository, |
| 1178 | host: project.host, |
| 1179 | number: input.number, |
| 1180 | }), |
| 1181 | ), |
| 1182 | Effect.orElseSucceed(() => Stream.empty), |
| 1183 | ), |
| 1184 | ); |
| 1185 | |
| 1186 | // Access can change after page load; recheck every write. |
| 1187 | const viewerPermissionsOf = ( |
| 1188 | project: SupportedProject, |
| 1189 | ref: PullRequestRef, |
| 1190 | operation: string, |
| 1191 | includeUpdateBranch = false, |
| 1192 | ) => |
| 1193 | project.api |
| 1194 | .getViewerPermissions({ |
| 1195 | cwd: project.project.workspaceRoot, |
| 1196 | repository: project.repository, |
| 1197 | host: project.host, |
| 1198 | number: ref.number, |
| 1199 | includeUpdateBranch, |
| 1200 | }) |
| 1201 | .pipe(Effect.mapError(toPullRequestError(operation))); |
| 1202 | |
| 1203 | const decodeCursors = ( |
| 1204 | cursors: PullRequestListInput["cursors"], |
| 1205 | ): Effect.Effect<ReadonlyMap<string, ListCursor> | null, PullRequestError> => { |
| 1206 | if (cursors === undefined) return Effect.succeed(null); |
| 1207 | const decoded = new Map<string, ListCursor>(); |
| 1208 | for (const [key, raw] of Object.entries(cursors)) { |
| 1209 | const cursor = parseListCursor(raw); |
| 1210 | if (cursor === null) { |
| 1211 | return Effect.fail( |
| 1212 | new PullRequestOperationError({ |
| 1213 | operation: "list", |
| 1214 | detail: "The list could not be carried on from where it left off.", |
| 1215 | }), |
| 1216 | ); |
| 1217 | } |
| 1218 | decoded.set(key, cursor); |
| 1219 | } |
| 1220 | return Effect.succeed(decoded); |
| 1221 | }; |
| 1222 | |
| 1223 | type ResolvedViewer = { |
| 1224 | readonly host: string; |
| 1225 | readonly kind: SourceControlProviderKind; |
| 1226 | readonly viewer: string | null; |
| 1227 | readonly error: PullRequestProviderError | null; |
| 1228 | }; |
| 1229 | const viewersByHost = new Map<string, { readonly at: number; readonly result: ResolvedViewer }>(); |
| 1230 | const viewerFlights = yield* Cache.makeWith( |
| 1231 | (key: string): Effect.Effect<ResolvedViewer> => { |
| 1232 | const [host, kind, roots] = JSON.parse(key) as [ |
| 1233 | string, |
| 1234 | SourceControlProviderKind, |
| 1235 | ReadonlyArray<string>, |
| 1236 | ]; |
| 1237 | const registered = registry.get(kind); |
| 1238 | if (registered === null) { |
| 1239 | return Effect.die(new Error(`Missing pull request provider: ${kind}`)); |
| 1240 | } |
| 1241 | const api = withRateLimitBackoff(registered, host, rateLimits, { viewerAllowsPause: true }); |
| 1242 | return Effect.firstSuccessOf(roots.map((cwd) => api.getViewer({ cwd, host }))).pipe( |
| 1243 | Effect.map((viewer) => ({ |
| 1244 | host, |
| 1245 | kind, |
| 1246 | viewer: viewer as string | null, |
| 1247 | error: null as PullRequestProviderError | null, |
| 1248 | })), |
| 1249 | Effect.tap((result) => |
| 1250 | Effect.map(Clock.currentTimeMillis, (at) => viewersByHost.set(host, { at, result })), |
| 1251 | ), |
| 1252 | Effect.catch((error) => |
| 1253 | Effect.succeed({ |
| 1254 | host, |
| 1255 | kind, |
| 1256 | viewer: null, |
| 1257 | error, |
| 1258 | }), |
| 1259 | ), |
| 1260 | ); |
| 1261 | }, |
| 1262 | { |
| 1263 | capacity: VIEWER_CACHE_CAPACITY, |
| 1264 | // Share cold-page lookups briefly; keep failures retryable. |
| 1265 | timeToLive: (exit) => |
| 1266 | Exit.isSuccess(exit) && exit.value.error === null ? Duration.seconds(1) : Duration.zero, |
| 1267 | }, |
| 1268 | ); |
| 1269 | |
| 1270 | const resolveViewers = ( |
| 1271 | projects: ReadonlyArray<SupportedProject>, |
| 1272 | viewerRoots: WorkspaceProjects["viewerRoots"], |
| 1273 | options?: { readonly allowPaused: boolean }, |
| 1274 | ) => |
| 1275 | Effect.forEach( |
| 1276 | [...new Set(projects.map(({ host }) => host))], |
| 1277 | (host) => |
| 1278 | Effect.flatMap(Clock.currentTimeMillis, (now): Effect.Effect<ResolvedViewer> => { |
| 1279 | const held = viewersByHost.get(host); |
| 1280 | if (held !== undefined && now - held.at <= Duration.toMillis(VIEWER_CACHE_TTL)) { |
| 1281 | return Effect.succeed(held.result); |
| 1282 | } |
| 1283 | const forHost = projects.filter((project) => project.host === host); |
| 1284 | const api = forHost[0]!.api; |
| 1285 | // Include deduplicated checkouts too; one unreadable worktree must not mark the whole host signed out. |
| 1286 | const roots = |
| 1287 | viewerRoots.get(host) ?? forHost.map(({ project }) => project.workspaceRoot); |
| 1288 | const key = JSON.stringify([host, api.kind, [...new Set(roots)].sort()]); |
| 1289 | if (options?.allowPaused === true) return Cache.get(viewerFlights, key); |
| 1290 | // Check pauses outside the shared lookup so background reads cannot spawn repeated failing CLIs and extend the pause. |
| 1291 | return rateLimits.check({ provider: api.kind, host }).pipe( |
| 1292 | Effect.flatMap(() => Cache.get(viewerFlights, key)), |
| 1293 | Effect.catch((error) => |
| 1294 | Effect.succeed<ResolvedViewer>({ |
| 1295 | host, |
| 1296 | kind: api.kind, |
| 1297 | viewer: null, |
| 1298 | error: new PullRequestProviderError({ |
| 1299 | provider: api.kind, |
| 1300 | operation: "getViewer", |
| 1301 | reason: "rate-limited", |
| 1302 | detail: error.detail, |
| 1303 | retryAt: error.retryAt, |
| 1304 | cause: error, |
| 1305 | }), |
| 1306 | }), |
| 1307 | ), |
| 1308 | ); |
| 1309 | }), |
| 1310 | { concurrency: REPOSITORY_CONCURRENCY }, |
| 1311 | ); |
| 1312 | |
| 1313 | const matchesRowFilters = ( |
| 1314 | item: ProviderChangeRequest, |
| 1315 | filters: PullRequestListFilters | undefined, |
| 1316 | viewer: string, |
| 1317 | ): boolean => { |
| 1318 | if (filters === undefined) return true; |
| 1319 | const labels = new Set(item.labels.map((label) => label.name.trim().toLowerCase())); |
| 1320 | const holds = (label: string) => labels.has(label.trim().toLowerCase()); |
| 1321 | return ( |
| 1322 | (filters.draft === undefined || item.isDraft === (filters.draft === "only")) && |
| 1323 | (filters.review === undefined || |
| 1324 | item.reviewDecision === undefined || |
| 1325 | (filters.review === "none" |
| 1326 | ? item.reviewDecision === null |
| 1327 | : item.reviewDecision === filters.review)) && |
| 1328 | (filters.checks === undefined || |
| 1329 | item.checksState === undefined || |
| 1330 | item.checksState === filters.checks) && |
| 1331 | (filters.labels === undefined || filters.labels.every((group) => group.some(holds))) && |
| 1332 | (filters.excludedLabels === undefined || !filters.excludedLabels.some(holds)) && |
| 1333 | (filters.author === undefined || |
| 1334 | item.author?.login.toLowerCase() === |
| 1335 | resolvePullRequestAuthorFilter(filters.author, viewer).toLowerCase()) |
| 1336 | ); |
| 1337 | }; |
| 1338 | |
| 1339 | const toEntry = (input: { |
| 1340 | readonly project: SupportedProject; |
| 1341 | readonly item: ProviderChangeRequest; |
| 1342 | readonly viewer: string; |
| 1343 | readonly observedAt: number; |
| 1344 | }): PullRequestListEntry => { |
| 1345 | const viewer = input.viewer.toLowerCase(); |
| 1346 | return { |
| 1347 | ...(input.item.stack === undefined ? {} : { stack: input.item.stack }), |
| 1348 | provider: input.project.api.kind, |
| 1349 | host: input.project.host, |
| 1350 | projectId: input.project.project.id, |
| 1351 | projectTitle: input.project.project.title, |
| 1352 | repository: input.project.repository, |
| 1353 | number: input.item.number, |
| 1354 | title: input.item.title, |
| 1355 | url: input.item.url, |
| 1356 | author: input.item.author, |
| 1357 | headBranch: input.item.headBranch, |
| 1358 | baseBranch: input.item.baseBranch, |
| 1359 | state: input.item.state, |
| 1360 | isDraft: input.item.isDraft, |
| 1361 | mergeability: input.item.mergeability, |
| 1362 | ...(input.item.rebaseRequired === undefined |
| 1363 | ? {} |
| 1364 | : { rebaseRequired: input.item.rebaseRequired }), |
| 1365 | additions: input.item.additions, |
| 1366 | deletions: input.item.deletions, |
| 1367 | createdAt: input.item.createdAt, |
| 1368 | updatedAt: input.item.updatedAt, |
| 1369 | observedAt: input.observedAt, |
| 1370 | ...(input.item.checksState === undefined || input.item.checksState === null |
| 1371 | ? {} |
| 1372 | : { checksState: input.item.checksState }), |
| 1373 | viewerReviewRequested: |
| 1374 | input.item.author?.login.toLowerCase() !== viewer && |
| 1375 | input.item.reviewRequestLogins.some((login) => login.toLowerCase() === viewer), |
| 1376 | labels: input.item.labels, |
| 1377 | ...(input.item.reviewDecision === undefined || input.item.reviewDecision === null |
| 1378 | ? {} |
| 1379 | : { reviewDecision: input.item.reviewDecision }), |
| 1380 | }; |
| 1381 | }; |
| 1382 | |
| 1383 | const listUncached: PullRequestService["Service"]["list"] = Effect.fn( |
| 1384 | "PullRequestService.listUncached", |
| 1385 | )(function* (input) { |
| 1386 | const involvement = input.involvement ?? "all"; |
| 1387 | const epochAtStart = epochCounter; |
| 1388 | const continuation = yield* decodeCursors(input.cursors); |
| 1389 | const { |
| 1390 | supported: projects, |
| 1391 | unimplemented, |
| 1392 | viewerRoots, |
| 1393 | refinedProjectIdsByHost, |
| 1394 | } = yield* listWorkspaceProjects(input); |
| 1395 | const projectCounts = new Map<string, number>(); |
| 1396 | for (const { host } of projects) { |
| 1397 | projectCounts.set(host, (projectCounts.get(host) ?? 0) + 1); |
| 1398 | } |
| 1399 | |
| 1400 | const viewerResults = yield* resolveViewers(projects, viewerRoots); |
| 1401 | const viewers: Record<string, string> = {}; |
| 1402 | for (const result of viewerResults) { |
| 1403 | if (result.viewer !== null) viewers[result.host] = result.viewer; |
| 1404 | } |
| 1405 | |
| 1406 | const providers: ReadonlyArray<PullRequestProviderSummary> = [ |
| 1407 | ...viewerResults.map((result) => { |
| 1408 | const capabilities = projects.find((project) => project.host === result.host)?.api |
| 1409 | .capabilities; |
| 1410 | return { |
| 1411 | host: result.host, |
| 1412 | kind: result.kind, |
| 1413 | searchesOnHost: capabilities?.search ?? false, |
| 1414 | actions: capabilities?.actions ?? [], |
| 1415 | projectCount: projectCounts.get(result.host) ?? 1, |
| 1416 | projectIds: refinedProjectIdsByHost.get(result.host), |
| 1417 | configured: result.viewer !== null, |
| 1418 | detail: result.error === null ? null : providerDetail(requirementOf, result.error), |
| 1419 | }; |
| 1420 | }), |
| 1421 | ...[...unimplemented].map(([host, { kind, projectCount }]) => ({ |
| 1422 | host, |
| 1423 | kind, |
| 1424 | searchesOnHost: false, |
| 1425 | actions: [], |
| 1426 | projectCount, |
| 1427 | projectIds: refinedProjectIdsByHost.get(host), |
| 1428 | configured: false, |
| 1429 | detail: "This host cannot be browsed here yet.", |
| 1430 | })), |
| 1431 | ]; |
| 1432 | |
| 1433 | const selected = |
| 1434 | continuation === null |
| 1435 | ? projects |
| 1436 | : projects.filter(({ cursorKey }) => continuation.has(cursorKey)); |
| 1437 | const readable = selected.filter(({ host }) => viewers[host] !== undefined); |
| 1438 | const unreadable = selected |
| 1439 | .filter(({ host }) => viewers[host] === undefined) |
| 1440 | .map(({ project, repository }) => ({ |
| 1441 | projectId: project.id, |
| 1442 | projectTitle: project.title, |
| 1443 | message: `${repository} could not be read.`, |
| 1444 | })); |
| 1445 | if (readable.length === 0) { |
| 1446 | const listResult: PullRequestListResult = { |
| 1447 | viewers: viewers as PullRequestListResult["viewers"], |
| 1448 | providers, |
| 1449 | entries: [], |
| 1450 | errors: unreadable, |
| 1451 | truncated: false, |
| 1452 | nextCursors: {}, |
| 1453 | }; |
| 1454 | const errors = viewerResults.flatMap((result) => |
| 1455 | result.error === null || !selected.some(({ host }) => host === result.host) |
| 1456 | ? [] |
| 1457 | : [result.error], |
| 1458 | ); |
| 1459 | const blocking = errors.find(isProviderUnusable) ?? errors[0]; |
| 1460 | if (blocking) { |
| 1461 | // Preserve failure/retry semantics while letting clients try another server for these hosts. |
| 1462 | const error = toPullRequestError("list")(blocking); |
| 1463 | return yield* error._tag === "PullRequestUnavailableError" |
| 1464 | ? new PullRequestUnavailableError({ ...error, listResult }) |
| 1465 | : new PullRequestOperationError({ ...error, listResult }); |
| 1466 | } |
| 1467 | return listResult; |
| 1468 | } |
| 1469 | |
| 1470 | const limit = input.limit ?? DEFAULT_REPOSITORY_LIST_LIMIT; |
| 1471 | const cursorOf = (project: SupportedProject): ListCursor | undefined => |
| 1472 | continuation?.get(project.cursorKey); |
| 1473 | |
| 1474 | const readSlice = ( |
| 1475 | project: SupportedProject, |
| 1476 | cursor: ListCursor | undefined, |
| 1477 | ): Effect.Effect<RepositoryBatch> => { |
| 1478 | { |
| 1479 | const viewer = viewers[project.host]!; |
| 1480 | const key = project.cursorKey; |
| 1481 | return project.api |
| 1482 | .listChangeRequests({ |
| 1483 | cwd: project.project.workspaceRoot, |
| 1484 | repository: project.repository, |
| 1485 | host: project.host, |
| 1486 | state: input.state, |
| 1487 | involvement, |
| 1488 | viewer, |
| 1489 | limit, |
| 1490 | query: input.query, |
| 1491 | filters: input.filters, |
| 1492 | ...(cursor === undefined |
| 1493 | ? {} |
| 1494 | : { |
| 1495 | cursor: { |
| 1496 | updatedBefore: cursor.updatedBefore, |
| 1497 | delivered: cursor.delivered, |
| 1498 | seenAt: cursor.seenAt, |
| 1499 | resumeAfter: cursor.resumeAfter, |
| 1500 | }, |
| 1501 | }), |
| 1502 | }) |
| 1503 | .pipe( |
| 1504 | observeRead, |
| 1505 | Effect.map(({ value: page, observedAt }): RepositoryBatch => { |
| 1506 | // The boundary instant was asked for inclusively, so the rows already sent at it |
| 1507 | // come back with the slice. Dropping them here rather than asking for strictly |
| 1508 | // older is what keeps their neighbours at the same instant from being skipped. |
| 1509 | const items = |
| 1510 | cursor === undefined |
| 1511 | ? page.items |
| 1512 | : page.items.filter( |
| 1513 | (item) => |
| 1514 | item.updatedAt !== cursor.updatedBefore || |
| 1515 | !cursor.seenAt.includes(item.number), |
| 1516 | ); |
| 1517 | return { |
| 1518 | key, |
| 1519 | entries: items |
| 1520 | .filter((item) => matchesRowFilters(item, input.filters, viewer)) |
| 1521 | .map((item) => toEntry({ project, item, viewer, observedAt })), |
| 1522 | errors: [], |
| 1523 | truncated: page.truncated, |
| 1524 | nextCursor: |
| 1525 | page.continues && page.truncated |
| 1526 | ? nextListCursor( |
| 1527 | cursor, |
| 1528 | page.items, |
| 1529 | items, |
| 1530 | page.cursorAdvance, |
| 1531 | page.resumeAfter, |
| 1532 | ) |
| 1533 | : null, |
| 1534 | }; |
| 1535 | }), |
| 1536 | Effect.catch((error): Effect.Effect<RepositoryBatch> => |
| 1537 | Effect.succeed({ |
| 1538 | key, |
| 1539 | entries: [], |
| 1540 | errors: [ |
| 1541 | { |
| 1542 | projectId: project.project.id, |
| 1543 | projectTitle: project.project.title, |
| 1544 | message: |
| 1545 | error.accessHint === undefined |
| 1546 | ? `${project.repository} could not be read.` |
| 1547 | : `${project.repository} could not be read. ${error.accessHint}`, |
| 1548 | }, |
| 1549 | ], |
| 1550 | truncated: false, |
| 1551 | nextCursor: null, |
| 1552 | }), |
| 1553 | ), |
| 1554 | ); |
| 1555 | } |
| 1556 | }; |
| 1557 | |
| 1558 | // Filters a host cannot apply thin out the slices it hands over, so a repository keeps |
| 1559 | // reading until it has a page's worth or runs out. The reads are bounded: a filter that |
| 1560 | // matches nothing would otherwise walk the repository's whole history in one request. |
| 1561 | const readRepository = (project: SupportedProject): Effect.Effect<RepositoryBatch> => { |
| 1562 | const fill = (batch: RepositoryBatch, reads: number): Effect.Effect<RepositoryBatch> => { |
| 1563 | const cursor = batch.nextCursor === null ? null : parseListCursor(batch.nextCursor); |
| 1564 | if ( |
| 1565 | input.filters === undefined || |
| 1566 | cursor === null || |
| 1567 | batch.entries.length >= limit || |
| 1568 | reads >= FILTERED_LIST_READS |
| 1569 | ) { |
| 1570 | return Effect.succeed(batch); |
| 1571 | } |
| 1572 | return readSlice(project, cursor).pipe( |
| 1573 | Effect.flatMap((next) => |
| 1574 | // A slice that failed keeps the cursor before it, so the reader can try again. |
| 1575 | next.errors.length > 0 |
| 1576 | ? Effect.succeed(batch) |
| 1577 | : fill({ ...next, entries: [...batch.entries, ...next.entries] }, reads + 1), |
| 1578 | ), |
| 1579 | ); |
| 1580 | }; |
| 1581 | return readSlice(project, cursorOf(project)).pipe(Effect.flatMap((batch) => fill(batch, 1))); |
| 1582 | }; |
| 1583 | |
| 1584 | const readTogether = ( |
| 1585 | chunk: ReadonlyArray<SupportedProject>, |
| 1586 | ): Effect.Effect<ReadonlyArray<RepositoryBatch>> => { |
| 1587 | const first = chunk[0]!; |
| 1588 | const readAcross = first.api.listChangeRequestsAcross; |
| 1589 | const separately = () => |
| 1590 | Effect.forEach(chunk, readRepository, { concurrency: REPOSITORY_CONCURRENCY }); |
| 1591 | if (readAcross === undefined) return separately(); |
| 1592 | const viewer = viewers[first.host]!; |
| 1593 | const cursor = cursorOf(first); |
| 1594 | return readAcross({ |
| 1595 | cwd: first.project.workspaceRoot, |
| 1596 | host: first.host, |
| 1597 | repositories: chunk.map((project) => project.repository), |
| 1598 | state: input.state, |
| 1599 | involvement, |
| 1600 | viewer, |
| 1601 | limit, |
| 1602 | query: input.query, |
| 1603 | filters: input.filters, |
| 1604 | ...(cursor === undefined |
| 1605 | ? {} |
| 1606 | : { |
| 1607 | cursor: { |
| 1608 | updatedBefore: cursor.updatedBefore, |
| 1609 | delivered: cursor.delivered, |
| 1610 | seenAt: chunk.flatMap((project) => |
| 1611 | (cursorOf(project)?.seenAt ?? []).map((number) => ({ |
| 1612 | repository: project.repository, |
| 1613 | number, |
| 1614 | })), |
| 1615 | ), |
| 1616 | }, |
| 1617 | }), |
| 1618 | }).pipe( |
| 1619 | observeRead, |
| 1620 | Effect.flatMap(({ value: page, observedAt }) => { |
| 1621 | const rows = new Map<string, Array<ProviderChangeRequest>>(); |
| 1622 | for (const item of page.items) { |
| 1623 | const key = item.repository.trim().toLowerCase(); |
| 1624 | const held = rows.get(key); |
| 1625 | if (held === undefined) rows.set(key, [item]); |
| 1626 | else held.push(item); |
| 1627 | } |
| 1628 | const unresolved = new Set( |
| 1629 | (page.unresolved ?? []).map((repository) => repository.trim().toLowerCase()), |
| 1630 | ); |
| 1631 | const boundary = page.items.reduce<string | null>( |
| 1632 | (oldest, item) => |
| 1633 | oldest === null || item.updatedAt < oldest ? item.updatedAt : oldest, |
| 1634 | null, |
| 1635 | ); |
| 1636 | return Effect.forEach( |
| 1637 | chunk, |
| 1638 | (project): Effect.Effect<RepositoryBatch> => { |
| 1639 | const key = project.repository.trim().toLowerCase(); |
| 1640 | const fetched = rows.get(key) ?? []; |
| 1641 | if (fetched.length === 0 && unresolved.has(key)) return readRepository(project); |
| 1642 | const cursorHere = cursorOf(project); |
| 1643 | const items = |
| 1644 | cursorHere === undefined |
| 1645 | ? fetched |
| 1646 | : fetched.filter( |
| 1647 | (item) => |
| 1648 | item.updatedAt !== cursorHere.updatedBefore || |
| 1649 | !cursorHere.seenAt.includes(item.number), |
| 1650 | ); |
| 1651 | return Effect.succeed({ |
| 1652 | key: project.cursorKey, |
| 1653 | entries: items |
| 1654 | .filter((item) => matchesRowFilters(item, input.filters, viewer)) |
| 1655 | .map((item) => toEntry({ project, item, viewer, observedAt })), |
| 1656 | errors: [], |
| 1657 | truncated: page.truncated, |
| 1658 | nextCursor: |
| 1659 | page.truncated && boundary !== null |
| 1660 | ? listCursorAt(cursorHere, boundary, fetched, items.length) |
| 1661 | : null, |
| 1662 | }); |
| 1663 | }, |
| 1664 | { concurrency: REPOSITORY_CONCURRENCY }, |
| 1665 | ); |
| 1666 | }), |
| 1667 | Effect.catch(separately), |
| 1668 | ); |
| 1669 | }; |
| 1670 | |
| 1671 | const together = new Map<string, Array<SupportedProject>>(); |
| 1672 | const separate: Array<SupportedProject> = []; |
| 1673 | for (const project of readable) { |
| 1674 | if (project.api.listChangeRequestsAcross === undefined) { |
| 1675 | separate.push(project); |
| 1676 | continue; |
| 1677 | } |
| 1678 | const key = `${project.host}\n${cursorOf(project)?.updatedBefore ?? ""}`; |
| 1679 | const group = together.get(key); |
| 1680 | if (group === undefined) together.set(key, [project]); |
| 1681 | else group.push(project); |
| 1682 | } |
| 1683 | const reads: Array<Effect.Effect<ReadonlyArray<RepositoryBatch>>> = separate.map((project) => |
| 1684 | readRepository(project).pipe(Effect.map((batch) => [batch])), |
| 1685 | ); |
| 1686 | for (const group of together.values()) { |
| 1687 | for (let start = 0; start < group.length; start += REPOSITORY_SEARCH_CHUNK) { |
| 1688 | reads.push(readTogether(group.slice(start, start + REPOSITORY_SEARCH_CHUNK))); |
| 1689 | } |
| 1690 | } |
| 1691 | const batches = (yield* Effect.all(reads, { concurrency: REPOSITORY_CONCURRENCY })).flat(); |
| 1692 | |
| 1693 | const nextCursors: Record<string, string> = {}; |
| 1694 | for (const batch of batches) { |
| 1695 | if (batch.nextCursor !== null) nextCursors[batch.key] = batch.nextCursor; |
| 1696 | } |
| 1697 | const entries = batches |
| 1698 | .flatMap((batch) => batch.entries) |
| 1699 | .toSorted((left, right) => right.updatedAt.localeCompare(left.updatedAt)); |
| 1700 | // Hover cards on listed rows read from here. A pinned account or a mid-read refresh is another |
| 1701 | // scope; half the cache stays free for previews read directly. |
| 1702 | if ((yield* routingCredential) === null && epochCounter === epochAtStart) { |
| 1703 | const seeds = entries |
| 1704 | .slice(0, DETAIL_CACHE_CAPACITY / 2) |
| 1705 | .map((entry) => [refCacheKey(entry), previewFields(entry)] as const) |
| 1706 | .toReversed(); |
| 1707 | for (const [key, value] of seeds) { |
| 1708 | if (!(yield* Cache.has(previewCache, key))) yield* Cache.set(previewCache, key, value); |
| 1709 | } |
| 1710 | } |
| 1711 | |
| 1712 | return { |
| 1713 | viewers: viewers as PullRequestListResult["viewers"], |
| 1714 | providers, |
| 1715 | entries, |
| 1716 | errors: [...unreadable, ...batches.flatMap((batch) => batch.errors)], |
| 1717 | truncated: batches.some((batch) => batch.truncated), |
| 1718 | nextCursors, |
| 1719 | }; |
| 1720 | }); |
| 1721 | |
| 1722 | const viewerOf = (project: SupportedProject): Effect.Effect<string | null> => |
| 1723 | routingCredential.pipe( |
| 1724 | Effect.flatMap((credential) => |
| 1725 | credential !== null |
| 1726 | ? Effect.succeed(credential.viewer) |
| 1727 | : resolveViewers([project], new Map()).pipe( |
| 1728 | Effect.map(([resolved]) => resolved?.viewer ?? null), |
| 1729 | ), |
| 1730 | ), |
| 1731 | ); |
| 1732 | |
| 1733 | const routingIdentity: PullRequestService["Service"]["routingIdentity"] = Effect.fn( |
| 1734 | "PullRequestService.routingIdentity", |
| 1735 | )(function* (input) { |
| 1736 | const host = input.host.toLowerCase(); |
| 1737 | const { supported } = yield* listWorkspaceProjects({ host }); |
| 1738 | const project = supported.find( |
| 1739 | (candidate) => registry.get(candidate.api.kind)?.getRoutingIdentity !== undefined, |
| 1740 | ); |
| 1741 | const api = project === undefined ? null : registry.get(project.api.kind); |
| 1742 | if (project === undefined || api?.getRoutingIdentity === undefined) { |
| 1743 | return yield* new PullRequestUnavailableError({ reason: "provider-unsupported" }); |
| 1744 | } |
| 1745 | const identity = yield* api |
| 1746 | .getRoutingIdentity({ |
| 1747 | cwd: project.project.workspaceRoot, |
| 1748 | host, |
| 1749 | }) |
| 1750 | .pipe(Effect.mapError(toPullRequestError("routeIdentity"))); |
| 1751 | return { ...identity, host, provider: api.kind }; |
| 1752 | }); |
| 1753 | |
| 1754 | const withRoutingCredential: PullRequestService["Service"]["withRoutingCredential"] = Effect.fn( |
| 1755 | "PullRequestService.withRoutingCredential", |
| 1756 | )(function* (input, operation) { |
| 1757 | if (input.expectedAccountId === undefined) return yield* operation; |
| 1758 | const rejected = () => |
| 1759 | new PullRequestOperationError({ |
| 1760 | operation: "routeIdentity", |
| 1761 | detail: "The signed-in account could not be verified before starting the operation.", |
| 1762 | }); |
| 1763 | const project = yield* requireProject(input).pipe(Effect.mapError(rejected)); |
| 1764 | const api = registry.get(project.api.kind); |
| 1765 | if ( |
| 1766 | api?.withVerifiedCredential === undefined || |
| 1767 | input.host?.toLowerCase() !== project.host.toLowerCase() |
| 1768 | ) { |
| 1769 | return yield* rejected(); |
| 1770 | } |
| 1771 | const result = yield* api |
| 1772 | .withVerifiedCredential( |
| 1773 | { cwd: project.project.workspaceRoot, host: project.host, repository: project.repository }, |
| 1774 | (identity) => |
| 1775 | identity.accountId === input.expectedAccountId |
| 1776 | ? operation.pipe(Effect.provideService(routingCredential, identity), Effect.result) |
| 1777 | : Effect.fail(rejected()), |
| 1778 | ) |
| 1779 | .pipe(Effect.catchTags({ PullRequestProviderError: () => Effect.fail(rejected()) })); |
| 1780 | return yield* Effect.fromResult(result); |
| 1781 | }); |
| 1782 | |
| 1783 | const routing = Effect.fn("PullRequestService.routing")(function* (input: PullRequestRef) { |
| 1784 | const project = yield* requireProject(input); |
| 1785 | const api = registry.get(project.api.kind); |
| 1786 | if (api?.getRoutingIdentity === undefined) { |
| 1787 | return yield* new PullRequestUnavailableError({ reason: "provider-unsupported" }); |
| 1788 | } |
| 1789 | const identity = yield* api |
| 1790 | .getRoutingIdentity({ |
| 1791 | cwd: project.project.workspaceRoot, |
| 1792 | host: project.host, |
| 1793 | }) |
| 1794 | .pipe(Effect.mapError(toPullRequestError("routeIdentity"))); |
| 1795 | if (!identity.viewer.trim() || !identity.accountId.trim()) { |
| 1796 | return yield* new PullRequestOperationError({ |
| 1797 | operation: "routeIdentity", |
| 1798 | detail: "The signed-in account could not be verified.", |
| 1799 | }); |
| 1800 | } |
| 1801 | return { |
| 1802 | host: project.host, |
| 1803 | provider: project.api.kind, |
| 1804 | ...identity, |
| 1805 | projectTitle: project.project.title, |
| 1806 | workspaceRoot: project.project.workspaceRoot, |
| 1807 | }; |
| 1808 | }); |
| 1809 | |
| 1810 | const toSummary = ( |
| 1811 | project: SupportedProject, |
| 1812 | changeRequest: ProviderChangeRequestSummary | ProviderChangeRequestDetail, |
| 1813 | observedAt: number, |
| 1814 | reply = false, |
| 1815 | ): PullRequestSummary => ({ |
| 1816 | provider: project.api.kind, |
| 1817 | projectId: project.project.id, |
| 1818 | repository: project.repository, |
| 1819 | number: changeRequest.number, |
| 1820 | title: changeRequest.title, |
| 1821 | url: changeRequest.url, |
| 1822 | state: changeRequest.state, |
| 1823 | headBranch: changeRequest.headBranch, |
| 1824 | baseBranch: changeRequest.baseBranch, |
| 1825 | // An action reply may not carry these, and null would erase a time a client already holds. |
| 1826 | ...(changeRequest.closedAt === undefined && reply |
| 1827 | ? {} |
| 1828 | : { closedAt: changeRequest.closedAt ?? null }), |
| 1829 | ...(changeRequest.mergedAt === undefined && reply |
| 1830 | ? {} |
| 1831 | : { mergedAt: changeRequest.mergedAt ?? null }), |
| 1832 | updatedAt: changeRequest.updatedAt, |
| 1833 | observedAt, |
| 1834 | ...(changeRequest.isDraft === undefined ? {} : { isDraft: changeRequest.isDraft }), |
| 1835 | ...(changeRequest.author === undefined ? {} : { author: changeRequest.author }), |
| 1836 | ...(changeRequest.additions === undefined ? {} : { additions: changeRequest.additions }), |
| 1837 | ...(changeRequest.deletions === undefined ? {} : { deletions: changeRequest.deletions }), |
| 1838 | ...(changeRequest.changedFiles === undefined |
| 1839 | ? {} |
| 1840 | : { changedFiles: changeRequest.changedFiles }), |
| 1841 | ...(changeRequest.reviewDecision === undefined |
| 1842 | ? {} |
| 1843 | : { reviewDecision: changeRequest.reviewDecision }), |
| 1844 | ...(changeRequest.checksState === undefined ? {} : { checksState: changeRequest.checksState }), |
| 1845 | ...(changeRequest.mergeability === undefined |
| 1846 | ? {} |
| 1847 | : { mergeability: changeRequest.mergeability }), |
| 1848 | ...(changeRequest.rebaseRequired === undefined |
| 1849 | ? {} |
| 1850 | : { rebaseRequired: changeRequest.rebaseRequired }), |
| 1851 | ...(changeRequest.stack === undefined ? {} : { stack: changeRequest.stack }), |
| 1852 | ...(changeRequest.headSha?.trim() ? { headSha: changeRequest.headSha.trim() } : {}), |
| 1853 | ...(changeRequest.autoMergeEnabled === undefined |
| 1854 | ? {} |
| 1855 | : { autoMergeEnabled: changeRequest.autoMergeEnabled }), |
| 1856 | ...(changeRequest.autoMergeMethod === undefined |
| 1857 | ? {} |
| 1858 | : { autoMergeMethod: changeRequest.autoMergeMethod }), |
| 1859 | }); |
| 1860 | |
| 1861 | const summaryUncached: PullRequestService["Service"]["summary"] = (input) => |
| 1862 | requireProject(input).pipe( |
| 1863 | Effect.flatMap((project) => { |
| 1864 | const providerInput = { |
| 1865 | cwd: project.project.workspaceRoot, |
| 1866 | repository: project.repository, |
| 1867 | host: project.host, |
| 1868 | number: input.number, |
| 1869 | }; |
| 1870 | const read: Effect.Effect< |
| 1871 | ProviderChangeRequestSummary | ProviderChangeRequestDetail, |
| 1872 | PullRequestProviderError |
| 1873 | > = |
| 1874 | project.api.getChangeRequestSummary === undefined |
| 1875 | ? project.api.getChangeRequest(providerInput) |
| 1876 | : project.api.getChangeRequestSummary(providerInput); |
| 1877 | return read.pipe( |
| 1878 | Effect.mapError(toPullRequestError("summary")), |
| 1879 | observeRead, |
| 1880 | Effect.map(({ value, observedAt }) => toSummary(project, value, observedAt)), |
| 1881 | ); |
| 1882 | }), |
| 1883 | ); |
| 1884 | |
| 1885 | const stackUncached: PullRequestService["Service"]["stack"] = (input, options) => |
| 1886 | requireProject(input).pipe( |
| 1887 | Effect.flatMap((project) => { |
| 1888 | const read = project.api.getChangeRequestStack; |
| 1889 | if (read === undefined) return Effect.succeed(null); |
| 1890 | return read({ |
| 1891 | cwd: project.project.workspaceRoot, |
| 1892 | repository: project.repository, |
| 1893 | host: project.host, |
| 1894 | number: input.number, |
| 1895 | includeDetails: options?.includeDetails !== false, |
| 1896 | }).pipe( |
| 1897 | Effect.mapError(toPullRequestError("stack")), |
| 1898 | Effect.map((stack): PullRequestStack | null => |
| 1899 | stack === null |
| 1900 | ? null |
| 1901 | : { |
| 1902 | id: stack.id, |
| 1903 | number: stack.number, |
| 1904 | url: stack.url, |
| 1905 | base: stack.base, |
| 1906 | layers: stack.layers.map((layer) => ({ |
| 1907 | ...layer, |
| 1908 | number: layer.number, |
| 1909 | headBranch: layer.headBranch, |
| 1910 | state: layer.state, |
| 1911 | })), |
| 1912 | }, |
| 1913 | ), |
| 1914 | ); |
| 1915 | }), |
| 1916 | ); |
| 1917 | |
| 1918 | const detailUncached: PullRequestService["Service"]["detail"] = (input) => |
| 1919 | requireProject(input).pipe( |
| 1920 | Effect.flatMap((project) => |
| 1921 | Effect.all( |
| 1922 | [ |
| 1923 | project.api |
| 1924 | .getChangeRequest({ |
| 1925 | cwd: project.project.workspaceRoot, |
| 1926 | repository: project.repository, |
| 1927 | host: project.host, |
| 1928 | number: input.number, |
| 1929 | }) |
| 1930 | .pipe(Effect.mapError(toPullRequestError("detail")), observeRead), |
| 1931 | viewerOf(project), |
| 1932 | ], |
| 1933 | { concurrency: 2 }, |
| 1934 | ).pipe( |
| 1935 | Effect.map(([{ value: changeRequest, observedAt }, viewer]): PullRequestDetail => ({ |
| 1936 | provider: project.api.kind, |
| 1937 | capabilities: project.api.capabilities, |
| 1938 | projectId: project.project.id, |
| 1939 | projectTitle: project.project.title, |
| 1940 | workspaceRoot: project.project.workspaceRoot, |
| 1941 | repository: project.repository, |
| 1942 | number: changeRequest.number, |
| 1943 | title: changeRequest.title, |
| 1944 | body: changeRequest.body, |
| 1945 | url: changeRequest.url, |
| 1946 | author: changeRequest.author, |
| 1947 | state: changeRequest.state, |
| 1948 | isDraft: changeRequest.isDraft, |
| 1949 | mergeability: changeRequest.mergeability, |
| 1950 | ...(changeRequest.rebaseRequired === undefined |
| 1951 | ? {} |
| 1952 | : { rebaseRequired: changeRequest.rebaseRequired }), |
| 1953 | additions: changeRequest.additions, |
| 1954 | deletions: changeRequest.deletions, |
| 1955 | changedFiles: changeRequest.changedFiles, |
| 1956 | headBranch: changeRequest.headBranch, |
| 1957 | ...(changeRequest.headRepositoryNameWithOwner === undefined |
| 1958 | ? {} |
| 1959 | : { headRepositoryNameWithOwner: changeRequest.headRepositoryNameWithOwner }), |
| 1960 | ...(changeRequest.headSha ? { headSha: changeRequest.headSha } : {}), |
| 1961 | baseBranch: changeRequest.baseBranch, |
| 1962 | createdAt: changeRequest.createdAt, |
| 1963 | updatedAt: changeRequest.updatedAt, |
| 1964 | observedAt, |
| 1965 | mergedAt: changeRequest.mergedAt, |
| 1966 | ...(changeRequest.mergeCommitSha |
| 1967 | ? { mergeCommitSha: changeRequest.mergeCommitSha } |
| 1968 | : {}), |
| 1969 | ...(changeRequest.mergedBy ? { mergedBy: changeRequest.mergedBy } : {}), |
| 1970 | closedAt: changeRequest.closedAt, |
| 1971 | reviewers: changeRequest.reviewers, |
| 1972 | labels: changeRequest.labels, |
| 1973 | checks: changeRequest.checks, |
| 1974 | mergeCapabilities: changeRequest.mergeCapabilities, |
| 1975 | viewerPermissions: changeRequest.viewerPermissions, |
| 1976 | ...(viewer === null || viewer.trim().length === 0 ? {} : { viewer }), |
| 1977 | ...(changeRequest.baseComparison === undefined |
| 1978 | ? {} |
| 1979 | : { baseComparison: changeRequest.baseComparison }), |
| 1980 | ...(changeRequest.behindBy === undefined ? {} : { behindBy: changeRequest.behindBy }), |
| 1981 | ...(changeRequest.autoMergeEnabled === undefined |
| 1982 | ? {} |
| 1983 | : { autoMergeEnabled: changeRequest.autoMergeEnabled }), |
| 1984 | ...(changeRequest.autoMergeMethod === undefined |
| 1985 | ? {} |
| 1986 | : { autoMergeMethod: changeRequest.autoMergeMethod }), |
| 1987 | ...(changeRequest.maintainerCanModify === undefined |
| 1988 | ? {} |
| 1989 | : { maintainerCanModify: changeRequest.maintainerCanModify }), |
| 1990 | ...(changeRequest.workflowApprovalsRequired === undefined |
| 1991 | ? {} |
| 1992 | : { workflowApprovalsRequired: changeRequest.workflowApprovalsRequired }), |
| 1993 | ...(changeRequest.mergeQueueRemoval === undefined |
| 1994 | ? {} |
| 1995 | : { mergeQueueRemoval: changeRequest.mergeQueueRemoval }), |
| 1996 | })), |
| 1997 | ), |
| 1998 | ), |
| 1999 | ); |
| 2000 | |
| 2001 | const previewFields = (value: PullRequestPreview): PullRequestPreview => ({ |
| 2002 | projectId: value.projectId, |
| 2003 | repository: value.repository, |
| 2004 | number: value.number, |
| 2005 | title: value.title, |
| 2006 | url: value.url, |
| 2007 | author: value.author, |
| 2008 | state: value.state, |
| 2009 | isDraft: value.isDraft, |
| 2010 | createdAt: value.createdAt, |
| 2011 | }); |
| 2012 | const previewUncached: PullRequestService["Service"]["preview"] = (input) => |
| 2013 | requireProject(input).pipe( |
| 2014 | Effect.flatMap((project) => |
| 2015 | (project.api.getChangeRequestPreview ?? project.api.getChangeRequest)({ |
| 2016 | cwd: project.project.workspaceRoot, |
| 2017 | repository: project.repository, |
| 2018 | host: project.host, |
| 2019 | number: input.number, |
| 2020 | }).pipe( |
| 2021 | Effect.mapError(toPullRequestError("preview")), |
| 2022 | Effect.map((value) => |
| 2023 | previewFields({ |
| 2024 | ...value, |
| 2025 | projectId: project.project.id, |
| 2026 | repository: project.repository, |
| 2027 | }), |
| 2028 | ), |
| 2029 | ), |
| 2030 | ), |
| 2031 | ); |
| 2032 | |
| 2033 | const activityUncached: PullRequestService["Service"]["activity"] = (input) => |
| 2034 | requireProject(input).pipe( |
| 2035 | Effect.flatMap((project) => |
| 2036 | project.api |
| 2037 | .getChangeRequestActivity({ |
| 2038 | cwd: project.project.workspaceRoot, |
| 2039 | repository: project.repository, |
| 2040 | host: project.host, |
| 2041 | number: input.number, |
| 2042 | }) |
| 2043 | .pipe( |
| 2044 | Effect.mapError(toPullRequestError("activity")), |
| 2045 | Effect.map((activity): PullRequestActivity => ({ |
| 2046 | ...(activity.author === undefined ? {} : { author: activity.author }), |
| 2047 | ...(activity.reviewers === undefined ? {} : { reviewers: activity.reviewers }), |
| 2048 | comments: activity.comments, |
| 2049 | commentCount: activity.commentCount, |
| 2050 | commentsTruncated: activity.commentsTruncated, |
| 2051 | ...(activity.reviewThreadsTruncated === undefined |
| 2052 | ? {} |
| 2053 | : { reviewThreadsTruncated: activity.reviewThreadsTruncated }), |
| 2054 | reviewThreads: activity.reviewThreads, |
| 2055 | ...(activity.overviewThreads === undefined |
| 2056 | ? {} |
| 2057 | : { overviewThreads: activity.overviewThreads }), |
| 2058 | commits: activity.commits, |
| 2059 | ...(activity.reactions === undefined ? {} : { reactions: activity.reactions }), |
| 2060 | })), |
| 2061 | ), |
| 2062 | ), |
| 2063 | ); |
| 2064 | |
| 2065 | const threadComments: PullRequestService["Service"]["threadComments"] = (input) => |
| 2066 | requireProject(input).pipe( |
| 2067 | Effect.flatMap( |
| 2068 | (project): Effect.Effect<PullRequestThreadCommentsResult, PullRequestError> => { |
| 2069 | const read = project.api.getReviewThreadComments; |
| 2070 | if (read === undefined) { |
| 2071 | return Effect.fail( |
| 2072 | new PullRequestOperationError({ |
| 2073 | operation: "threadComments", |
| 2074 | detail: "This host does not page review thread comments.", |
| 2075 | }), |
| 2076 | ); |
| 2077 | } |
| 2078 | return read({ |
| 2079 | cwd: project.project.workspaceRoot, |
| 2080 | repository: project.repository, |
| 2081 | host: project.host, |
| 2082 | number: input.number, |
| 2083 | threadId: input.threadId, |
| 2084 | cursor: input.cursor, |
| 2085 | }).pipe(Effect.mapError(toPullRequestError("threadComments"))); |
| 2086 | }, |
| 2087 | ), |
| 2088 | ); |
| 2089 | |
| 2090 | const diffUncached: PullRequestService["Service"]["diff"] = (input) => |
| 2091 | requireProject(input).pipe( |
| 2092 | Effect.flatMap((project) => |
| 2093 | input.path !== undefined && project.api.capabilities.withheldFileDiff !== true |
| 2094 | ? Effect.fail( |
| 2095 | new PullRequestOperationError({ |
| 2096 | operation: "diff", |
| 2097 | detail: "This host cannot read one file of a change request's diff.", |
| 2098 | }), |
| 2099 | ) |
| 2100 | : project.api.capabilities.diff |
| 2101 | ? project.api |
| 2102 | .getDiff({ |
| 2103 | cwd: project.project.workspaceRoot, |
| 2104 | repository: project.repository, |
| 2105 | host: project.host, |
| 2106 | number: input.number, |
| 2107 | ...(input.path === undefined ? {} : { path: input.path }), |
| 2108 | ...(input.cursor === undefined ? {} : { cursor: input.cursor }), |
| 2109 | ...(input.commit === undefined ? {} : { commit: input.commit }), |
| 2110 | }) |
| 2111 | .pipe(Effect.mapError(toPullRequestError("diff"))) |
| 2112 | : Effect.fail( |
| 2113 | new PullRequestOperationError({ |
| 2114 | operation: "diff", |
| 2115 | detail: "This host cannot provide a diff for a change request.", |
| 2116 | }), |
| 2117 | ), |
| 2118 | ), |
| 2119 | ); |
| 2120 | |
| 2121 | const readDiffFileContents: PullRequestService["Service"]["diffFileContents"] = (input) => |
| 2122 | requireProject(input).pipe( |
| 2123 | Effect.flatMap((project) => { |
| 2124 | const read = project.api.getDiffFileContents; |
| 2125 | return project.api.capabilities.diff && read |
| 2126 | ? read({ |
| 2127 | cwd: project.project.workspaceRoot, |
| 2128 | repository: project.repository, |
| 2129 | host: project.host, |
| 2130 | number: input.number, |
| 2131 | ...(input.commit === undefined ? {} : { commit: input.commit }), |
| 2132 | changeType: input.changeType, |
| 2133 | oldPath: input.oldPath, |
| 2134 | newPath: input.newPath, |
| 2135 | }).pipe(Effect.mapError(toPullRequestError("diffFileContents"))) |
| 2136 | : Effect.fail( |
| 2137 | new PullRequestOperationError({ |
| 2138 | operation: "diffFileContents", |
| 2139 | detail: "This host cannot expand unchanged pull request lines.", |
| 2140 | }), |
| 2141 | ); |
| 2142 | }), |
| 2143 | ); |
| 2144 | |
| 2145 | const context = yield* Effect.context<never>(); |
| 2146 | const scope = yield* Effect.scope; |
| 2147 | const runFork = Effect.runForkWith(context); |
| 2148 | |
| 2149 | // Refuse failed viewer lookups; unnamed fallbacks hide marks and orphan subsequent writes. |
| 2150 | const requiredViewerOf = ( |
| 2151 | project: SupportedProject, |
| 2152 | operation: string, |
| 2153 | ): Effect.Effect<string | null, PullRequestError> => |
| 2154 | resolveViewers([project], new Map(), { allowPaused: true }).pipe( |
| 2155 | Effect.flatMap(([resolved]) => { |
| 2156 | const error = resolved?.error ?? null; |
| 2157 | return error === null |
| 2158 | ? Effect.succeed(resolved?.viewer ?? null) |
| 2159 | : Effect.fail(toPullRequestError(operation)(error)); |
| 2160 | }), |
| 2161 | ); |
| 2162 | |
| 2163 | const setFilesViewed: PullRequestService["Service"]["setFilesViewed"] = (input) => |
| 2164 | canonicalRef(input).pipe( |
| 2165 | Effect.flatMap((ref) => |
| 2166 | viewedFiles.setFilesViewed(input).pipe( |
| 2167 | // Deliberately not `invalidatedByMutation`: ticking a file off says nothing about the |
| 2168 | // change request, and dropping a 300-file diff on every checkbox is the whole cost of |
| 2169 | // the feature. |
| 2170 | Effect.ensuring( |
| 2171 | Effect.sync(() => { |
| 2172 | bumpFilesViewedEpoch(ref); |
| 2173 | if (input.files.some((file) => file.viewed && file.revision !== undefined)) { |
| 2174 | bumpEpoch(fileRevisionEpochs, ref); |
| 2175 | } |
| 2176 | }), |
| 2177 | ), |
| 2178 | ), |
| 2179 | ), |
| 2180 | ); |
| 2181 | |
| 2182 | type ActionOutcome = { |
| 2183 | readonly repository: string; |
| 2184 | readonly summary: PullRequestSummary | undefined; |
| 2185 | }; |
| 2186 | const runAction = ( |
| 2187 | input: PullRequestActionInput, |
| 2188 | ): Effect.Effect<ActionOutcome, PullRequestError> => |
| 2189 | requireProject(input).pipe( |
| 2190 | Effect.flatMap((project): Effect.Effect<ActionOutcome, PullRequestError> => { |
| 2191 | if (input.action === "delete-branch" && project.api.capabilities.deleteBranch !== true) { |
| 2192 | return Effect.fail( |
| 2193 | new PullRequestOperationError({ |
| 2194 | operation: "runAction", |
| 2195 | detail: "This host cannot delete a change request's source branch.", |
| 2196 | }), |
| 2197 | ); |
| 2198 | } |
| 2199 | if ( |
| 2200 | input.stackNumber !== undefined && |
| 2201 | (project.api.capabilities.stackActions !== true || |
| 2202 | !["merge", "update-branch"].includes(input.action) || |
| 2203 | input.expectedStackHeads === undefined || |
| 2204 | (input.action === "update-branch" && input.updateMethod !== "rebase")) |
| 2205 | ) { |
| 2206 | return Effect.fail( |
| 2207 | new PullRequestOperationError({ |
| 2208 | operation: "runAction", |
| 2209 | detail: "This stack action is not supported or has no expected head revision.", |
| 2210 | }), |
| 2211 | ); |
| 2212 | } |
| 2213 | if (!project.api.capabilities.actions.includes(input.action)) { |
| 2214 | return Effect.fail( |
| 2215 | new PullRequestOperationError({ |
| 2216 | operation: "runAction", |
| 2217 | detail: `This host cannot ${input.action} a change request.`, |
| 2218 | }), |
| 2219 | ); |
| 2220 | } |
| 2221 | // Refuse unsupported strategies; providers silently map unrecognized methods to their default. |
| 2222 | if ( |
| 2223 | input.mergeMethod !== undefined && |
| 2224 | !project.api.capabilities.mergeMethods.includes(input.mergeMethod) |
| 2225 | ) { |
| 2226 | return Effect.fail( |
| 2227 | new PullRequestOperationError({ |
| 2228 | operation: "runAction", |
| 2229 | detail: `This host cannot merge with the ${input.mergeMethod} strategy.`, |
| 2230 | }), |
| 2231 | ); |
| 2232 | } |
| 2233 | if ( |
| 2234 | input.updateMethod !== undefined && |
| 2235 | !(project.api.capabilities.updateMethods ?? []).includes(input.updateMethod) |
| 2236 | ) { |
| 2237 | return Effect.fail( |
| 2238 | new PullRequestOperationError({ |
| 2239 | operation: "runAction", |
| 2240 | detail: `This host cannot update a branch by ${input.updateMethod}.`, |
| 2241 | }), |
| 2242 | ); |
| 2243 | } |
| 2244 | const operation = viewerPermissionsOf( |
| 2245 | project, |
| 2246 | input, |
| 2247 | "runAction", |
| 2248 | input.action === "update-branch", |
| 2249 | ).pipe( |
| 2250 | Effect.flatMap((viewer): Effect.Effect<ActionOutcome, PullRequestError> => { |
| 2251 | const stackRebase = input.stackNumber !== undefined && input.action === "update-branch"; |
| 2252 | if ( |
| 2253 | stackRebase ? viewer.stackRebase !== true : !viewer.actions.includes(input.action) |
| 2254 | ) { |
| 2255 | return Effect.fail( |
| 2256 | new PullRequestOperationError({ |
| 2257 | operation: "runAction", |
| 2258 | detail: ACTION_ACCESS_REFUSALS[input.action], |
| 2259 | }), |
| 2260 | ); |
| 2261 | } |
| 2262 | if ( |
| 2263 | !stackRebase && |
| 2264 | input.updateMethod !== undefined && |
| 2265 | !(viewer.updateMethods ?? []).includes(input.updateMethod) |
| 2266 | ) { |
| 2267 | return Effect.fail( |
| 2268 | new PullRequestOperationError({ |
| 2269 | operation: "runAction", |
| 2270 | detail: ACTION_ACCESS_REFUSALS["update-branch"], |
| 2271 | }), |
| 2272 | ); |
| 2273 | } |
| 2274 | const mergeSettings = |
| 2275 | project.api.mergeMessageRewrite !== undefined && |
| 2276 | input.stackNumber === undefined && |
| 2277 | (input.action === "merge" || input.action === "enable-auto-merge") |
| 2278 | ? serverSettings.getSettings.pipe( |
| 2279 | Effect.map( |
| 2280 | (settings) => |
| 2281 | resolveProjectSettings(settings, project.project.id).settings |
| 2282 | .removeAgentCreditsOnMerge, |
| 2283 | ), |
| 2284 | Effect.mapError( |
| 2285 | () => |
| 2286 | new PullRequestOperationError({ |
| 2287 | operation: "runAction", |
| 2288 | detail: "Could not read merge settings.", |
| 2289 | }), |
| 2290 | ), |
| 2291 | ) |
| 2292 | : Effect.succeed(false); |
| 2293 | // Hosts that cannot pin a merge to a commit still refuse a head that already moved. |
| 2294 | const expected = input.expectedHeadSha; |
| 2295 | const headPinned: Effect.Effect<string | undefined, PullRequestError> = |
| 2296 | expected === undefined |
| 2297 | ? Effect.undefined |
| 2298 | : project.api |
| 2299 | .getChangeRequest({ |
| 2300 | cwd: project.project.workspaceRoot, |
| 2301 | repository: project.repository, |
| 2302 | host: project.host, |
| 2303 | number: input.number, |
| 2304 | }) |
| 2305 | .pipe( |
| 2306 | Effect.mapError(toPullRequestError("runAction")), |
| 2307 | Effect.flatMap((current) => |
| 2308 | typeof current.headSha === "string" && isHeadSha(current.headSha, expected) |
| 2309 | ? Effect.succeed(current.headSha) |
| 2310 | : Effect.fail( |
| 2311 | new PullRequestOperationError({ |
| 2312 | operation: "runAction", |
| 2313 | detail: `The head is now ${current.headSha ?? "unknown"}, not ${expected}. Review the new commits first.`, |
| 2314 | }), |
| 2315 | ), |
| 2316 | ), |
| 2317 | ); |
| 2318 | return headPinned.pipe( |
| 2319 | Effect.flatMap((expectedHeadSha) => |
| 2320 | Effect.map(mergeSettings, (removeAgentCreditsOnMerge) => ({ |
| 2321 | expectedHeadSha, |
| 2322 | removeAgentCreditsOnMerge, |
| 2323 | })), |
| 2324 | ), |
| 2325 | Effect.flatMap(({ expectedHeadSha, removeAgentCreditsOnMerge }) => |
| 2326 | project.api |
| 2327 | .runAction({ |
| 2328 | cwd: project.project.workspaceRoot, |
| 2329 | repository: project.repository, |
| 2330 | host: project.host, |
| 2331 | number: input.number, |
| 2332 | action: input.action, |
| 2333 | ...(removeAgentCreditsOnMerge ? { removeAgentCreditsOnMerge: true } : {}), |
| 2334 | ...(input.stackNumber === undefined ? {} : { stackNumber: input.stackNumber }), |
| 2335 | ...(input.expectedStackHeads === undefined |
| 2336 | ? {} |
| 2337 | : { expectedStackHeads: input.expectedStackHeads }), |
| 2338 | ...(expectedHeadSha === undefined ? {} : { expectedHeadSha }), |
| 2339 | ...(input.mergeMethod === undefined ? {} : { mergeMethod: input.mergeMethod }), |
| 2340 | ...(input.updateMethod === undefined |
| 2341 | ? {} |
| 2342 | : { updateMethod: input.updateMethod }), |
| 2343 | }) |
| 2344 | .pipe( |
| 2345 | Effect.ensuring( |
| 2346 | input.stackNumber === undefined |
| 2347 | ? Effect.void |
| 2348 | : refreshAfterTurn(project.project.id), |
| 2349 | ), |
| 2350 | Effect.mapError(toPullRequestError("runAction")), |
| 2351 | observeRead, |
| 2352 | Effect.map(({ value, observedAt }) => ({ |
| 2353 | repository: |
| 2354 | project.repositoryKey !== null |
| 2355 | ? input.repository.trim() |
| 2356 | : project.repository, |
| 2357 | summary: |
| 2358 | value === undefined || input.stackNumber !== undefined |
| 2359 | ? undefined |
| 2360 | : toSummary(project, value, observedAt, true), |
| 2361 | })), |
| 2362 | ), |
| 2363 | ), |
| 2364 | ); |
| 2365 | }), |
| 2366 | ); |
| 2367 | return input.action === "delete-branch" && project.api.withVerifiedCredential !== undefined |
| 2368 | ? project.api |
| 2369 | .withVerifiedCredential( |
| 2370 | { |
| 2371 | cwd: project.project.workspaceRoot, |
| 2372 | host: project.host, |
| 2373 | repository: project.repository, |
| 2374 | }, |
| 2375 | () => operation.pipe(Effect.result), |
| 2376 | ) |
| 2377 | .pipe( |
| 2378 | Effect.mapError(toPullRequestError("runAction")), |
| 2379 | Effect.flatMap(Effect.fromResult), |
| 2380 | ) |
| 2381 | : operation; |
| 2382 | }), |
| 2383 | ); |
| 2384 | |
| 2385 | const comment: PullRequestService["Service"]["comment"] = (input) => |
| 2386 | (input.body.trim().length === 0 |
| 2387 | ? Effect.fail( |
| 2388 | new PullRequestOperationError({ |
| 2389 | operation: "comment", |
| 2390 | detail: "A comment cannot be empty.", |
| 2391 | }), |
| 2392 | ) |
| 2393 | : requireProject(input) |
| 2394 | ).pipe( |
| 2395 | Effect.flatMap((project): Effect.Effect<void, PullRequestError> => { |
| 2396 | if (!project.api.capabilities.comment) { |
| 2397 | return Effect.fail( |
| 2398 | new PullRequestOperationError({ |
| 2399 | operation: "comment", |
| 2400 | detail: "This host cannot post a comment on a change request.", |
| 2401 | }), |
| 2402 | ); |
| 2403 | } |
| 2404 | return viewerPermissionsOf(project, input, "comment").pipe( |
| 2405 | Effect.flatMap((viewer): Effect.Effect<void, PullRequestError> => { |
| 2406 | if (!viewer.comment) { |
| 2407 | return Effect.fail( |
| 2408 | new PullRequestOperationError({ |
| 2409 | operation: "comment", |
| 2410 | detail: |
| 2411 | "You need write access on this repository to comment on a change request.", |
| 2412 | }), |
| 2413 | ); |
| 2414 | } |
| 2415 | return project.api |
| 2416 | .comment({ |
| 2417 | cwd: project.project.workspaceRoot, |
| 2418 | repository: project.repository, |
| 2419 | host: project.host, |
| 2420 | number: input.number, |
| 2421 | body: input.body, |
| 2422 | }) |
| 2423 | .pipe(Effect.mapError(toPullRequestError("comment"))); |
| 2424 | }), |
| 2425 | ); |
| 2426 | }), |
| 2427 | ); |
| 2428 | |
| 2429 | // Hosts let authors edit without reporting that permission; checking it would wrongly deny access. |
| 2430 | const update: PullRequestService["Service"]["update"] = (input) => |
| 2431 | requireProject(input).pipe( |
| 2432 | Effect.flatMap((project): Effect.Effect<void, PullRequestError> => { |
| 2433 | const rewrite = project.api.updateChangeRequest; |
| 2434 | if (project.api.capabilities.edit?.changeRequest !== true || rewrite === undefined) { |
| 2435 | return Effect.fail( |
| 2436 | new PullRequestOperationError({ |
| 2437 | operation: "update", |
| 2438 | detail: "This host cannot rewrite a change request.", |
| 2439 | }), |
| 2440 | ); |
| 2441 | } |
| 2442 | if ( |
| 2443 | input.maintainerCanModify !== undefined && |
| 2444 | project.api.capabilities.edit?.maintainerEdits !== true |
| 2445 | ) { |
| 2446 | return Effect.fail( |
| 2447 | new PullRequestOperationError({ |
| 2448 | operation: "update", |
| 2449 | detail: "This host does not support maintainer edits.", |
| 2450 | }), |
| 2451 | ); |
| 2452 | } |
| 2453 | if ( |
| 2454 | input.title === undefined && |
| 2455 | input.body === undefined && |
| 2456 | input.maintainerCanModify === undefined |
| 2457 | ) { |
| 2458 | return Effect.fail( |
| 2459 | new PullRequestOperationError({ |
| 2460 | operation: "update", |
| 2461 | detail: "Nothing was changed.", |
| 2462 | }), |
| 2463 | ); |
| 2464 | } |
| 2465 | return rewrite({ |
| 2466 | cwd: project.project.workspaceRoot, |
| 2467 | repository: project.repository, |
| 2468 | host: project.host, |
| 2469 | number: input.number, |
| 2470 | ...(input.maintainerCanModify === undefined |
| 2471 | ? {} |
| 2472 | : { maintainerCanModify: input.maintainerCanModify }), |
| 2473 | ...(input.title === undefined ? {} : { title: input.title }), |
| 2474 | ...(input.body === undefined ? {} : { body: input.body }), |
| 2475 | }).pipe(Effect.mapError(toPullRequestError("update"))); |
| 2476 | }), |
| 2477 | ); |
| 2478 | |
| 2479 | const updateComment: PullRequestService["Service"]["updateComment"] = (input) => |
| 2480 | (input.body.trim().length === 0 |
| 2481 | ? Effect.fail( |
| 2482 | new PullRequestOperationError({ |
| 2483 | operation: "updateComment", |
| 2484 | detail: "A comment cannot be empty.", |
| 2485 | }), |
| 2486 | ) |
| 2487 | : requireProject(input) |
| 2488 | ).pipe( |
| 2489 | Effect.flatMap((project): Effect.Effect<void, PullRequestError> => { |
| 2490 | const rewrite = project.api.updateComment; |
| 2491 | if (project.api.capabilities.edit?.comment !== true || rewrite === undefined) { |
| 2492 | return Effect.fail( |
| 2493 | new PullRequestOperationError({ |
| 2494 | operation: "updateComment", |
| 2495 | detail: "This host cannot rewrite a comment.", |
| 2496 | }), |
| 2497 | ); |
| 2498 | } |
| 2499 | return rewrite({ |
| 2500 | cwd: project.project.workspaceRoot, |
| 2501 | repository: project.repository, |
| 2502 | host: project.host, |
| 2503 | number: input.number, |
| 2504 | commentId: input.commentId, |
| 2505 | kind: input.kind, |
| 2506 | body: input.body, |
| 2507 | }).pipe(Effect.mapError(toPullRequestError("updateComment"))); |
| 2508 | }), |
| 2509 | ); |
| 2510 | |
| 2511 | const submitReview: PullRequestService["Service"]["submitReview"] = (input) => |
| 2512 | requireProject(input).pipe( |
| 2513 | Effect.flatMap((project): Effect.Effect<void, PullRequestError> => { |
| 2514 | const review = project.api.capabilities.review; |
| 2515 | const refuse = (detail: string) => |
| 2516 | Effect.fail(new PullRequestOperationError({ operation: "submitReview", detail })); |
| 2517 | if (!review.verdicts.includes(input.verdict)) { |
| 2518 | return refuse(`This host cannot ${VERDICT_LABELS[input.verdict]} a change request.`); |
| 2519 | } |
| 2520 | if (input.comments.length > 0 && !review.inlineComment) { |
| 2521 | return refuse("This host cannot comment on a line of a change request."); |
| 2522 | } |
| 2523 | if ( |
| 2524 | input.verdict !== "approve" && |
| 2525 | input.body.trim().length === 0 && |
| 2526 | input.comments.length === 0 |
| 2527 | ) { |
| 2528 | return refuse("A review needs a summary or at least one comment."); |
| 2529 | } |
| 2530 | return viewerPermissionsOf(project, input, "submitReview").pipe( |
| 2531 | Effect.flatMap((viewer): Effect.Effect<void, PullRequestError> => { |
| 2532 | if (!viewer.verdicts.includes(input.verdict)) { |
| 2533 | return refuse( |
| 2534 | `You need write access on this repository to ${ |
| 2535 | VERDICT_LABELS[input.verdict] |
| 2536 | } a change request.`, |
| 2537 | ); |
| 2538 | } |
| 2539 | if (input.comments.length > 0 && !viewer.comment) { |
| 2540 | return refuse( |
| 2541 | "You need write access on this repository to comment on a line of a change request.", |
| 2542 | ); |
| 2543 | } |
| 2544 | return project.api |
| 2545 | .submitReview({ |
| 2546 | cwd: project.project.workspaceRoot, |
| 2547 | repository: project.repository, |
| 2548 | host: project.host, |
| 2549 | number: input.number, |
| 2550 | verdict: input.verdict, |
| 2551 | body: input.body, |
| 2552 | comments: input.comments, |
| 2553 | }) |
| 2554 | .pipe(Effect.mapError(toPullRequestError("submitReview"))); |
| 2555 | }), |
| 2556 | ); |
| 2557 | }), |
| 2558 | ); |
| 2559 | |
| 2560 | const replyToThread: PullRequestService["Service"]["replyToThread"] = (input) => |
| 2561 | (input.body.trim().length === 0 |
| 2562 | ? Effect.fail( |
| 2563 | new PullRequestOperationError({ |
| 2564 | operation: "replyToThread", |
| 2565 | detail: "A reply cannot be empty.", |
| 2566 | }), |
| 2567 | ) |
| 2568 | : requireProject(input) |
| 2569 | ).pipe( |
| 2570 | Effect.flatMap((project): Effect.Effect<void, PullRequestError> => { |
| 2571 | if (!project.api.capabilities.review.reply) { |
| 2572 | return Effect.fail( |
| 2573 | new PullRequestOperationError({ |
| 2574 | operation: "replyToThread", |
| 2575 | detail: "This host cannot reply to a review conversation.", |
| 2576 | }), |
| 2577 | ); |
| 2578 | } |
| 2579 | return viewerPermissionsOf(project, input, "replyToThread").pipe( |
| 2580 | Effect.flatMap((viewer): Effect.Effect<void, PullRequestError> => { |
| 2581 | if (!viewer.comment) { |
| 2582 | return Effect.fail( |
| 2583 | new PullRequestOperationError({ |
| 2584 | operation: "replyToThread", |
| 2585 | detail: |
| 2586 | "You need write access on this repository to reply to a review conversation.", |
| 2587 | }), |
| 2588 | ); |
| 2589 | } |
| 2590 | return project.api |
| 2591 | .replyToThread({ |
| 2592 | cwd: project.project.workspaceRoot, |
| 2593 | repository: project.repository, |
| 2594 | host: project.host, |
| 2595 | number: input.number, |
| 2596 | threadId: input.threadId, |
| 2597 | body: input.body, |
| 2598 | }) |
| 2599 | .pipe(Effect.mapError(toPullRequestError("replyToThread"))); |
| 2600 | }), |
| 2601 | ); |
| 2602 | }), |
| 2603 | ); |
| 2604 | |
| 2605 | const setThreadResolution: PullRequestService["Service"]["setThreadResolution"] = (input) => |
| 2606 | requireProject(input).pipe( |
| 2607 | Effect.flatMap((project): Effect.Effect<void, PullRequestError> => { |
| 2608 | if (!project.api.capabilities.review.resolve) { |
| 2609 | return Effect.fail( |
| 2610 | new PullRequestOperationError({ |
| 2611 | operation: "setThreadResolution", |
| 2612 | detail: "This host cannot resolve a review conversation.", |
| 2613 | }), |
| 2614 | ); |
| 2615 | } |
| 2616 | return viewerPermissionsOf(project, input, "setThreadResolution").pipe( |
| 2617 | Effect.flatMap((viewer): Effect.Effect<void, PullRequestError> => { |
| 2618 | if (!viewer.resolve) { |
| 2619 | return Effect.fail( |
| 2620 | new PullRequestOperationError({ |
| 2621 | operation: "setThreadResolution", |
| 2622 | detail: |
| 2623 | "You need write access on this repository, or to have opened this change request, to resolve a review conversation.", |
| 2624 | }), |
| 2625 | ); |
| 2626 | } |
| 2627 | return project.api |
| 2628 | .setThreadResolution({ |
| 2629 | cwd: project.project.workspaceRoot, |
| 2630 | repository: project.repository, |
| 2631 | host: project.host, |
| 2632 | number: input.number, |
| 2633 | threadId: input.threadId, |
| 2634 | resolved: input.resolved, |
| 2635 | }) |
| 2636 | .pipe(Effect.mapError(toPullRequestError("setThreadResolution"))); |
| 2637 | }), |
| 2638 | ); |
| 2639 | }), |
| 2640 | ); |
| 2641 | |
| 2642 | // Hosts permit reactions from any reader; reading the PR already checks access. |
| 2643 | const setReaction: PullRequestService["Service"]["setReaction"] = (input) => |
| 2644 | requireProject(input).pipe( |
| 2645 | Effect.flatMap((project): Effect.Effect<void, PullRequestError> => { |
| 2646 | if (project.api.capabilities.reactions !== true) { |
| 2647 | return Effect.fail( |
| 2648 | new PullRequestOperationError({ |
| 2649 | operation: "setReaction", |
| 2650 | detail: "This host has no reactions.", |
| 2651 | }), |
| 2652 | ); |
| 2653 | } |
| 2654 | return project.api |
| 2655 | .setReaction({ |
| 2656 | cwd: project.project.workspaceRoot, |
| 2657 | repository: project.repository, |
| 2658 | host: project.host, |
| 2659 | number: input.number, |
| 2660 | ...(input.subjectId === undefined ? {} : { subjectId: input.subjectId }), |
| 2661 | content: input.content, |
| 2662 | reacted: input.reacted, |
| 2663 | }) |
| 2664 | .pipe(Effect.mapError(toPullRequestError("setReaction"))); |
| 2665 | }), |
| 2666 | ); |
| 2667 | |
| 2668 | const reviewerCandidates: PullRequestService["Service"]["reviewerCandidates"] = (input) => |
| 2669 | requireProject(input).pipe( |
| 2670 | Effect.flatMap( |
| 2671 | (project): Effect.Effect<PullRequestReviewerCandidateList, PullRequestError> => { |
| 2672 | if (!project.api.capabilities.reviewers.listCandidates) { |
| 2673 | return Effect.fail( |
| 2674 | new PullRequestOperationError({ |
| 2675 | operation: "reviewerCandidates", |
| 2676 | detail: "This host cannot say who may review a change request.", |
| 2677 | }), |
| 2678 | ); |
| 2679 | } |
| 2680 | return viewerPermissionsOf(project, input, "reviewerCandidates").pipe( |
| 2681 | Effect.flatMap( |
| 2682 | (viewer): Effect.Effect<PullRequestReviewerCandidateList, PullRequestError> => |
| 2683 | viewer.requestReviewers |
| 2684 | ? project.api |
| 2685 | .listReviewerCandidates({ |
| 2686 | cwd: project.project.workspaceRoot, |
| 2687 | repository: project.repository, |
| 2688 | host: project.host, |
| 2689 | number: input.number, |
| 2690 | query: input.query, |
| 2691 | }) |
| 2692 | .pipe(Effect.mapError(toPullRequestError("reviewerCandidates"))) |
| 2693 | : Effect.fail( |
| 2694 | new PullRequestOperationError({ |
| 2695 | operation: "reviewerCandidates", |
| 2696 | detail: REVIEWER_REQUEST_REFUSAL, |
| 2697 | }), |
| 2698 | ), |
| 2699 | ), |
| 2700 | ); |
| 2701 | }, |
| 2702 | ), |
| 2703 | ); |
| 2704 | |
| 2705 | const requestReviewers: PullRequestService["Service"]["requestReviewers"] = (input) => |
| 2706 | requireProject(input).pipe( |
| 2707 | Effect.flatMap((project): Effect.Effect<void, PullRequestError> => { |
| 2708 | if (!project.api.capabilities.reviewers.request) { |
| 2709 | return Effect.fail( |
| 2710 | new PullRequestOperationError({ |
| 2711 | operation: "requestReviewers", |
| 2712 | detail: "This host cannot ask somebody for a review.", |
| 2713 | }), |
| 2714 | ); |
| 2715 | } |
| 2716 | return viewerPermissionsOf(project, input, "requestReviewers").pipe( |
| 2717 | Effect.flatMap((viewer): Effect.Effect<void, PullRequestError> => { |
| 2718 | if (!viewer.requestReviewers) { |
| 2719 | return Effect.fail( |
| 2720 | new PullRequestOperationError({ |
| 2721 | operation: "requestReviewers", |
| 2722 | detail: REVIEWER_REQUEST_REFUSAL, |
| 2723 | }), |
| 2724 | ); |
| 2725 | } |
| 2726 | return project.api |
| 2727 | .setReviewerRequest({ |
| 2728 | cwd: project.project.workspaceRoot, |
| 2729 | repository: project.repository, |
| 2730 | host: project.host, |
| 2731 | number: input.number, |
| 2732 | reviewers: input.reviewers, |
| 2733 | requested: input.requested, |
| 2734 | }) |
| 2735 | .pipe(Effect.mapError(toPullRequestError("requestReviewers"))); |
| 2736 | }), |
| 2737 | ); |
| 2738 | }), |
| 2739 | ); |
| 2740 | |
| 2741 | const filterOptions: PullRequestService["Service"]["filterOptions"] = Effect.fn( |
| 2742 | "PullRequestService.filterOptions", |
| 2743 | )(function* (input) { |
| 2744 | const { supported } = yield* listWorkspaceProjects(input); |
| 2745 | // Worktrees of one checkout are separate projects over the same repository. |
| 2746 | const repositories = [ |
| 2747 | ...new Map(supported.map((project) => [project.cursorKey, project])).values(), |
| 2748 | ]; |
| 2749 | const refOf = (project: SupportedProject) => ({ |
| 2750 | cwd: project.project.workspaceRoot, |
| 2751 | repository: project.repository, |
| 2752 | host: project.host, |
| 2753 | query: input.query, |
| 2754 | }); |
| 2755 | // One repository the host cannot read leaves the others' options standing, as a listing does. |
| 2756 | const gather = <A>( |
| 2757 | read: ( |
| 2758 | project: SupportedProject, |
| 2759 | ) => Effect.Effect<ProviderFilterOptionPage<A>, PullRequestProviderError> | undefined, |
| 2760 | ) => |
| 2761 | Effect.forEach( |
| 2762 | repositories, |
| 2763 | (project): Effect.Effect<ReadonlyArray<ProviderFilterOptionPage<A>>> => { |
| 2764 | const page = read(project); |
| 2765 | return page === undefined |
| 2766 | ? Effect.succeed([]) |
| 2767 | : page.pipe( |
| 2768 | Effect.map((answered) => [answered]), |
| 2769 | Effect.orElseSucceed(() => []), |
| 2770 | ); |
| 2771 | }, |
| 2772 | { concurrency: REPOSITORY_CONCURRENCY }, |
| 2773 | ).pipe(Effect.map((pages) => pages.flat())); |
| 2774 | if (input.kind === "labels") { |
| 2775 | const pages = yield* gather<PullRequestLabel>((project) => |
| 2776 | project.api.listRepositoryLabels?.(refOf(project)), |
| 2777 | ); |
| 2778 | const { items, truncated } = rankFilterOptions(pages, { |
| 2779 | query: input.query, |
| 2780 | keyOf: (label) => label.name, |
| 2781 | textsOf: (label) => [label.name], |
| 2782 | }); |
| 2783 | return { labels: items, authors: [], references: [], truncated }; |
| 2784 | } |
| 2785 | if (input.kind === "references") { |
| 2786 | const pages = yield* gather<PullRequestReferenceCandidate>((project) => |
| 2787 | project.api.searchRepositoryReferences?.({ ...refOf(project), sigil: input.sigil }), |
| 2788 | ); |
| 2789 | const { items, truncated } = rankFilterOptions(pages, { |
| 2790 | query: input.query, |
| 2791 | keyOf: (candidate) => candidate.reference, |
| 2792 | textsOf: (candidate) => [String(candidate.number), candidate.title], |
| 2793 | hostOrder: true, |
| 2794 | }); |
| 2795 | return { labels: [], authors: [], references: items, truncated }; |
| 2796 | } |
| 2797 | const pages = yield* gather<PullRequestActor>((project) => |
| 2798 | project.api.searchRepositoryAuthors?.(refOf(project)), |
| 2799 | ); |
| 2800 | const { items, truncated } = rankFilterOptions(pages, { |
| 2801 | query: input.query, |
| 2802 | keyOf: (author) => author.login, |
| 2803 | textsOf: (author) => [author.login, author.name], |
| 2804 | }); |
| 2805 | return { labels: [], authors: items, references: [], truncated }; |
| 2806 | }); |
| 2807 | |
| 2808 | const labelCandidates: PullRequestService["Service"]["labelCandidates"] = (input) => |
| 2809 | requireProject(input).pipe( |
| 2810 | Effect.flatMap((project): Effect.Effect<PullRequestLabelCandidateList, PullRequestError> => { |
| 2811 | const list = project.api.listLabelCandidates; |
| 2812 | if (project.api.capabilities.labels !== true || list === undefined) { |
| 2813 | return Effect.fail( |
| 2814 | new PullRequestOperationError({ |
| 2815 | operation: "labelCandidates", |
| 2816 | detail: "This host cannot change the labels on a change request.", |
| 2817 | }), |
| 2818 | ); |
| 2819 | } |
| 2820 | return viewerPermissionsOf(project, input, "labelCandidates").pipe( |
| 2821 | Effect.flatMap( |
| 2822 | (viewer): Effect.Effect<PullRequestLabelCandidateList, PullRequestError> => |
| 2823 | viewer.labels === false |
| 2824 | ? Effect.fail( |
| 2825 | new PullRequestOperationError({ |
| 2826 | operation: "labelCandidates", |
| 2827 | detail: LABEL_CHANGE_REFUSAL, |
| 2828 | }), |
| 2829 | ) |
| 2830 | : list({ |
| 2831 | cwd: project.project.workspaceRoot, |
| 2832 | repository: project.repository, |
| 2833 | host: project.host, |
| 2834 | number: input.number, |
| 2835 | }).pipe(Effect.mapError(toPullRequestError("labelCandidates"))), |
| 2836 | ), |
| 2837 | ); |
| 2838 | }), |
| 2839 | ); |
| 2840 | |
| 2841 | const setLabels: PullRequestService["Service"]["setLabels"] = (input) => |
| 2842 | requireProject(input).pipe( |
| 2843 | Effect.flatMap((project): Effect.Effect<void, PullRequestError> => { |
| 2844 | const change = project.api.setLabels; |
| 2845 | if (project.api.capabilities.labels !== true || change === undefined) { |
| 2846 | return Effect.fail( |
| 2847 | new PullRequestOperationError({ |
| 2848 | operation: "setLabels", |
| 2849 | detail: "This host cannot change the labels on a change request.", |
| 2850 | }), |
| 2851 | ); |
| 2852 | } |
| 2853 | return viewerPermissionsOf(project, input, "setLabels").pipe( |
| 2854 | Effect.flatMap((viewer): Effect.Effect<void, PullRequestError> => |
| 2855 | viewer.labels === false |
| 2856 | ? Effect.fail( |
| 2857 | new PullRequestOperationError({ |
| 2858 | operation: "setLabels", |
| 2859 | detail: LABEL_CHANGE_REFUSAL, |
| 2860 | }), |
| 2861 | ) |
| 2862 | : change({ |
| 2863 | cwd: project.project.workspaceRoot, |
| 2864 | repository: project.repository, |
| 2865 | host: project.host, |
| 2866 | number: input.number, |
| 2867 | labels: input.labels, |
| 2868 | applied: input.applied, |
| 2869 | }).pipe(Effect.mapError(toPullRequestError("setLabels"))), |
| 2870 | ), |
| 2871 | ); |
| 2872 | }), |
| 2873 | ); |
| 2874 | |
| 2875 | /** |
| 2876 | * The line counts for rows already on the page, which the listing left out because on GitHub |
| 2877 | * they cost more than everything else on the row put together. |
| 2878 | */ |
| 2879 | const listStatsUncached: PullRequestService["Service"]["listStats"] = Effect.fn( |
| 2880 | "PullRequestService.listStatsUncached", |
| 2881 | )(function* (input) { |
| 2882 | if (input.refs.length === 0) return { stats: [] }; |
| 2883 | const { supported } = yield* listWorkspaceProjects({}); |
| 2884 | const byProject = new Map(supported.map((project) => [project.project.id, project])); |
| 2885 | const wanted = new Map< |
| 2886 | string, |
| 2887 | { readonly project: SupportedProject; readonly number: number } |
| 2888 | >(); |
| 2889 | for (const ref of input.refs) { |
| 2890 | const project = byProject.get(ref.projectId); |
| 2891 | if ( |
| 2892 | project === undefined || |
| 2893 | project.api.listChangeRequestStats === undefined || |
| 2894 | project.repository.toLowerCase() !== ref.repository.trim().toLowerCase() |
| 2895 | ) { |
| 2896 | continue; |
| 2897 | } |
| 2898 | wanted.set(`${project.project.id} ${ref.number}`, { project, number: ref.number }); |
| 2899 | } |
| 2900 | const byHost = new Map<string, Array<{ project: SupportedProject; number: number }>>(); |
| 2901 | for (const entry of wanted.values()) { |
| 2902 | const held = byHost.get(entry.project.host); |
| 2903 | if (held === undefined) byHost.set(entry.project.host, [entry]); |
| 2904 | else held.push(entry); |
| 2905 | } |
| 2906 | const stats = yield* Effect.forEach( |
| 2907 | [...byHost.values()], |
| 2908 | (entries) => { |
| 2909 | const first = entries[0]!; |
| 2910 | const readStats = first.project.api.listChangeRequestStats; |
| 2911 | if (readStats === undefined) return Effect.succeed<ReadonlyArray<PullRequestDiffStat>>([]); |
| 2912 | const projectsByRepository = new Map( |
| 2913 | entries.map((entry) => [ |
| 2914 | `${entry.project.repository.toLowerCase()} ${entry.number}`, |
| 2915 | entry.project, |
| 2916 | ]), |
| 2917 | ); |
| 2918 | return readStats({ |
| 2919 | cwd: first.project.project.workspaceRoot, |
| 2920 | host: first.project.host, |
| 2921 | changeRequests: entries.map((entry) => ({ |
| 2922 | repository: entry.project.repository, |
| 2923 | number: entry.number, |
| 2924 | })), |
| 2925 | }).pipe( |
| 2926 | Effect.map((read) => |
| 2927 | read.flatMap((stat): ReadonlyArray<PullRequestDiffStat> => { |
| 2928 | const project = projectsByRepository.get( |
| 2929 | `${stat.repository.toLowerCase()} ${stat.number}`, |
| 2930 | ); |
| 2931 | return project === undefined |
| 2932 | ? [] |
| 2933 | : [ |
| 2934 | { |
| 2935 | projectId: project.project.id, |
| 2936 | repository: project.repository, |
| 2937 | number: stat.number, |
| 2938 | additions: stat.additions, |
| 2939 | deletions: stat.deletions, |
| 2940 | }, |
| 2941 | ]; |
| 2942 | }), |
| 2943 | ), |
| 2944 | Effect.orElseSucceed((): ReadonlyArray<PullRequestDiffStat> => []), |
| 2945 | ); |
| 2946 | }, |
| 2947 | { concurrency: REPOSITORY_CONCURRENCY }, |
| 2948 | ); |
| 2949 | return { stats: stats.flat() }; |
| 2950 | }); |
| 2951 | |
| 2952 | const revalidate = <A, E>(read: Effect.Effect<A, E>) => |
| 2953 | Effect.context<never>().pipe( |
| 2954 | Effect.flatMap((caller) => |
| 2955 | Effect.sync(() => runFork(Effect.ignore(read).pipe(Effect.provideContext(caller)))), |
| 2956 | ), |
| 2957 | ); |
| 2958 | |
| 2959 | const staleDiff = (() => { |
| 2960 | const staleMs = Duration.toMillis(DIFF_STALE_WINDOW); |
| 2961 | const held = new Map<string, { readonly at: number; readonly value: PullRequestDiffResult }>(); |
| 2962 | const record = (key: string, value: PullRequestDiffResult) => |
| 2963 | Effect.map(Clock.currentTimeMillis, (at) => { |
| 2964 | held.delete(key); |
| 2965 | if (!canCacheDiff(value)) return; |
| 2966 | if (held.size >= DIFF_CACHE_CAPACITY) { |
| 2967 | const oldest = held.keys().next().value; |
| 2968 | if (oldest !== undefined) held.delete(oldest); |
| 2969 | } |
| 2970 | held.set(key, { at, value }); |
| 2971 | for (const evicted of diffCacheEvictions( |
| 2972 | Array.from(held, ([key, snapshot]) => [key, snapshot.value] as const), |
| 2973 | )) { |
| 2974 | held.delete(evicted); |
| 2975 | } |
| 2976 | armDiffSweep(); |
| 2977 | }); |
| 2978 | const serve = <E>(key: string, read: Effect.Effect<PullRequestDiffResult, E>) => { |
| 2979 | const recorded = read.pipe(Effect.tap((value) => record(key, value))); |
| 2980 | return Effect.flatMap(Clock.currentTimeMillis, (now) => { |
| 2981 | const snapshot = held.get(key); |
| 2982 | if (snapshot === undefined || now - snapshot.at > staleMs) return recorded; |
| 2983 | // Use an independent fiber; refresh outlives the answered caller. |
| 2984 | return revalidate(recorded).pipe(Effect.as(snapshot.value)); |
| 2985 | }); |
| 2986 | }; |
| 2987 | const dropExpired = Effect.map(Clock.currentTimeMillis, (now) => { |
| 2988 | for (const [key, snapshot] of held) { |
| 2989 | if (now - snapshot.at > staleMs) held.delete(key); |
| 2990 | } |
| 2991 | return held.size; |
| 2992 | }); |
| 2993 | return { serve, dropExpired }; |
| 2994 | })(); |
| 2995 | |
| 2996 | const makeLastGoodRead = <A>(capacity: number) => { |
| 2997 | const held = new Map<string, { readonly at: number; readonly value: A }>(); |
| 2998 | const record = (key: string, value: A) => |
| 2999 | Effect.map(Clock.currentTimeMillis, (at) => { |
| 3000 | held.delete(key); |
| 3001 | if (held.size >= capacity) { |
| 3002 | const oldest = held.keys().next().value; |
| 3003 | if (oldest !== undefined) held.delete(oldest); |
| 3004 | } |
| 3005 | held.set(key, { at, value }); |
| 3006 | }); |
| 3007 | const read = (key: string, effect: Effect.Effect<A, PullRequestError>) => |
| 3008 | effect.pipe( |
| 3009 | Effect.tap((value) => record(key, value)), |
| 3010 | Effect.catchTags({ |
| 3011 | PullRequestOperationError: (error) => { |
| 3012 | if (!isPullRequestProviderError(error.cause)) { |
| 3013 | return Effect.fail(error); |
| 3014 | } |
| 3015 | const provider = error.cause; |
| 3016 | if (provider.reason !== "failed" && provider.reason !== "rate-limited") { |
| 3017 | return Effect.fail(error); |
| 3018 | } |
| 3019 | return Effect.flatMap(Clock.currentTimeMillis, (now) => { |
| 3020 | const snapshot = held.get(key); |
| 3021 | if ( |
| 3022 | snapshot === undefined || |
| 3023 | now - snapshot.at > Duration.toMillis(STALE_DETAIL_WINDOW) |
| 3024 | ) { |
| 3025 | return Effect.fail(error); |
| 3026 | } |
| 3027 | return Effect.logWarning("using recent pull request data after a failed refresh", { |
| 3028 | operation: error.operation, |
| 3029 | reason: provider.reason, |
| 3030 | }).pipe(Effect.as(snapshot.value)); |
| 3031 | }); |
| 3032 | }, |
| 3033 | }), |
| 3034 | ); |
| 3035 | const serveHeld = (key: string, effect: Effect.Effect<A, PullRequestError>) => { |
| 3036 | const snapshot = held.get(key); |
| 3037 | if (snapshot === undefined) return read(key, effect); |
| 3038 | return revalidate(read(key, effect)).pipe(Effect.as(snapshot.value)); |
| 3039 | }; |
| 3040 | return { peek: (key: string) => held.get(key)?.value, read, record, serveHeld }; |
| 3041 | }; |
| 3042 | const lastGoodSummary = makeLastGoodRead<PullRequestSummary>(DETAIL_CACHE_CAPACITY); |
| 3043 | const lastGoodDetail = makeLastGoodRead<PullRequestDetail>(DETAIL_CACHE_CAPACITY); |
| 3044 | |
| 3045 | // A shared monotonic counter prevents evicted scopes reusing epochs held by old entries. |
| 3046 | let epochCounter = 0; |
| 3047 | let listingsEpoch = 0; |
| 3048 | const refEpochs = new Map<string, number>(); |
| 3049 | const projectEpochs = new Map<ProjectId, number>(); |
| 3050 | let projectEpochFloor = 0; |
| 3051 | const REF_EPOCH_CAPACITY = 2_048; |
| 3052 | const refScope = (ref: PullRequestRef) => |
| 3053 | JSON.stringify([ |
| 3054 | ref.projectId, |
| 3055 | ref.host?.toLowerCase() ?? "", |
| 3056 | ref.repository.toLowerCase(), |
| 3057 | ref.number, |
| 3058 | ]); |
| 3059 | const mergedEpochs = new Map<string, number>(); |
| 3060 | const refEpoch = (ref: PullRequestRef) => { |
| 3061 | const scope = refScope(ref); |
| 3062 | return Math.max( |
| 3063 | mergedEpochs.get(scope) ?? projectEpochs.get(ref.projectId) ?? projectEpochFloor, |
| 3064 | refEpochs.get(scope) ?? 0, |
| 3065 | ); |
| 3066 | }; |
| 3067 | const noteMerged = (ref: PullRequestRef) => { |
| 3068 | const scope = refScope(ref); |
| 3069 | if (mergedEpochs.has(scope)) return; |
| 3070 | if (mergedEpochs.size >= REF_EPOCH_CAPACITY) { |
| 3071 | const oldest = mergedEpochs.keys().next().value; |
| 3072 | if (oldest !== undefined) mergedEpochs.delete(oldest); |
| 3073 | } |
| 3074 | mergedEpochs.set(scope, projectEpochs.get(ref.projectId) ?? projectEpochFloor); |
| 3075 | }; |
| 3076 | const refCacheKey = (ref: CredentialRef) => |
| 3077 | JSON.stringify([ |
| 3078 | refEpoch(ref), |
| 3079 | ref.projectId, |
| 3080 | ref.host?.toLowerCase() ?? null, |
| 3081 | ref.repository.toLowerCase(), |
| 3082 | ref.number, |
| 3083 | ref.expectedAccountId ?? null, |
| 3084 | ref[credentialNamespace] ?? null, |
| 3085 | ]); |
| 3086 | const refOfCacheKey = (key: string): PullRequestRef => { |
| 3087 | const [, projectId, host, repository, number, expectedAccountId, fingerprint] = JSON.parse( |
| 3088 | key, |
| 3089 | ) as [number, string, string | null, string, number, string | null, string | null]; |
| 3090 | return { |
| 3091 | projectId, |
| 3092 | ...(host === null ? {} : { host }), |
| 3093 | ...(expectedAccountId === null ? {} : { expectedAccountId }), |
| 3094 | ...(fingerprint === null ? {} : { [credentialNamespace]: fingerprint }), |
| 3095 | repository, |
| 3096 | number, |
| 3097 | } as PullRequestRef; |
| 3098 | }; |
| 3099 | const statsCacheKey = (key: string) => JSON.stringify([listingsEpoch, key]); |
| 3100 | const recentStats = new Map< |
| 3101 | string, |
| 3102 | { readonly at: number; readonly value: PullRequestDiffStat } |
| 3103 | >(); |
| 3104 | const recordStats = (key: string, value: PullRequestDiffStat, at: number) => { |
| 3105 | recentStats.delete(key); |
| 3106 | recentStats.set(key, { at, value }); |
| 3107 | if (recentStats.size > REF_EPOCH_CAPACITY) { |
| 3108 | const oldest = recentStats.keys().next().value; |
| 3109 | if (oldest !== undefined) recentStats.delete(oldest); |
| 3110 | } |
| 3111 | }; |
| 3112 | const bumpEpoch = (epochs: Map<string, number>, ref: PullRequestRef) => { |
| 3113 | const scope = refScope(ref); |
| 3114 | if (!epochs.has(scope) && epochs.size >= REF_EPOCH_CAPACITY) { |
| 3115 | const oldest = epochs.keys().next().value; |
| 3116 | if (oldest !== undefined) epochs.delete(oldest); |
| 3117 | } |
| 3118 | epochs.set(scope, ++epochCounter); |
| 3119 | }; |
| 3120 | const bumpRefEpoch = (ref: PullRequestRef) => bumpEpoch(refEpochs, ref); |
| 3121 | const filesViewedEpochs = new Map<string, number>(); |
| 3122 | const filesViewedEpoch = (ref: PullRequestRef) => filesViewedEpochs.get(refScope(ref)) ?? 0; |
| 3123 | const bumpFilesViewedEpoch = (ref: PullRequestRef) => bumpEpoch(filesViewedEpochs, ref); |
| 3124 | |
| 3125 | const fileRevisionEpochs = new Map<string, number>(); |
| 3126 | let everyFileRevisionEpoch = 0; |
| 3127 | const viewedFiles = ViewedFiles.make({ |
| 3128 | filesViewedStore, |
| 3129 | requireProject, |
| 3130 | requiredViewerOf, |
| 3131 | toPullRequestError, |
| 3132 | runFork, |
| 3133 | refEpoch, |
| 3134 | fileRevisionsEpoch: (ref) => |
| 3135 | `${everyFileRevisionEpoch}:${fileRevisionEpochs.get(refScope(ref)) ?? 0}`, |
| 3136 | }); |
| 3137 | |
| 3138 | const filtersOfKey = ( |
| 3139 | slots: ReadonlyArray< |
| 3140 | string | ReadonlyArray<string> | ReadonlyArray<ReadonlyArray<string>> | null |
| 3141 | >, |
| 3142 | ): PullRequestListFilters => { |
| 3143 | const [draft, review, checks, author, labels, excludedLabels] = slots; |
| 3144 | return { |
| 3145 | ...(typeof draft === "string" ? { draft: draft as "only" | "hide" } : {}), |
| 3146 | ...(typeof review === "string" ? { review: review as PullRequestListFilters["review"] } : {}), |
| 3147 | ...(typeof checks === "string" ? { checks: checks as PullRequestListFilters["checks"] } : {}), |
| 3148 | ...(typeof author === "string" ? { author } : {}), |
| 3149 | ...(Array.isArray(labels) ? { labels: labels as ReadonlyArray<ReadonlyArray<string>> } : {}), |
| 3150 | ...(Array.isArray(excludedLabels) ? { excludedLabels } : {}), |
| 3151 | }; |
| 3152 | }; |
| 3153 | |
| 3154 | const persistedRead = Effect.fn("PullRequestService.persistedRead")(function* <A>( |
| 3155 | input: CredentialRef, |
| 3156 | operation: string, |
| 3157 | codec: Schema.Codec<A, string>, |
| 3158 | read: Effect.Effect<A, PullRequestError>, |
| 3159 | ) { |
| 3160 | const project = yield* requireProject(input); |
| 3161 | const key = [ |
| 3162 | operation, |
| 3163 | project.api.kind, |
| 3164 | project.host.toLowerCase(), |
| 3165 | project.repository.toLowerCase(), |
| 3166 | project.project.id, |
| 3167 | project.project.workspaceRoot, |
| 3168 | String(input.number), |
| 3169 | input.expectedAccountId ?? "", |
| 3170 | input[credentialNamespace] ?? "", |
| 3171 | ] |
| 3172 | .map(encodeURIComponent) |
| 3173 | .join(":"); |
| 3174 | const lookup = yield* Effect.cached(read); |
| 3175 | const encodedRead = lookup.pipe( |
| 3176 | Effect.flatMap((value) => |
| 3177 | Schema.encodeEffect(codec)(value).pipe( |
| 3178 | Effect.mapError( |
| 3179 | (cause) => |
| 3180 | new PullRequestOperationError({ |
| 3181 | operation: "cache", |
| 3182 | detail: "Could not encode PR cache data.", |
| 3183 | cause, |
| 3184 | }), |
| 3185 | ), |
| 3186 | ), |
| 3187 | ), |
| 3188 | ); |
| 3189 | const payload = yield* readCache.get(key, encodedRead, [ |
| 3190 | `project:${input.projectId}`, |
| 3191 | refScope(input), |
| 3192 | ]); |
| 3193 | const decoded = yield* Schema.decodeEffect(codec)(payload).pipe(Effect.option); |
| 3194 | return Option.isSome(decoded) ? decoded.value : yield* lookup; |
| 3195 | }); |
| 3196 | const summaryCodec = Schema.fromJsonString(PullRequestSummary); |
| 3197 | const stackCodec = Schema.fromJsonString(Schema.NullOr(PullRequestStack)); |
| 3198 | |
| 3199 | const summary: PullRequestService["Service"]["summary"] = (input, options) => { |
| 3200 | const key = refCacheKey(input); |
| 3201 | const read = |
| 3202 | options?.bypassCache === true |
| 3203 | ? summaryUncached(input) |
| 3204 | : persistedRead(input, "summary", summaryCodec, summaryUncached(input)); |
| 3205 | const held = lastGoodSummary.peek(key); |
| 3206 | return options?.bypassCache !== true && |
| 3207 | held !== undefined && |
| 3208 | input.allowStale !== false && |
| 3209 | (options?.recoverTransientFailure !== false || held.state === "merged") |
| 3210 | ? Effect.succeed(held) |
| 3211 | : read.pipe( |
| 3212 | Effect.tap((value) => |
| 3213 | shouldReplaceHeldSummary(key, value) ? lastGoodSummary.record(key, value) : Effect.void, |
| 3214 | ), |
| 3215 | ); |
| 3216 | }; |
| 3217 | |
| 3218 | const batchesReads: PullRequestService["Service"]["batchesReads"] = Effect.fn( |
| 3219 | "PullRequestService.batchesReads", |
| 3220 | )( |
| 3221 | function* (input) { |
| 3222 | const project = yield* requireProject(input); |
| 3223 | return project.api.batchesReads === true; |
| 3224 | }, |
| 3225 | Effect.orElseSucceed(() => false), |
| 3226 | ); |
| 3227 | |
| 3228 | const stack: PullRequestService["Service"]["stack"] = (input, options) => |
| 3229 | options?.bypassCache === true |
| 3230 | ? stackUncached(input, options) |
| 3231 | : persistedRead( |
| 3232 | input, |
| 3233 | `stack:${options?.includeDetails !== false}`, |
| 3234 | stackCodec, |
| 3235 | stackUncached(input, options), |
| 3236 | ); |
| 3237 | |
| 3238 | const listCache = yield* Cache.makeWith( |
| 3239 | (key: string) => { |
| 3240 | const [ |
| 3241 | , |
| 3242 | state, |
| 3243 | involvement, |
| 3244 | filters, |
| 3245 | projectId, |
| 3246 | projectIds, |
| 3247 | host, |
| 3248 | limit, |
| 3249 | query, |
| 3250 | cursorEntries, |
| 3251 | ] = JSON.parse(key) as [ |
| 3252 | number, |
| 3253 | string, |
| 3254 | string | null, |
| 3255 | ReadonlyArray<string | ReadonlyArray<string> | null> | null, |
| 3256 | string | null, |
| 3257 | ReadonlyArray<string> | null, |
| 3258 | string | null, |
| 3259 | number | null, |
| 3260 | string | null, |
| 3261 | ReadonlyArray<[string, string]> | null, |
| 3262 | ]; |
| 3263 | return listUncached({ |
| 3264 | state, |
| 3265 | ...(involvement === null ? {} : { involvement }), |
| 3266 | ...(filters === null ? {} : { filters: filtersOfKey(filters) }), |
| 3267 | ...(projectId === null ? {} : { projectId }), |
| 3268 | ...(projectIds === null ? {} : { projectIds }), |
| 3269 | ...(host === null ? {} : { host }), |
| 3270 | ...(limit === null ? {} : { limit }), |
| 3271 | ...(query === null ? {} : { query }), |
| 3272 | ...(cursorEntries === null ? {} : { cursors: Object.fromEntries(cursorEntries) }), |
| 3273 | } as PullRequestListInput); |
| 3274 | }, |
| 3275 | { |
| 3276 | capacity: LIST_CACHE_CAPACITY, |
| 3277 | timeToLive: (exit) => (Exit.isSuccess(exit) ? LIST_CACHE_TTL : Duration.zero), |
| 3278 | }, |
| 3279 | ); |
| 3280 | const list: PullRequestService["Service"]["list"] = (input) => { |
| 3281 | const key = JSON.stringify([ |
| 3282 | listingsEpoch, |
| 3283 | input.state, |
| 3284 | input.involvement ?? null, |
| 3285 | input.filters === undefined |
| 3286 | ? null |
| 3287 | : [ |
| 3288 | input.filters.draft ?? null, |
| 3289 | input.filters.review ?? null, |
| 3290 | input.filters.checks ?? null, |
| 3291 | input.filters.author ?? null, |
| 3292 | input.filters.labels ?? null, |
| 3293 | input.filters.excludedLabels ?? null, |
| 3294 | ], |
| 3295 | input.projectId ?? null, |
| 3296 | input.projectIds === undefined ? null : [...input.projectIds].sort(), |
| 3297 | input.host ?? null, |
| 3298 | input.limit ?? null, |
| 3299 | input.query ?? null, |
| 3300 | input.cursors === undefined |
| 3301 | ? null |
| 3302 | : Object.entries(input.cursors).toSorted(([left], [right]) => left.localeCompare(right)), |
| 3303 | ]); |
| 3304 | // A replacement reader can join a lookup still finishing its previous reader's cancellation. |
| 3305 | return Cache.get(listCache, key).pipe( |
| 3306 | Effect.catchCauseIf( |
| 3307 | (cause) => Cause.hasInterruptsOnly(cause), |
| 3308 | (_cause) => Cache.get(listCache, key), |
| 3309 | ), |
| 3310 | ); |
| 3311 | }; |
| 3312 | |
| 3313 | const checksCache = yield* Cache.makeWith( |
| 3314 | (key: string) => { |
| 3315 | const input = refOfCacheKey(key); |
| 3316 | return requireProject(input).pipe( |
| 3317 | Effect.flatMap((project) => |
| 3318 | project.api.getChangeRequestChecks === undefined |
| 3319 | ? Effect.succeed(null) |
| 3320 | : project.api |
| 3321 | .getChangeRequestChecks({ |
| 3322 | cwd: project.project.workspaceRoot, |
| 3323 | repository: project.repository, |
| 3324 | host: project.host, |
| 3325 | number: input.number, |
| 3326 | }) |
| 3327 | .pipe( |
| 3328 | Effect.mapError(toPullRequestError("checks")), |
| 3329 | observeRead, |
| 3330 | Effect.map(({ value, observedAt }) => ({ ...value, observedAt })), |
| 3331 | ), |
| 3332 | ), |
| 3333 | ); |
| 3334 | }, |
| 3335 | { |
| 3336 | capacity: DETAIL_CACHE_CAPACITY, |
| 3337 | // Expire from the read's start so checks seeded from a slow detail read keep their age. |
| 3338 | timeToLive: (exit) => |
| 3339 | !Exit.isSuccess(exit) |
| 3340 | ? Duration.zero |
| 3341 | : exit.value === null |
| 3342 | ? CHECKS_CACHE_TTL |
| 3343 | : Duration.millis( |
| 3344 | Math.max( |
| 3345 | 0, |
| 3346 | exit.value.observedAt + |
| 3347 | Duration.toMillis(CHECKS_CACHE_TTL) - |
| 3348 | clock.currentTimeMillisUnsafe(), |
| 3349 | ), |
| 3350 | ), |
| 3351 | }, |
| 3352 | ); |
| 3353 | |
| 3354 | const watchFingerprintCache = yield* Cache.makeWith( |
| 3355 | (key: string) => { |
| 3356 | const input = refOfCacheKey(key); |
| 3357 | return requireProject(input).pipe( |
| 3358 | Effect.flatMap((project) => |
| 3359 | project.api.getChangeRequestWatchFingerprint === undefined |
| 3360 | ? Effect.succeed(null) |
| 3361 | : project.api |
| 3362 | .getChangeRequestWatchFingerprint({ |
| 3363 | cwd: project.project.workspaceRoot, |
| 3364 | repository: project.repository, |
| 3365 | host: project.host, |
| 3366 | number: input.number, |
| 3367 | }) |
| 3368 | .pipe(Effect.mapError(toPullRequestError("watchFingerprint"))), |
| 3369 | ), |
| 3370 | ); |
| 3371 | }, |
| 3372 | { |
| 3373 | capacity: DETAIL_CACHE_CAPACITY, |
| 3374 | timeToLive: (exit) => (Exit.isSuccess(exit) ? CHECKS_CACHE_TTL : Duration.zero), |
| 3375 | }, |
| 3376 | ); |
| 3377 | |
| 3378 | const detailCache = yield* Cache.makeWith( |
| 3379 | (key: string) => { |
| 3380 | const statsKey = statsCacheKey(key); |
| 3381 | return detailUncached(refOfCacheKey(key)).pipe( |
| 3382 | Effect.tap( |
| 3383 | Effect.fn("PullRequestService.recordDetailStats")(function* (value: PullRequestDetail) { |
| 3384 | // GitHub and Azure detail include the same checks; the checks TTL counts from their observation. |
| 3385 | // Azure detail answers a failed policy read with no checks, which must not be cached. |
| 3386 | if ( |
| 3387 | (value.provider === "github" || |
| 3388 | (value.provider === "azure-devops" && value.checks.length > 0)) && |
| 3389 | value.observedAt !== undefined && |
| 3390 | !(yield* Cache.has(checksCache, key)) |
| 3391 | ) { |
| 3392 | yield* Cache.set(checksCache, key, { |
| 3393 | state: value.state, |
| 3394 | checks: value.checks, |
| 3395 | observedAt: value.observedAt, |
| 3396 | }); |
| 3397 | } |
| 3398 | recordStats( |
| 3399 | statsKey, |
| 3400 | { |
| 3401 | projectId: value.projectId, |
| 3402 | repository: value.repository, |
| 3403 | number: value.number, |
| 3404 | additions: value.additions, |
| 3405 | deletions: value.deletions, |
| 3406 | }, |
| 3407 | yield* Clock.currentTimeMillis, |
| 3408 | ); |
| 3409 | }), |
| 3410 | ), |
| 3411 | ); |
| 3412 | }, |
| 3413 | { |
| 3414 | capacity: DETAIL_CACHE_CAPACITY, |
| 3415 | timeToLive: (exit) => |
| 3416 | Exit.isSuccess(exit) ? detailTimeToLive(exit.value.state) : Duration.zero, |
| 3417 | }, |
| 3418 | ); |
| 3419 | const summaryFromDetail = ( |
| 3420 | detail: PullRequestDetail, |
| 3421 | previous: PullRequestSummary | undefined, |
| 3422 | ): PullRequestSummary => ({ |
| 3423 | // Detail does not carry review/check summaries. Keep the last summary observation. |
| 3424 | ...previous, |
| 3425 | provider: detail.provider, |
| 3426 | projectId: detail.projectId, |
| 3427 | repository: detail.repository, |
| 3428 | number: detail.number, |
| 3429 | title: detail.title, |
| 3430 | url: detail.url, |
| 3431 | state: detail.state, |
| 3432 | isDraft: detail.isDraft, |
| 3433 | author: detail.author, |
| 3434 | additions: detail.additions, |
| 3435 | deletions: detail.deletions, |
| 3436 | changedFiles: detail.changedFiles, |
| 3437 | mergeability: detail.mergeability, |
| 3438 | ...(detail.rebaseRequired === undefined ? {} : { rebaseRequired: detail.rebaseRequired }), |
| 3439 | headBranch: detail.headBranch, |
| 3440 | baseBranch: detail.baseBranch, |
| 3441 | closedAt: detail.closedAt, |
| 3442 | mergedAt: detail.mergedAt, |
| 3443 | updatedAt: detail.updatedAt, |
| 3444 | observedAt: detail.observedAt, |
| 3445 | }); |
| 3446 | const shouldReplaceHeldSummary = (key: string, next: PullRequestSummary) => |
| 3447 | supersedesReading(lastGoodSummary.peek(key), next); |
| 3448 | // Keep newest detail states across epochs/credentials; summary reads would mask subsequent detail changes. |
| 3449 | const detailStates = new Map<string, PullRequestReading>(); |
| 3450 | const noteDetailReading = (ref: PullRequestRef, next: PullRequestSummary) => |
| 3451 | Effect.suspend(() => { |
| 3452 | const scope = refScope(ref); |
| 3453 | const current = detailStates.get(scope); |
| 3454 | if (!supersedesReading(current, next)) return Effect.void; |
| 3455 | detailStates.delete(scope); |
| 3456 | if (detailStates.size >= REF_EPOCH_CAPACITY) { |
| 3457 | const oldest = detailStates.keys().next().value; |
| 3458 | if (oldest !== undefined) detailStates.delete(oldest); |
| 3459 | } |
| 3460 | detailStates.set(scope, { |
| 3461 | state: next.state, |
| 3462 | isDraft: next.isDraft, |
| 3463 | updatedAt: next.updatedAt, |
| 3464 | observedAt: next.observedAt, |
| 3465 | }); |
| 3466 | return (current?.state !== next.state || current?.isDraft !== next.isDraft) && |
| 3467 | ref.host !== undefined |
| 3468 | ? PubSub.publish(stateChanges, { |
| 3469 | host: ref.host, |
| 3470 | repository: ref.repository, |
| 3471 | number: ref.number, |
| 3472 | }) |
| 3473 | : Effect.void; |
| 3474 | }); |
| 3475 | // Keep routed reports separate; unverified reports must not outrank this environment's reads. |
| 3476 | const reportedStates = new Map< |
| 3477 | string, |
| 3478 | { |
| 3479 | readonly state: PullRequestState; |
| 3480 | readonly isDraft: boolean | undefined; |
| 3481 | readonly atMs: number; |
| 3482 | } |
| 3483 | >(); |
| 3484 | const reportState: PullRequestService["Service"]["reportState"] = ({ |
| 3485 | reference, |
| 3486 | state, |
| 3487 | isDraft, |
| 3488 | }) => |
| 3489 | Effect.all([canonicalRef(reference), Clock.currentTimeMillis]).pipe( |
| 3490 | Effect.flatMap(([ref, nowMs]) => |
| 3491 | Effect.suspend(() => { |
| 3492 | const scope = refScope(ref); |
| 3493 | const reported = reportedStates.get(scope); |
| 3494 | if ( |
| 3495 | reported?.state === state && |
| 3496 | reported.isDraft === isDraft && |
| 3497 | nowMs - reported.atMs < REPORTED_STATE_DEDUPE_MS |
| 3498 | ) |
| 3499 | return Effect.void; |
| 3500 | reportedStates.delete(scope); |
| 3501 | if (reportedStates.size >= REF_EPOCH_CAPACITY) { |
| 3502 | const oldest = reportedStates.keys().next().value; |
| 3503 | if (oldest !== undefined) reportedStates.delete(oldest); |
| 3504 | } |
| 3505 | reportedStates.set(scope, { state, isDraft, atMs: nowMs }); |
| 3506 | return ref.host === undefined |
| 3507 | ? Effect.void |
| 3508 | : PubSub.publish(stateChanges, { |
| 3509 | host: ref.host, |
| 3510 | repository: ref.repository, |
| 3511 | number: ref.number, |
| 3512 | }); |
| 3513 | }), |
| 3514 | ), |
| 3515 | ); |
| 3516 | const detail: PullRequestService["Service"]["detail"] = (input) => { |
| 3517 | const key = refCacheKey(input); |
| 3518 | // Skip reads older than strict summaries; caching them would preserve regressions without asking the host again. |
| 3519 | const read = Cache.get(detailCache, key).pipe( |
| 3520 | Effect.tap((value) => { |
| 3521 | if (value.state === "merged") noteMerged(input); |
| 3522 | const summary = summaryFromDetail(value, lastGoodSummary.peek(key)); |
| 3523 | return noteDetailReading(input, summary).pipe( |
| 3524 | Effect.andThen( |
| 3525 | shouldReplaceHeldSummary(key, summary) |
| 3526 | ? lastGoodSummary.record(key, summary) |
| 3527 | : Effect.void, |
| 3528 | ), |
| 3529 | ); |
| 3530 | }), |
| 3531 | ); |
| 3532 | return input.allowStale === false |
| 3533 | ? read.pipe(Effect.tap((value) => lastGoodDetail.record(key, value))) |
| 3534 | : lastGoodDetail.serveHeld(key, read); |
| 3535 | }; |
| 3536 | |
| 3537 | const activityCache = yield* Cache.makeWith( |
| 3538 | (key: string) => { |
| 3539 | return activityUncached(refOfCacheKey(key)); |
| 3540 | }, |
| 3541 | { |
| 3542 | capacity: DETAIL_CACHE_CAPACITY, |
| 3543 | timeToLive: (exit, key) => |
| 3544 | Exit.isSuccess(exit) ? detailTimeToLive(lastGoodSummary.peek(key)?.state) : Duration.zero, |
| 3545 | }, |
| 3546 | ); |
| 3547 | |
| 3548 | const changeBreakdownCache = yield* Cache.makeWith( |
| 3549 | (key: string) => { |
| 3550 | const ref = refOfCacheKey(key); |
| 3551 | return requireProject(ref).pipe( |
| 3552 | Effect.flatMap((project) => { |
| 3553 | const read = project.api.getFileStats; |
| 3554 | if (read === undefined) return Effect.succeed(null); |
| 3555 | return read({ |
| 3556 | cwd: project.project.workspaceRoot, |
| 3557 | repository: project.repository, |
| 3558 | host: project.host, |
| 3559 | number: ref.number, |
| 3560 | }).pipe( |
| 3561 | Effect.map(toChangeBreakdown), |
| 3562 | Effect.mapError(toPullRequestError("changeBreakdown")), |
| 3563 | ); |
| 3564 | }), |
| 3565 | ); |
| 3566 | }, |
| 3567 | { |
| 3568 | capacity: DETAIL_CACHE_CAPACITY, |
| 3569 | timeToLive: (exit, key) => |
| 3570 | Exit.isSuccess(exit) ? detailTimeToLive(lastGoodSummary.peek(key)?.state) : Duration.zero, |
| 3571 | }, |
| 3572 | ); |
| 3573 | |
| 3574 | const previewCache = yield* Cache.makeWith( |
| 3575 | (key: string) => { |
| 3576 | return previewUncached(refOfCacheKey(key)); |
| 3577 | }, |
| 3578 | { |
| 3579 | capacity: DETAIL_CACHE_CAPACITY, |
| 3580 | timeToLive: (exit) => |
| 3581 | Exit.isSuccess(exit) ? detailTimeToLive(exit.value.state) : Duration.zero, |
| 3582 | }, |
| 3583 | ); |
| 3584 | const preview: PullRequestService["Service"]["preview"] = (input) => { |
| 3585 | const key = refCacheKey(input); |
| 3586 | return Cache.getSuccess(detailCache, key).pipe( |
| 3587 | Effect.flatMap( |
| 3588 | Option.match({ |
| 3589 | onNone: () => Cache.get(previewCache, key), |
| 3590 | onSome: (detail) => Effect.succeed(previewFields(detail)), |
| 3591 | }), |
| 3592 | ), |
| 3593 | ); |
| 3594 | }; |
| 3595 | const activity: PullRequestService["Service"]["activity"] = (input) => { |
| 3596 | const key = refCacheKey(input); |
| 3597 | return Cache.get(activityCache, key); |
| 3598 | }; |
| 3599 | |
| 3600 | const diffCache = yield* Cache.makeWith( |
| 3601 | (key: string) => { |
| 3602 | const [reference, cursor, commit, , path] = JSON.parse(key) as [ |
| 3603 | string, |
| 3604 | string | null, |
| 3605 | string | null, |
| 3606 | string | null, |
| 3607 | string | null, |
| 3608 | ]; |
| 3609 | return diffUncached({ |
| 3610 | ...refOfCacheKey(reference), |
| 3611 | ...(path === null ? {} : { path }), |
| 3612 | ...(cursor === null ? {} : { cursor }), |
| 3613 | ...(commit === null ? {} : { commit }), |
| 3614 | } as PullRequestDiffInput).pipe( |
| 3615 | observeRead, |
| 3616 | Effect.tap(({ value, observedAt }) => { |
| 3617 | // Keep the loader's epoch and read time if a refresh occurs during the provider read. |
| 3618 | // One withheld file is not the page's file list. |
| 3619 | if (path === null) { |
| 3620 | diffFiles.record(JSON.stringify([reference, cursor, commit]), value, observedAt); |
| 3621 | } |
| 3622 | return Effect.void; |
| 3623 | }), |
| 3624 | ); |
| 3625 | }, |
| 3626 | { |
| 3627 | capacity: DIFF_CACHE_CAPACITY, |
| 3628 | timeToLive: (exit, key) => { |
| 3629 | if (!Exit.isSuccess(exit)) return Duration.zero; |
| 3630 | const commit = (JSON.parse(key) as ReadonlyArray<unknown>)[2]; |
| 3631 | const ttl = Duration.toMillis(commit === null ? DIFF_CACHE_TTL : COMMIT_DIFF_CACHE_TTL); |
| 3632 | return Duration.millis( |
| 3633 | Math.max(0, exit.value.observedAt + ttl - clock.currentTimeMillisUnsafe()), |
| 3634 | ); |
| 3635 | }, |
| 3636 | }, |
| 3637 | ); |
| 3638 | // Diffs expire only when their keys are reread; push-dependent keys leave closed pages' patches retained. |
| 3639 | let diffSweepPending = false; |
| 3640 | // Fork in service context atomically with the flag to avoid stranded flags and retained caller requests. |
| 3641 | const armDiffSweep = () => { |
| 3642 | if (diffSweepPending) return; |
| 3643 | diffSweepPending = true; |
| 3644 | runFork(Effect.forkIn(sweepDiffs, scope)); |
| 3645 | }; |
| 3646 | const sweepDiffs: Effect.Effect<void> = Effect.sleep(DIFF_SWEEP_INTERVAL).pipe( |
| 3647 | Effect.andThen( |
| 3648 | Effect.suspend(() => { |
| 3649 | diffSweepPending = false; |
| 3650 | return staleDiff.dropExpired; |
| 3651 | }), |
| 3652 | ), |
| 3653 | Effect.flatMap((stale) => |
| 3654 | Effect.map(Cache.keys(diffCache), (keys) => stale + Array.from(keys).length), |
| 3655 | ), |
| 3656 | Effect.map((held) => { |
| 3657 | if (held > 0) armDiffSweep(); |
| 3658 | }), |
| 3659 | ); |
| 3660 | const readDiff = (input: PullRequestDiffInput) => { |
| 3661 | const key = JSON.stringify([ |
| 3662 | refCacheKey(input), |
| 3663 | input.cursor ?? null, |
| 3664 | input.commit ?? null, |
| 3665 | input.commit === undefined |
| 3666 | ? (lastGoodSummary.peek(refCacheKey(input))?.updatedAt ?? null) |
| 3667 | : null, |
| 3668 | input.path ?? null, |
| 3669 | ]); |
| 3670 | const evictDiffs = Cache.entries(diffCache).pipe( |
| 3671 | Effect.flatMap((entries) => |
| 3672 | Effect.forEach( |
| 3673 | diffCacheEvictions(Array.from(entries, ([key, read]) => [key, read.value] as const)), |
| 3674 | (evicted) => Cache.invalidate(diffCache, evicted), |
| 3675 | ), |
| 3676 | ), |
| 3677 | Effect.uninterruptible, |
| 3678 | ); |
| 3679 | const read = Cache.get(diffCache, key).pipe( |
| 3680 | Effect.ensuring(evictDiffs), |
| 3681 | Effect.ensuring(Effect.sync(armDiffSweep)), |
| 3682 | ); |
| 3683 | return { key, read }; |
| 3684 | }; |
| 3685 | const diff: PullRequestService["Service"]["diff"] = (input) => { |
| 3686 | const { key, read } = readDiff(input); |
| 3687 | return staleDiff.serve(key, read.pipe(Effect.map((read) => read.value))); |
| 3688 | }; |
| 3689 | |
| 3690 | const filesViewedCache = yield* Cache.makeWith( |
| 3691 | (key: string) => { |
| 3692 | const [referenceKey] = JSON.parse(key) as [string, number]; |
| 3693 | return viewedFiles.filesViewed(refOfCacheKey(referenceKey)); |
| 3694 | }, |
| 3695 | { |
| 3696 | capacity: FILES_VIEWED_CACHE_CAPACITY, |
| 3697 | timeToLive: (exit) => (Exit.isSuccess(exit) ? FILES_VIEWED_CACHE_TTL : Duration.zero), |
| 3698 | }, |
| 3699 | ); |
| 3700 | // Key canonical refs to match epochs bumped with the remote's spelling. |
| 3701 | const filesViewed: PullRequestService["Service"]["filesViewed"] = (input) => |
| 3702 | canonicalRef(input).pipe( |
| 3703 | Effect.flatMap((ref) => |
| 3704 | Cache.get(filesViewedCache, JSON.stringify([refCacheKey(ref), filesViewedEpoch(ref)])), |
| 3705 | ), |
| 3706 | ); |
| 3707 | |
| 3708 | const listStatsCache = yield* Cache.makeWith( |
| 3709 | (key: string) => { |
| 3710 | const [, refs] = JSON.parse(key) as [number, ReadonlyArray<[string, string, number, number]>]; |
| 3711 | return listStatsUncached({ |
| 3712 | refs: refs.map(([projectId, repository, number]) => ({ projectId, repository, number })), |
| 3713 | } as unknown as PullRequestListStatsInput).pipe( |
| 3714 | Effect.flatMap((result) => |
| 3715 | Clock.currentTimeMillis.pipe(Effect.map((at) => ({ result, at }))), |
| 3716 | ), |
| 3717 | ); |
| 3718 | }, |
| 3719 | { |
| 3720 | capacity: LIST_STATS_CACHE_CAPACITY, |
| 3721 | timeToLive: (exit) => (Exit.isSuccess(exit) ? LIST_STATS_CACHE_TTL : Duration.zero), |
| 3722 | }, |
| 3723 | ); |
| 3724 | const statsBatchKey = (refs: Iterable<PullRequestRef>) => |
| 3725 | JSON.stringify([ |
| 3726 | listingsEpoch, |
| 3727 | [...refs] |
| 3728 | .map((ref) => [ref.projectId, ref.repository, ref.number, refEpoch(ref)] as const) |
| 3729 | .toSorted((left, right) => |
| 3730 | `${left[0]} ${left[1]} ${left[2]}`.localeCompare(`${right[0]} ${right[1]} ${right[2]}`), |
| 3731 | ), |
| 3732 | ]); |
| 3733 | const listStats: PullRequestService["Service"]["listStats"] = Effect.fn( |
| 3734 | "PullRequestService.listStats", |
| 3735 | )(function* (input: PullRequestListStatsInput) { |
| 3736 | if (input.refs.length === 0) return { stats: [] }; |
| 3737 | const now = yield* Clock.currentTimeMillis; |
| 3738 | const held: PullRequestDiffStat[] = []; |
| 3739 | const missing = new Map<string, PullRequestRef>(); |
| 3740 | for (const ref of input.refs) { |
| 3741 | const key = statsCacheKey(refCacheKey(ref)); |
| 3742 | const cached = recentStats.get(key); |
| 3743 | if (cached !== undefined && now - cached.at < Duration.toMillis(LIST_STATS_CACHE_TTL)) { |
| 3744 | held.push(cached.value); |
| 3745 | } else { |
| 3746 | missing.set(key, ref); |
| 3747 | } |
| 3748 | } |
| 3749 | if (missing.size === 0) return { stats: held }; |
| 3750 | const key = statsBatchKey(missing.values()); |
| 3751 | const { result, at } = yield* Cache.get(listStatsCache, key).pipe( |
| 3752 | Effect.catchCauseIf( |
| 3753 | (cause) => Cause.hasInterruptsOnly(cause), |
| 3754 | (_cause) => Cache.get(listStatsCache, key), |
| 3755 | ), |
| 3756 | ); |
| 3757 | for (const [key, ref] of missing) { |
| 3758 | const stat = result.stats.find( |
| 3759 | (stat) => |
| 3760 | stat.projectId === ref.projectId && |
| 3761 | stat.repository.toLowerCase() === ref.repository.toLowerCase() && |
| 3762 | stat.number === ref.number, |
| 3763 | ); |
| 3764 | if (stat !== undefined) recordStats(key, stat, at); |
| 3765 | } |
| 3766 | return { stats: [...held, ...result.stats] }; |
| 3767 | }); |
| 3768 | |
| 3769 | const forgetProviderReads = (scope?: { readonly repository: string; readonly number?: number }) => |
| 3770 | Effect.forEach( |
| 3771 | registry.kinds, |
| 3772 | (kind) => registry.get(kind)?.forgetChangeRequestReads?.(scope) ?? Effect.void, |
| 3773 | { discard: true }, |
| 3774 | ); |
| 3775 | |
| 3776 | const invalidate: PullRequestService["Service"]["invalidate"] = Effect.fn( |
| 3777 | "PullRequestService.invalidate", |
| 3778 | )(function* (input, options) { |
| 3779 | const reference = input.reference; |
| 3780 | if (input.filesViewedOnly === true) { |
| 3781 | return yield* reference === undefined |
| 3782 | ? Cache.invalidateAll(filesViewedCache) |
| 3783 | : canonicalRef(reference).pipe( |
| 3784 | Effect.flatMap((ref) => Effect.sync(() => bumpFilesViewedEpoch(ref))), |
| 3785 | Effect.ignore, |
| 3786 | ); |
| 3787 | } |
| 3788 | if (reference !== undefined) { |
| 3789 | yield* canonicalRef(reference).pipe( |
| 3790 | Effect.flatMap((ref) => |
| 3791 | forgetProviderReads({ repository: ref.repository, number: ref.number }).pipe( |
| 3792 | Effect.andThen(readCache.invalidate(refScope(ref))), |
| 3793 | Effect.andThen(Effect.sync(() => bumpRefEpoch(ref))), |
| 3794 | ), |
| 3795 | ), |
| 3796 | Effect.ignore, |
| 3797 | ); |
| 3798 | } else { |
| 3799 | yield* forgetProviderReads(); |
| 3800 | listingsEpoch = ++epochCounter; |
| 3801 | everyFileRevisionEpoch = ++epochCounter; |
| 3802 | viewersByHost.clear(); |
| 3803 | yield* Cache.invalidateAll(viewerFlights); |
| 3804 | } |
| 3805 | if (options?.notifyReaders) { |
| 3806 | yield* SubscriptionRef.set(pullRequestRefreshes, ++epochCounter); |
| 3807 | } |
| 3808 | }); |
| 3809 | |
| 3810 | const refreshAfterTurn: PullRequestService["Service"]["refreshAfterTurn"] = Effect.fn( |
| 3811 | "PullRequestService.refreshAfterTurn", |
| 3812 | )(function* (projectId, options) { |
| 3813 | // Everything the provider holds, not just the project's repository: a turn can touch a |
| 3814 | // change request reached through another repository, and no epoch may move until those |
| 3815 | // reads are gone, or a reader in between keeps the old one under the new epoch. |
| 3816 | yield* forgetProviderReads(); |
| 3817 | const epoch = ++epochCounter; |
| 3818 | // A push can open or move a PR; a plain turn waits for the listing TTL to spare the API quota. |
| 3819 | if (options?.pushed === true) listingsEpoch = epoch; |
| 3820 | projectEpochs.delete(projectId); |
| 3821 | if (projectEpochs.size >= REF_EPOCH_CAPACITY) { |
| 3822 | const oldest = projectEpochs.keys().next().value; |
| 3823 | if (oldest !== undefined) { |
| 3824 | projectEpochFloor = projectEpochs.get(oldest)!; |
| 3825 | projectEpochs.delete(oldest); |
| 3826 | } |
| 3827 | } |
| 3828 | projectEpochs.set(projectId, epoch); |
| 3829 | yield* readCache.invalidate(`project:${projectId}`); |
| 3830 | yield* SubscriptionRef.set(pullRequestRefreshes, epoch); |
| 3831 | }); |
| 3832 | |
| 3833 | const notifyLinkedThreadsChanged = SubscriptionRef.update( |
| 3834 | linkedThreadRefreshes, |
| 3835 | (revision) => revision + 1, |
| 3836 | ); |
| 3837 | |
| 3838 | const invalidatedByMutation = |
| 3839 | <I extends PullRequestRef>( |
| 3840 | method: (input: I) => Effect.Effect<void, PullRequestError>, |
| 3841 | ): ((input: I) => Effect.Effect<void, PullRequestError>) => |
| 3842 | (input) => |
| 3843 | Effect.gen(function* () { |
| 3844 | const ref = yield* canonicalRef(input); |
| 3845 | yield* readCache.invalidate(refScope(ref)).pipe( |
| 3846 | Effect.andThen(method(input)), |
| 3847 | Effect.ensuring(readCache.invalidate(refScope(ref))), |
| 3848 | Effect.tap(() => |
| 3849 | Effect.sync(() => { |
| 3850 | bumpRefEpoch(ref); |
| 3851 | listingsEpoch = ++epochCounter; |
| 3852 | }), |
| 3853 | ), |
| 3854 | ); |
| 3855 | yield* SubscriptionRef.set(pullRequestRefreshes, listingsEpoch); |
| 3856 | }); |
| 3857 | const selectChecks = Effect.fn("PullRequestService.selectChecks")(function* ( |
| 3858 | project: SupportedProject, |
| 3859 | input: PullRequestRef & { readonly check?: string }, |
| 3860 | operation: string, |
| 3861 | ) { |
| 3862 | const ref = { |
| 3863 | cwd: project.project.workspaceRoot, |
| 3864 | repository: project.repository, |
| 3865 | host: project.host, |
| 3866 | number: input.number, |
| 3867 | }; |
| 3868 | const { checks } = yield* ( |
| 3869 | project.api.getChangeRequestChecks === undefined |
| 3870 | ? project.api.getChangeRequest(ref) |
| 3871 | : project.api.getChangeRequestChecks(ref) |
| 3872 | ).pipe(Effect.mapError(toPullRequestError(operation))); |
| 3873 | const named = input.check?.trim().toLowerCase(); |
| 3874 | if (named === undefined) { |
| 3875 | return checks |
| 3876 | .filter((check) => check.status === "failure" || check.status === "cancelled") |
| 3877 | .map(({ name, url }) => ({ name, url })); |
| 3878 | } |
| 3879 | const matches = checks.filter((check) => check.name.toLowerCase() === named); |
| 3880 | if (matches.length === 0) { |
| 3881 | return yield* new PullRequestOperationError({ |
| 3882 | operation, |
| 3883 | detail: `No check is named ${input.check}. Checks: ${checks.map((check) => check.name).join(", ") || "none"}.`, |
| 3884 | }); |
| 3885 | } |
| 3886 | return matches.map(({ name, url }) => ({ name, url })); |
| 3887 | }); |
| 3888 | |
| 3889 | const DEFAULT_CHECK_LOGS = 5; |
| 3890 | const checkLogs: PullRequestService["Service"]["checkLogs"] = Effect.fn( |
| 3891 | "PullRequestService.checkLogs", |
| 3892 | )(function* (input) { |
| 3893 | const project = yield* requireProject(input); |
| 3894 | const read = project.api.getCheckLogs; |
| 3895 | if (read === undefined) { |
| 3896 | return yield* new PullRequestOperationError({ |
| 3897 | operation: "checkLogs", |
| 3898 | detail: "This host cannot read check logs.", |
| 3899 | }); |
| 3900 | } |
| 3901 | const checks = yield* selectChecks(project, input, "checkLogs"); |
| 3902 | if (checks.length === 0) return []; |
| 3903 | // Many failing checks would flood the agent's context; the rest stay a name away. |
| 3904 | const [shown, rest] = |
| 3905 | input.check === undefined |
| 3906 | ? [checks.slice(0, DEFAULT_CHECK_LOGS), checks.slice(DEFAULT_CHECK_LOGS)] |
| 3907 | : [checks, []]; |
| 3908 | const logs = yield* read({ |
| 3909 | cwd: project.project.workspaceRoot, |
| 3910 | repository: project.repository, |
| 3911 | host: project.host, |
| 3912 | checks: shown, |
| 3913 | tailLines: input.tailLines, |
| 3914 | }).pipe(Effect.mapError(toPullRequestError("checkLogs"))); |
| 3915 | return [ |
| 3916 | ...logs, |
| 3917 | ...rest.map((check) => ({ |
| 3918 | ...check, |
| 3919 | log: null, |
| 3920 | truncated: false, |
| 3921 | detail: "Not read, to keep the reply short. Ask for this check by name.", |
| 3922 | })), |
| 3923 | ]; |
| 3924 | }); |
| 3925 | |
| 3926 | const rerunChecks: PullRequestService["Service"]["rerunChecks"] = Effect.fn( |
| 3927 | "PullRequestService.rerunChecks", |
| 3928 | )(function* (input) { |
| 3929 | const project = yield* requireProject(input); |
| 3930 | const rerun = project.api.rerunChecks; |
| 3931 | if (rerun === undefined) { |
| 3932 | return yield* new PullRequestOperationError({ |
| 3933 | operation: "rerunChecks", |
| 3934 | detail: "This host cannot re-run checks.", |
| 3935 | }); |
| 3936 | } |
| 3937 | const checks = yield* selectChecks(project, input, "rerunChecks"); |
| 3938 | if (checks.length === 0) return []; |
| 3939 | const ref = yield* canonicalRef(input); |
| 3940 | // A failure can follow a run that already restarted, so readers refresh either way. |
| 3941 | return yield* rerun({ |
| 3942 | cwd: project.project.workspaceRoot, |
| 3943 | repository: project.repository, |
| 3944 | host: project.host, |
| 3945 | checks, |
| 3946 | }).pipe( |
| 3947 | Effect.mapError(toPullRequestError("rerunChecks")), |
| 3948 | Effect.ensuring( |
| 3949 | readCache.invalidate(refScope(ref)).pipe( |
| 3950 | Effect.andThen( |
| 3951 | Effect.suspend(() => { |
| 3952 | bumpRefEpoch(ref); |
| 3953 | listingsEpoch = ++epochCounter; |
| 3954 | return SubscriptionRef.set(pullRequestRefreshes, listingsEpoch); |
| 3955 | }), |
| 3956 | ), |
| 3957 | ), |
| 3958 | ), |
| 3959 | ); |
| 3960 | }); |
| 3961 | |
| 3962 | const runActionAndInvalidate: PullRequestService["Service"]["runAction"] = Effect.fn( |
| 3963 | "PullRequestService.runActionAndInvalidate", |
| 3964 | )(function* (input) { |
| 3965 | const ref = yield* canonicalRef(input); |
| 3966 | yield* readCache.invalidate(refScope(ref)); |
| 3967 | const { repository, summary } = yield* runAction(input).pipe( |
| 3968 | Effect.ensuring(readCache.invalidate(refScope(ref))), |
| 3969 | ); |
| 3970 | bumpRefEpoch({ ...ref, repository }); |
| 3971 | listingsEpoch = ++epochCounter; |
| 3972 | yield* SubscriptionRef.set(pullRequestRefreshes, listingsEpoch); |
| 3973 | if (input.action === "merge") { |
| 3974 | // A successful merge action can merely enqueue the PR or enable auto-merge. |
| 3975 | const merged = summary?.state === "merged" ? summary : null; |
| 3976 | const confirmed = |
| 3977 | merged?.mergedAt != null |
| 3978 | ? merged |
| 3979 | : yield* summaryUncached({ ...input, repository }).pipe( |
| 3980 | Effect.map((reread) => (reread.state === "merged" ? reread : merged)), |
| 3981 | Effect.catch((error) => |
| 3982 | Effect.logWarning("failed to confirm pull request merge", { error }).pipe( |
| 3983 | Effect.as(merged), |
| 3984 | ), |
| 3985 | ), |
| 3986 | ); |
| 3987 | if (confirmed?.state === "merged") { |
| 3988 | yield* PubSub.publish(mergedPullRequests, { |
| 3989 | projectId: input.projectId, |
| 3990 | repository, |
| 3991 | number: input.number, |
| 3992 | mergedAt: confirmed.mergedAt ?? DateTime.formatIso(yield* DateTime.now), |
| 3993 | }); |
| 3994 | } |
| 3995 | } |
| 3996 | return input.replyWithSummary === true ? summary : undefined; |
| 3997 | }); |
| 3998 | |
| 3999 | const credentialCached = |
| 4000 | <I extends PullRequestRef, Args extends ReadonlyArray<unknown>, A, E>( |
| 4001 | read: (input: I, ...args: Args) => Effect.Effect<A, E>, |
| 4002 | ) => |
| 4003 | (input: I, ...args: Args) => |
| 4004 | Effect.gen(function* () { |
| 4005 | const ref = yield* canonicalRef(input); |
| 4006 | const credential = yield* routingCredential; |
| 4007 | return yield* read( |
| 4008 | credential === null |
| 4009 | ? ref |
| 4010 | : { ...ref, [credentialNamespace]: credential.credentialFingerprint }, |
| 4011 | ...args, |
| 4012 | ); |
| 4013 | }); |
| 4014 | |
| 4015 | // Cache small filename lists even when patches exceed limits, avoiding diff refetches on file expansion. |
| 4016 | const diffFiles = (() => { |
| 4017 | const held = new Map< |
| 4018 | string, |
| 4019 | { |
| 4020 | readonly at: number; |
| 4021 | readonly files: ReadonlySet<string>; |
| 4022 | readonly nextCursor: string | null; |
| 4023 | } |
| 4024 | >(); |
| 4025 | const ttlMs = Duration.toMillis(DIFF_CACHE_TTL); |
| 4026 | const fileKey = (oldPath: string, newPath: string) => JSON.stringify([oldPath, newPath]); |
| 4027 | const sliceKey = (input: PullRequestDiffInput) => |
| 4028 | JSON.stringify([refCacheKey(input), input.cursor ?? null, input.commit ?? null]); |
| 4029 | const recordPaths = (key: string, slice: ProviderDiffFilePaths, at: number) => { |
| 4030 | const entry = { |
| 4031 | at, |
| 4032 | files: new Set(slice.files.map((file) => fileKey(file.oldPath, file.newPath))), |
| 4033 | nextCursor: slice.nextCursor, |
| 4034 | }; |
| 4035 | held.delete(key); |
| 4036 | if (held.size >= DIFF_CACHE_CAPACITY) { |
| 4037 | const oldest = held.keys().next().value; |
| 4038 | if (oldest !== undefined) held.delete(oldest); |
| 4039 | } |
| 4040 | held.set(key, entry); |
| 4041 | return entry; |
| 4042 | }; |
| 4043 | const record = (key: string, slice: PullRequestDiffResult, at: number) => |
| 4044 | recordPaths( |
| 4045 | key, |
| 4046 | { |
| 4047 | files: parseDiffFilePaths(slice.patch).map((file) => ({ |
| 4048 | oldPath: file.oldPath ?? file.newPath ?? "", |
| 4049 | newPath: file.newPath ?? file.oldPath ?? "", |
| 4050 | })), |
| 4051 | nextCursor: slice.nextCursor, |
| 4052 | }, |
| 4053 | at, |
| 4054 | ); |
| 4055 | const read = Effect.fn("PullRequestService.read")(function* (input: PullRequestDiffInput) { |
| 4056 | const key = sliceKey(input); |
| 4057 | const now = yield* Clock.currentTimeMillis; |
| 4058 | const cached = held.get(key); |
| 4059 | if (cached !== undefined && now - cached.at <= ttlMs) return cached; |
| 4060 | const project = yield* requireProject(input); |
| 4061 | if (project.api.capabilities.diff && project.api.getDiffFilePaths) { |
| 4062 | const slice = yield* project.api |
| 4063 | .getDiffFilePaths({ |
| 4064 | cwd: project.project.workspaceRoot, |
| 4065 | repository: project.repository, |
| 4066 | host: project.host, |
| 4067 | number: input.number, |
| 4068 | ...(input.cursor === undefined ? {} : { cursor: input.cursor }), |
| 4069 | ...(input.commit === undefined ? {} : { commit: input.commit }), |
| 4070 | }) |
| 4071 | .pipe(Effect.mapError(toPullRequestError("diffFileContents"))); |
| 4072 | return recordPaths(key, slice, now); |
| 4073 | } |
| 4074 | const { value, observedAt } = yield* readDiff(input).read; |
| 4075 | return record(key, value, observedAt); |
| 4076 | }); |
| 4077 | return { read: credentialCached(read), record, fileKey }; |
| 4078 | })(); |
| 4079 | const changesFile = (input: PullRequestDiffFileContentsInput) => { |
| 4080 | const wanted = diffFiles.fileKey(input.oldPath, input.newPath); |
| 4081 | const walk = (cursor: string | undefined): Effect.Effect<boolean, PullRequestError> => |
| 4082 | diffFiles |
| 4083 | .read({ |
| 4084 | ...input, |
| 4085 | ...(cursor === undefined ? {} : { cursor }), |
| 4086 | ...(input.commit === undefined ? {} : { commit: input.commit }), |
| 4087 | }) |
| 4088 | .pipe( |
| 4089 | Effect.flatMap((slice) => |
| 4090 | slice.files.has(wanted) |
| 4091 | ? Effect.succeed(true) |
| 4092 | : slice.nextCursor === null |
| 4093 | ? Effect.succeed(false) |
| 4094 | : walk(slice.nextCursor), |
| 4095 | ), |
| 4096 | ); |
| 4097 | return walk(undefined); |
| 4098 | }; |
| 4099 | // PR read access does not grant arbitrary repository reads with the project credential; restrict to changed files. |
| 4100 | const diffFileContents: PullRequestService["Service"]["diffFileContents"] = (input) => |
| 4101 | changesFile(input).pipe( |
| 4102 | Effect.flatMap((changed) => |
| 4103 | changed |
| 4104 | ? readDiffFileContents(input) |
| 4105 | : Effect.fail( |
| 4106 | new PullRequestOperationError({ |
| 4107 | operation: "diffFileContents", |
| 4108 | detail: "This file is not part of the change request.", |
| 4109 | reason: "not-found", |
| 4110 | }), |
| 4111 | ), |
| 4112 | ), |
| 4113 | ); |
| 4114 | |
| 4115 | return PullRequestService.of({ |
| 4116 | withSharedProjectReads, |
| 4117 | routing, |
| 4118 | routingIdentity, |
| 4119 | withRoutingCredential, |
| 4120 | list, |
| 4121 | filterOptions, |
| 4122 | // The local operation owns the span; this wrapper only canonicalizes refs. |
| 4123 | listStats: Effect.fnUntraced(function* (input) { |
| 4124 | const refs = yield* Effect.forEach(input.refs, (ref) => |
| 4125 | canonicalRef(ref).pipe(Effect.option), |
| 4126 | ); |
| 4127 | return yield* listStats({ ...input, refs: refs.flatMap(Option.toArray) }); |
| 4128 | }), |
| 4129 | summary: credentialCached(summary), |
| 4130 | batchesReads, |
| 4131 | stack: credentialCached(stack), |
| 4132 | subscribeMerges: PubSub.subscribe(mergedPullRequests).pipe( |
| 4133 | Effect.map((subscription) => Stream.fromSubscription(subscription)), |
| 4134 | ), |
| 4135 | subscribeStateChanges: PubSub.subscribe(stateChanges).pipe( |
| 4136 | Effect.map((subscription) => Stream.fromSubscription(subscription)), |
| 4137 | ), |
| 4138 | reportState, |
| 4139 | subscribeRefreshes: SubscriptionRef.changes(pullRequestRefreshes).pipe( |
| 4140 | Stream.filter((revision) => revision > 0), |
| 4141 | ), |
| 4142 | subscribeLinkedThreadRefreshes: SubscriptionRef.changes(linkedThreadRefreshes).pipe( |
| 4143 | Stream.filter((revision) => revision > 0), |
| 4144 | ), |
| 4145 | notifyLinkedThreadsChanged, |
| 4146 | refreshAfterTurn, |
| 4147 | detail: credentialCached(detail), |
| 4148 | checks: credentialCached((input) => Cache.get(checksCache, refCacheKey(input))), |
| 4149 | watchFingerprint: credentialCached((input) => |
| 4150 | Cache.get(watchFingerprintCache, refCacheKey(input)), |
| 4151 | ), |
| 4152 | activity: credentialCached(activity), |
| 4153 | changes, |
| 4154 | servesProject, |
| 4155 | preview: credentialCached(preview), |
| 4156 | threadComments, |
| 4157 | diff: credentialCached(diff), |
| 4158 | diffFileContents, |
| 4159 | filesViewed: credentialCached(filesViewed), |
| 4160 | setFilesViewed, |
| 4161 | changeBreakdown: credentialCached((input) => |
| 4162 | Cache.get(changeBreakdownCache, refCacheKey(input)), |
| 4163 | ), |
| 4164 | runAction: runActionAndInvalidate, |
| 4165 | checkLogs, |
| 4166 | rerunChecks, |
| 4167 | update: invalidatedByMutation(update), |
| 4168 | comment: invalidatedByMutation(comment), |
| 4169 | updateComment: invalidatedByMutation(updateComment), |
| 4170 | submitReview: invalidatedByMutation(submitReview), |
| 4171 | replyToThread: invalidatedByMutation(replyToThread), |
| 4172 | setThreadResolution: invalidatedByMutation(setThreadResolution), |
| 4173 | setReaction: invalidatedByMutation(setReaction), |
| 4174 | reviewerCandidates, |
| 4175 | requestReviewers: invalidatedByMutation(requestReviewers), |
| 4176 | labelCandidates, |
| 4177 | setLabels: invalidatedByMutation(setLabels), |
| 4178 | invalidate, |
| 4179 | }); |
| 4180 | }); |
| 4181 | |
| 4182 | export const layer = Layer.effect(PullRequestService, make); |