| 1 | import { type Database, schema } from '@ghost/db'; |
| 2 | import { Inject, Injectable |
| 3 | import { and, eq |
| 4 | import { Readable } |
| 5 | |
| 6 | import { RepositoryMaterializerService } |
| 7 | import { PackProcessService } |
| 8 | import type { GitRequestBody |
| 9 | import { |
| 10 | isProbeRequest, |
| 11 | readReceivePackHeader, |
| 12 | } from '../lib/git/protocol/receive-pack-request.js'; |
| 13 | import { withVerifiedPack } |
| 14 | import { RefAdvertisementService } |
| 15 | import { RepositoryContributionService } |
| 16 | import { PushTransactionService } |
| 17 | import { PullRefsService } |
| 18 | import { PullRequestPushesService } |
| 19 | import { CodeSearchService } |
| 20 | import { StorageQuotaService } |
| 21 | import { IssueReferencesService } |
| 22 | import { listCommits } |
| 23 | import { resolveDefaultRef } |
| 24 | import { isPullRef } |
| 25 | import { type RefTransition, |
| 26 | import { createUlid } |
| 27 | import type { Repository |
| 28 | import { |
| 29 | storageAccountOf, |
| 30 | billedKindOf, |
| 31 | } from '../lib/storage/storage-account.js'; |
| 32 | import { MAX_CLOSING_COMMITS } |
| 33 | import { MAX_PUSH_COMMITS, publishEvent |
| 34 | import { DATABASE } |
| 35 | import { |
| 36 | isGitServiceName, |
| 37 | type GitServiceName, |
| 38 | } from '../lib/git/protocol/git-service.js'; |
| 39 | import { |
| 40 | ProtectedRefError, |
| 41 | UnsupportedGitServiceError, |
| 42 | } from '../lib/git/git.errors.js'; |
| 43 | import { DomainError } |
| 44 | import { rejectedPushReport } |
| 45 | import { errorMessage } |
| 46 | |
| 47 | export interface GitTransportResponse |
| 48 | headers: Record |
| 49 | body: Readable |
| 50 | } |
| 51 | |
| 52 | interface RepositoryRef { |
| 53 | repository: { |
| 54 | } |
| 55 | |
| 56 | @Injectable() |
| 57 | export class GitService |
| 58 | private readonly logger |
| 59 | |
| 60 | constructor( |
| 61 | private readonly refAdvertisement |
| 62 | private readonly packProcess |
| 63 | private readonly pushTransaction |
| 64 | private readonly materializer |
| 65 | private readonly contributions |
| 66 | private readonly codeSearch |
| 67 | private readonly references |
| 68 | private readonly pullRefs |
| 69 | private readonly pullRequestPushes |
| 70 | private readonly quota |
| 71 | @Inject(DATABASE) |
| 72 | ) {} |
| 73 | |
| 74 | async advertiseRefs({ |
| 75 | repository, |
| 76 | service, |
| 77 | protocol, |
| 78 | }: RepositoryRef |
| 79 | service: string |
| 80 | protocol?: string |
| 81 | }): Promise |
| 82 | if (!isGitServiceName(service |
| 83 | |
| 84 | const repoDirectory = |
| 85 | |
| 86 | return { |
| 87 | headers: { |
| 88 | 'Content-Type': `application/x-${service |
| 89 | 'Cache-Control': 'no-cache', |
| 90 | }, |
| 91 | body: this.refAdvertisement |
| 92 | repoDirectory, |
| 93 | service, |
| 94 | protocol, |
| 95 | }), |
| 96 | }; |
| 97 | } |
| 98 | |
| 99 | async uploadPack({ |
| 100 | repository, |
| 101 | body, |
| 102 | protocol, |
| 103 | }: RepositoryRef |
| 104 | body: GitRequestBody |
| 105 | protocol?: string |
| 106 | }): Promise |
| 107 | const repoDirectory = |
| 108 | |
| 109 | return { |
| 110 | headers: resultHeaders('git-upload-pack |
| 111 | body: this.packProcess |
| 112 | repoDirectory, |
| 113 | input: body.open |
| 114 | protocol, |
| 115 | }), |
| 116 | }; |
| 117 | } |
| 118 | |
| 119 | /** A push. Materializes before the ref checks so they see what the log holds; the next materialize reconciles whatever git wrote locally. */ |
| 120 | async receivePack({ |
| 121 | repository, |
| 122 | body, |
| 123 | pushedBy = null, |
| 124 | apiKeyId = null, |
| 125 | }: { |
| 126 | repository: Pick |
| 127 | Repository, |
| 128 | | 'id' |
| 129 | | 'defaultBranch' |
| 130 | | 'visibility' |
| 131 | | 'ownerId' |
| 132 | | 'organizationId' |
| 133 | | 'parentRepositoryId' |
| 134 | >; |
| 135 | body: GitRequestBody |
| 136 | pushedBy?: string |
| 137 | /** The key an HTTP push authenticated with; only the key minted for a running import may write `refs/pull/*`. */ |
| 138 | apiKeyId?: string |
| 139 | }): Promise |
| 140 | if (await isProbeRequest |
| 141 | return { |
| 142 | headers: resultHeaders('git-receive-pack |
| 143 | body: Readable.from |
| 144 | }; |
| 145 | } |
| 146 | |
| 147 | const { id: |
| 148 | const isPublic = |
| 149 | const { transitions, |
| 150 | await readReceivePackHeader(body |
| 151 | let importing: |
| 152 | let repoDirectory: |
| 153 | try { |
| 154 | ({ importing, repoDirectory |
| 155 | repository, |
| 156 | transitions, |
| 157 | body, |
| 158 | packOffset, |
| 159 | pushedBy, |
| 160 | apiKeyId, |
| 161 | })); |
| 162 | } catch (error) |
| 163 | // Every refusal lands before the log commits, so the client is told per ref, the way git itself refuses one, instead of seeing a dropped connection. |
| 164 | const report = |
| 165 | error instanceof DomainError |
| 166 | ? rejectedPushReport({ |
| 167 | refs: transitions.map |
| 168 | capabilities, |
| 169 | reason: error.message |
| 170 | }) |
| 171 | : null; |
| 172 | if (!report) |
| 173 | return { |
| 174 | headers: resultHeaders('git-receive-pack |
| 175 | body: Readable.from |
| 176 | }; |
| 177 | } |
| 178 | |
| 179 | const result = |
| 180 | repoDirectory, |
| 181 | input: body.open |
| 182 | }); |
| 183 | |
| 184 | // Fire-and-forget: a push must not wait on a history walk or a reindex, and an interrupted index leaves a cursor the next sync tops up. |
| 185 | result.once('close |
| 186 | this.codeSearch.indexInBackground |
| 187 | repositoryId, |
| 188 | isPublic, |
| 189 | repoDirectory, |
| 190 | }); |
| 191 | this.contributions |
| 192 | .sync({ repositoryId |
| 193 | .catch((error: |
| 194 | this.logger.warn |
| 195 | `Contribution index update failed for ${repositoryId}: ${ |
| 196 | ), |
| 197 | ); |
| 198 | this.closeFromPush({ |
| 199 | repositoryId, |
| 200 | repoDirectory, |
| 201 | transitions, |
| 202 | pushedBy, |
| 203 | }).catch((error |
| 204 | this.logger.warn |
| 205 | `Closing referenced issues failed for ${repositoryId}: ${ |
| 206 | ), |
| 207 | ); |
| 208 | void this.pullRefs. |
| 209 | // An import is history, not activity: its push names every branch and tag the repository ever had. |
| 210 | if (importing) return |
| 211 | this.db |
| 212 | .update(schema.repository |
| 213 | .set({ lastPushedAt: |
| 214 | .where(eq(schema |
| 215 | .catch((error: |
| 216 | this.logger.warn |
| 217 | `Recording the push time failed for ${repositoryId}: ${ |
| 218 | ), |
| 219 | ); |
| 220 | void this.pullRequestPushes. |
| 221 | repositoryId, |
| 222 | transitions, |
| 223 | pushedBy, |
| 224 | }); |
| 225 | this.publishPushes({ |
| 226 | repositoryId, |
| 227 | repoDirectory, |
| 228 | transitions, |
| 229 | pushedBy, |
| 230 | }).catch((error |
| 231 | this.logger.warn |
| 232 | `Publishing push events failed for ${repositoryId}: ${ |
| 233 | ), |
| 234 | ); |
| 235 | }); |
| 236 | |
| 237 | return { |
| 238 | headers: resultHeaders('git-receive-pack |
| 239 | body: result, |
| 240 | }; |
| 241 | } |
| 242 | |
| 243 | /** Checks, bills and commits a push to the log. Checked before the log: receive-pack's own refusals land after the commit point, too late to keep a ref out. */ |
| 244 | private async commitToLog |
| 245 | repository, |
| 246 | transitions, |
| 247 | body, |
| 248 | packOffset, |
| 249 | pushedBy, |
| 250 | apiKeyId, |
| 251 | }: { |
| 252 | repository: Pick |
| 253 | Repository, |
| 254 | | 'id' |
| 255 | | 'defaultBranch' |
| 256 | | 'ownerId' |
| 257 | | 'organizationId' |
| 258 | | 'parentRepositoryId' |
| 259 | >; |
| 260 | transitions: RefTransition |
| 261 | body: GitRequestBody |
| 262 | packOffset: number |
| 263 | pushedBy: string |
| 264 | apiKeyId: string |
| 265 | }) { |
| 266 | const repositoryId = |
| 267 | const importing = |
| 268 | const pullRef = |
| 269 | if (pullRef && |
| 270 | throw new ProtectedRefError( |
| 271 | } |
| 272 | const repoDirectory = |
| 273 | id: repositoryId, |
| 274 | defaultBranch: repository.defaultBranch |
| 275 | }); |
| 276 | |
| 277 | await withVerifiedPack( |
| 278 | { gitDir: repoDirectory, |
| 279 | (pack) => |
| 280 | const ulid = |
| 281 | const size = |
| 282 | const entry = |
| 283 | let committed = |
| 284 | // ponytail: a crash between the log's commit point and the billing row leaves the push unbilled; reconcile against the WAL index, as pull refs do, if that leak matters. |
| 285 | return this.quota |
| 286 | .reserve( |
| 287 | storageAccountOf(repository), |
| 288 | billedKindOf(repository, ' |
| 289 | size, |
| 290 | async (tx) |
| 291 | await this.pushTransaction |
| 292 | ulid, |
| 293 | repoId: repositoryId, |
| 294 | transitions, |
| 295 | ...pack, |
| 296 | pushedBy, |
| 297 | }); |
| 298 | committed = true; |
| 299 | await tx |
| 300 | .insert(schema.repositoryLogEntry |
| 301 | .values(entry) |
| 302 | .onConflictDoNothing(); |
| 303 | }, |
| 304 | ) |
| 305 | .catch(async ( |
| 306 | // The layer is in the log whatever the transaction did, so it is billed outside it for the next push's quota check to count. |
| 307 | if (committed) |
| 308 | await this.db |
| 309 | .insert(schema.repositoryLogEntry |
| 310 | .values(entry) |
| 311 | .onConflictDoNothing(); |
| 312 | throw error; |
| 313 | }); |
| 314 | }, |
| 315 | ); |
| 316 | return { importing, |
| 317 | } |
| 318 | |
| 319 | /** Published after the push, not with it: refs live in object storage, outside any database transaction, so a crash in between loses the event but never invents one. */ |
| 320 | private async publishPushes |
| 321 | repositoryId, |
| 322 | repoDirectory, |
| 323 | transitions, |
| 324 | pushedBy, |
| 325 | }: { |
| 326 | repositoryId: string |
| 327 | repoDirectory: string |
| 328 | transitions: RefTransition |
| 329 | pushedBy: string |
| 330 | }) { |
| 331 | // Branches and tags only, as GitHub sends them: an import pushes a `refs/pull/*` ref per pull request, which nobody subscribes to. |
| 332 | const published = |
| 333 | ({ ref }) |
| 334 | ref.startsWith('refs/heads/ |
| 335 | ); |
| 336 | for (const { |
| 337 | const before = |
| 338 | const after = |
| 339 | const { commits |
| 340 | ? { commits: [] |
| 341 | : await listCommits( |
| 342 | gitDir: repoDirectory, |
| 343 | // a new ref lists from its tip, since there is no old one to start after |
| 344 | ref: oldOid.equals |
| 345 | limit: MAX_PUSH_COMMITS, |
| 346 | }); |
| 347 | await publishEvent(this |
| 348 | type: 'push', |
| 349 | repositoryId, |
| 350 | actorId: pushedBy, |
| 351 | payload: { |
| 352 | ref, |
| 353 | before, |
| 354 | after, |
| 355 | commits, |
| 356 | }, |
| 357 | }); |
| 358 | } |
| 359 | } |
| 360 | |
| 361 | /** Commits that moved the default branch forward close the issues they name, like GitHub's `Fixes #1`. */ |
| 362 | private async closeFromPush |
| 363 | repositoryId, |
| 364 | repoDirectory, |
| 365 | transitions, |
| 366 | pushedBy, |
| 367 | }: { |
| 368 | repositoryId: string |
| 369 | repoDirectory: string |
| 370 | transitions: RefTransition |
| 371 | pushedBy: string |
| 372 | }) { |
| 373 | const defaultRef = |
| 374 | const pushed = |
| 375 | (transition) => |
| 376 | ); |
| 377 | // ponytail: creating or deleting the default branch closes nothing; the first push of a whole history would otherwise close every issue it ever fixed. |
| 378 | if ( |
| 379 | !pushed || |
| 380 | pushed.oldOid.equals |
| 381 | pushed.newOid.equals |
| 382 | ) |
| 383 | return; |
| 384 | |
| 385 | const { commits |
| 386 | gitDir: repoDirectory, |
| 387 | ref: `${pushed. |
| 388 | limit: MAX_CLOSING_COMMITS, |
| 389 | }); |
| 390 | await this.references |
| 391 | repository: { id: repositoryId |
| 392 | actorId: pushedBy, |
| 393 | commits, |
| 394 | }); |
| 395 | } |
| 396 | |
| 397 | private async isImportKey |
| 398 | if (!apiKeyId) |
| 399 | const [running] |
| 400 | .select({ id: |
| 401 | .from(schema.repositoryImport |
| 402 | .where( |
| 403 | and( |
| 404 | eq(schema.repositoryImport |
| 405 | eq(schema.repositoryImport |
| 406 | eq(schema.repositoryImport |
| 407 | ), |
| 408 | ); |
| 409 | return Boolean(running |
| 410 | } |
| 411 | } |
| 412 | |
| 413 | function resultHeaders(service: |
| 414 | return { |
| 415 | 'Content-Type': `application/x-${service |
| 416 | 'Cache-Control': 'no-cache', |
| 417 | }; |
| 418 | } |