The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as Clock from "effect/Clock"; |
| 2 | import * as Cache from "effect/Cache"; |
| 3 | import * as Context from "effect/Context"; |
| 4 | import * as Effect from "effect/Effect"; |
| 5 | import * as Option from "effect/Option"; |
| 6 | import * as Schema from "effect/Schema"; |
| 7 | import * as Semaphore from "effect/Semaphore"; |
| 8 | import { PositiveInt, type PullRequestChecks } from "@t3tools/contracts"; |
| 9 | |
| 10 | import * as GitHubRest from "./GitHubRest.ts"; |
| 11 | import * as GitHubRequestPolicy from "./GitHubRequestPolicy.ts"; |
| 12 | import type { GitHubPullRequestDetail } from "./gitHubPullRequestJson.ts"; |
| 13 | import type { GitHubPullRequestApiError } from "./GitHubPullRequestApi.ts"; |
| 14 | import type { ProviderRepositoryRef } from "@t3tools/source-control-core/server/PullRequestProvider"; |
| 15 | |
| 16 | const HeadSchema = Schema.Struct({ |
| 17 | head: Schema.Struct({ |
| 18 | sha: Schema.String.check(Schema.isPattern(/^[a-f0-9]{40,64}$/)), |
| 19 | // Null once the fork a pull request came from has been deleted. |
| 20 | repo: Schema.NullOr(Schema.Struct({ id: PositiveInt })), |
| 21 | }), |
| 22 | base: Schema.Struct({ repo: Schema.Struct({ id: PositiveInt }) }), |
| 23 | }); |
| 24 | const decodeHead = Schema.decodeUnknownEffect(Schema.fromJsonString(HeadSchema)); |
| 25 | |
| 26 | class ChecksUnavailable extends Schema.TaggedError<ChecksUnavailable>()("ChecksUnavailable", {}) {} |
| 27 | |
| 28 | const WorkflowRunSchema = Schema.Struct({ |
| 29 | id: Schema.Int, |
| 30 | name: Schema.optional(Schema.NullOr(Schema.String)), |
| 31 | html_url: Schema.optional(Schema.NullOr(Schema.String)), |
| 32 | status: Schema.optional(Schema.NullOr(Schema.String)), |
| 33 | conclusion: Schema.optional(Schema.NullOr(Schema.String)), |
| 34 | head_branch: Schema.optional(Schema.NullOr(Schema.String)), |
| 35 | }); |
| 36 | const decodeWorkflowRuns = Schema.decodeUnknownOption( |
| 37 | Schema.fromJsonString(Schema.Struct({ workflow_runs: Schema.Array(WorkflowRunSchema) })), |
| 38 | ); |
| 39 | |
| 40 | export type KnownWorkflowRun = typeof WorkflowRunSchema.Type; |
| 41 | |
| 42 | export const KnownWorkflowRuns = Context.Reference<{ |
| 43 | readonly headSha: string; |
| 44 | readonly runs: ReadonlyArray<KnownWorkflowRun>; |
| 45 | } | null>("@t3tools/source-control-github/server/gitHubConditionalChecks/KnownWorkflowRuns", { |
| 46 | defaultValue: () => null, |
| 47 | }); |
| 48 | |
| 49 | type Validator = { etag: string | undefined; next: boolean; body: string }; |
| 50 | |
| 51 | const UNSUPPORTED_STATUSES = new Set([404, 405, 501]); |
| 52 | |
| 53 | export const makeChecksRevalidator = Effect.gen(function* () { |
| 54 | const api = yield* GitHubRest.GitHubRest; |
| 55 | const entries = yield* Cache.makeWith( |
| 56 | (_key: string) => |
| 57 | Effect.sync(() => ({ |
| 58 | gate: Semaphore.makeUnsafe(1), |
| 59 | validators: new Map<string, Validator>(), |
| 60 | head: null as typeof HeadSchema.Type | null, |
| 61 | value: null as PullRequestChecks | null, |
| 62 | readAt: 0, |
| 63 | supported: true, |
| 64 | })), |
| 65 | { capacity: 128, timeToLive: () => "30 minutes" }, |
| 66 | ); |
| 67 | return ( |
| 68 | input: ProviderRepositoryRef & { readonly number: number }, |
| 69 | read: Effect.Effect< |
| 70 | Pick<GitHubPullRequestDetail, "state" | "checks" | "headSha"> & { |
| 71 | workflowApprovalsRequired?: number; |
| 72 | }, |
| 73 | GitHubPullRequestApiError |
| 74 | >, |
| 75 | ) => |
| 76 | Effect.gen(function* () { |
| 77 | const credential = yield* GitHubRequestPolicy.PinnedGitHubCredential; |
| 78 | if (credential === null) return yield* read; |
| 79 | const key = `${credential.credentialFingerprint}\0${input.host}\0${input.repository}\0${input.number}`; |
| 80 | const entry = yield* Cache.get(entries, key); |
| 81 | return yield* entry.gate.withPermit( |
| 82 | Effect.gen(function* () { |
| 83 | if (!entry.supported) return yield* read; |
| 84 | const fail = (status: number) => |
| 85 | new GitHubRequestPolicy.GitHubApiResponseError({ |
| 86 | host: input.host, |
| 87 | operation: "revalidateChecks", |
| 88 | status, |
| 89 | }); |
| 90 | const get = Effect.fn("gitHubConditionalChecks.get")(function* ( |
| 91 | endpoint: string, |
| 92 | head = false, |
| 93 | ) { |
| 94 | const previous = entry.validators.get(endpoint); |
| 95 | const response = yield* api |
| 96 | .rest({ |
| 97 | host: input.host, |
| 98 | operation: "revalidateChecks", |
| 99 | path: endpoint, |
| 100 | ...(previous?.etag ? { ifNoneMatch: previous.etag } : {}), |
| 101 | }) |
| 102 | .pipe( |
| 103 | Effect.catchTags({ |
| 104 | GitHubApiNotFoundError: () => |
| 105 | Effect.sync(() => { |
| 106 | entry.supported = false; |
| 107 | return null; |
| 108 | }), |
| 109 | GitHubApiResponseError: (error) => |
| 110 | Effect.sync(() => { |
| 111 | entry.supported &&= !UNSUPPORTED_STATUSES.has(error.status); |
| 112 | return null; |
| 113 | }), |
| 114 | }), |
| 115 | ); |
| 116 | if (response === null) { |
| 117 | entry.value = null; |
| 118 | return null; |
| 119 | } |
| 120 | if (response.status === 304 && previous) return previous.next; |
| 121 | if (response.status !== 200 || response.truncated) { |
| 122 | return yield* fail(response.status); |
| 123 | } |
| 124 | entry.value = null; |
| 125 | if (head) { |
| 126 | const decoded = yield* decodeHead(response.body).pipe( |
| 127 | Effect.mapError(() => fail(response.status)), |
| 128 | ); |
| 129 | if (entry.head?.head.sha !== decoded.head.sha) entry.validators.clear(); |
| 130 | entry.head = decoded; |
| 131 | } |
| 132 | const validator = { |
| 133 | etag: response.headers["etag"]?.trim(), |
| 134 | next: /rel="next"/.test(response.headers["link"] ?? ""), |
| 135 | body: response.body, |
| 136 | }; |
| 137 | entry.validators.set(endpoint, validator); |
| 138 | return validator.next; |
| 139 | }); |
| 140 | const root = `repos/${input.repository}`; |
| 141 | if ((yield* get(`${root}/pulls/${input.number}`, true)) === null) return yield* read; |
| 142 | const head = entry.head; |
| 143 | if (head === null) return yield* fail(200); |
| 144 | const runsEndpoint = |
| 145 | head.head.repo?.id !== head.base.repo.id |
| 146 | ? `${root}/actions/runs?head_sha=${head.head.sha}&event=pull_request` |
| 147 | : null; |
| 148 | const endpoints = [ |
| 149 | `${root}/commits/${head.head.sha}/check-runs?filter=all`, |
| 150 | `${root}/commits/${head.head.sha}/status`, |
| 151 | ...(runsEndpoint === null ? [] : [runsEndpoint]), |
| 152 | ]; |
| 153 | const runPages: Array<string> = []; |
| 154 | // Each endpoint has its own cursor; only pages within one endpoint depend on each other. |
| 155 | // An unavailable endpoint interrupts the others so the fallback read starts at once. |
| 156 | const available = yield* Effect.forEach( |
| 157 | endpoints, |
| 158 | Effect.fn("gitHubConditionalChecks.revalidateEndpoint")(function* (endpoint) { |
| 159 | for (let page = 1; ; page++) { |
| 160 | if (page > 100) return yield* fail(200); |
| 161 | const paged = `${endpoint}${endpoint.includes("?") ? "&" : "?"}per_page=100&page=${page}`; |
| 162 | const next = yield* get(paged); |
| 163 | if (next === null) return yield* new ChecksUnavailable(); |
| 164 | if (endpoint === runsEndpoint) runPages.push(paged); |
| 165 | if (!next) return; |
| 166 | } |
| 167 | }), |
| 168 | { concurrency: 3, discard: true }, |
| 169 | ).pipe( |
| 170 | Effect.as(true), |
| 171 | Effect.catchTags({ ChecksUnavailable: () => Effect.succeed(false) }), |
| 172 | ); |
| 173 | if (!available) return yield* read; |
| 174 | const now = yield* Clock.currentTimeMillis; |
| 175 | if (entry.value !== null && now - entry.readAt < 5 * 60_000) return entry.value; |
| 176 | const pages = runPages.map((endpoint) => |
| 177 | decodeWorkflowRuns(entry.validators.get(endpoint)?.body ?? ""), |
| 178 | ); |
| 179 | const known = |
| 180 | runsEndpoint !== null && pages.every(Option.isSome) |
| 181 | ? { |
| 182 | headSha: head.head.sha, |
| 183 | runs: pages.flatMap((page) => |
| 184 | Option.isSome(page) ? page.value.workflow_runs : [], |
| 185 | ), |
| 186 | } |
| 187 | : null; |
| 188 | const fresh = yield* read.pipe(Effect.provideService(KnownWorkflowRuns, known)); |
| 189 | const value = { |
| 190 | state: fresh.state, |
| 191 | checks: fresh.checks, |
| 192 | }; |
| 193 | entry.value = |
| 194 | fresh.workflowApprovalsRequired !== undefined && fresh.headSha === head.head.sha |
| 195 | ? value |
| 196 | : null; |
| 197 | entry.readAt = now; |
| 198 | return value; |
| 199 | }), |
| 200 | ); |
| 201 | }); |
| 202 | }); |