| 1 | import path from 'node:path'; |
| 2 | |
| 3 | import { type Database, |
| 4 | import { atLeast } |
| 5 | import { Inject, Injectable |
| 6 | import { and, asc |
| 7 | |
| 8 | import { DATABASE } |
| 9 | import { keyset } |
| 10 | import { isoTimestamp } |
| 11 | import { publishEvent } |
| 12 | import { packRange } |
| 13 | import { |
| 14 | bufferBody, |
| 15 | fileBody, |
| 16 | } from '../../lib/git/protocol/git-request-body.js'; |
| 17 | import { isValidRefName } |
| 18 | import { listBranches, listRefs |
| 19 | import { createTagObject } |
| 20 | import { listTags } |
| 21 | import { resolveTargetCommit } |
| 22 | import { ZERO_OID } |
| 23 | import { |
| 24 | InvalidTagNameError, |
| 25 | ReleaseAlreadyExistsError, |
| 26 | ReleaseNotFoundError, |
| 27 | TagNotFoundError, |
| 28 | TagTargetNotFoundError, |
| 29 | } from '../../lib/releases/releases.errors.js'; |
| 30 | import type { AuthorizedRepository |
| 31 | import { withTempDir } |
| 32 | import { RepositoryMaterializerService } |
| 33 | import { RepositoryAccessService } |
| 34 | import { PushTransactionService } |
| 35 | import { UsersService } |
| 36 | import type { |
| 37 | CreateReleaseRequestDTO, |
| 38 | GetReleasesQueryDTO, |
| 39 | GetReleasesResponseDTO, |
| 40 | ReleaseDTO, |
| 41 | UpdateReleaseRequestDTO, |
| 42 | } from './dto/release.dto.js'; |
| 43 | import { |
| 44 | ReleaseAssetsService, |
| 45 | releaseAssetColumns, |
| 46 | } from './release-assets.service.js'; |
| 47 | |
| 48 | /** What an edit can change; `release.edited` is published only when one of these differs afterwards. */ |
| 49 | const editableColumns = { |
| 50 | name: schema.release |
| 51 | body: schema.release |
| 52 | isDraft: schema.release |
| 53 | isPrerelease: schema.release |
| 54 | }; |
| 55 | |
| 56 | const DEFAULT_PAGE_SIZE = 10 |
| 57 | |
| 58 | type RepositoryRef |
| 59 | |
| 60 | /** How the GitHub layer orders a page: by creation, or by name ignoring case, which falls back to the tag as a nameless release reads. */ |
| 61 | export type ReleaseOrder |
| 62 | field: 'created |
| 63 | direction: 'asc |
| 64 | }; |
| 65 | |
| 66 | /** Newest published release that is neither a draft nor a prerelease. */ |
| 67 | function latestReleaseId(repositoryId: |
| 68 | return sql`(select ${ |
| 69 | } |
| 70 | |
| 71 | @Injectable() |
| 72 | export class ReleasesService |
| 73 | constructor( |
| 74 | @Inject(DATABASE) |
| 75 | private readonly access |
| 76 | private readonly materializer |
| 77 | private readonly pushTransaction |
| 78 | private readonly users |
| 79 | private readonly assets |
| 80 | ) {} |
| 81 | |
| 82 | async listReleases({ |
| 83 | query, |
| 84 | ...target |
| 85 | }: RepositoryRef |
| 86 | query: GetReleasesQueryDTO |
| 87 | }): Promise |
| 88 | const repository = |
| 89 | ...target, |
| 90 | operation: 'read', |
| 91 | }); |
| 92 | |
| 93 | const list = |
| 94 | cursor: query.cursor |
| 95 | limit: query.limit |
| 96 | keys: { createdAt: schema |
| 97 | }); |
| 98 | const { page, |
| 99 | await this.select |
| 100 | ); |
| 101 | |
| 102 | return { releases: |
| 103 | } |
| 104 | |
| 105 | /** Offset pages in any order, with the total, as the GitHub layer pages lists. */ |
| 106 | async pageReleases({ |
| 107 | offset, |
| 108 | limit, |
| 109 | order, |
| 110 | ...target |
| 111 | }: RepositoryRef |
| 112 | const repository = |
| 113 | ...target, |
| 114 | operation: 'read', |
| 115 | }); |
| 116 | const sort = |
| 117 | const [rows, |
| 118 | this.select(repository |
| 119 | sort( |
| 120 | order.field === |
| 121 | ? sql`lower(coalesce(${schema |
| 122 | : schema.release. |
| 123 | ), |
| 124 | sort(schema.release |
| 125 | ]) |
| 126 | .limit(limit) |
| 127 | // ponytail: OFFSET scans the rows it skips; fine for a repository's releases, keyset if one grows thousands. |
| 128 | .offset(offset), |
| 129 | this.db |
| 130 | .select({ total: |
| 131 | .from(schema.release |
| 132 | .where(this.visible |
| 133 | ]); |
| 134 | return { |
| 135 | releases: await this |
| 136 | total: total?.total |
| 137 | }; |
| 138 | } |
| 139 | |
| 140 | async getRelease({ |
| 141 | const repository = |
| 142 | ...target, |
| 143 | operation: 'read', |
| 144 | }); |
| 145 | return this.readOne |
| 146 | } |
| 147 | |
| 148 | async getLatestRelease(target |
| 149 | const repository = |
| 150 | ...target, |
| 151 | operation: 'read', |
| 152 | }); |
| 153 | return this.readOne |
| 154 | repository, |
| 155 | eq(schema.release |
| 156 | ); |
| 157 | } |
| 158 | |
| 159 | async getReleaseByTag({ |
| 160 | tagName, |
| 161 | ...target |
| 162 | }: RepositoryRef |
| 163 | const repository = |
| 164 | ...target, |
| 165 | operation: 'read', |
| 166 | }); |
| 167 | return this.readOne |
| 168 | } |
| 169 | |
| 170 | /** A tag that does not exist yet is created first, annotated, through the same commit point a push uses. */ |
| 171 | async createRelease({ |
| 172 | body, |
| 173 | ...target |
| 174 | }: RepositoryRef |
| 175 | requesterId: string |
| 176 | body: CreateReleaseRequestDTO |
| 177 | }): Promise |
| 178 | const repository = |
| 179 | ...target, |
| 180 | operation: 'write', |
| 181 | }); |
| 182 | if (!isValidRefName(' |
| 183 | throw new InvalidTagNameError( |
| 184 | } |
| 185 | |
| 186 | const [existing] |
| 187 | .select({ id: |
| 188 | .from(schema.release |
| 189 | .where( |
| 190 | and( |
| 191 | eq(schema.release |
| 192 | eq(schema.release |
| 193 | ), |
| 194 | ); |
| 195 | if (existing) throw |
| 196 | |
| 197 | const directory = |
| 198 | const tags = |
| 199 | // ponytail: a draft tags its commit straight away; GitHub waits for publishing, which needs the target stored on the row. |
| 200 | if (!tags.some |
| 201 | const sha = |
| 202 | repository, |
| 203 | directory, |
| 204 | tags, |
| 205 | body.target, |
| 206 | ); |
| 207 | await this.createTag |
| 208 | repository, |
| 209 | directory, |
| 210 | sha, |
| 211 | name: body.tagName |
| 212 | message: body.name |
| 213 | requesterId: target.requesterId |
| 214 | }); |
| 215 | } |
| 216 | |
| 217 | const isDraft = |
| 218 | const created = |
| 219 | // A concurrent create for the same tag loses on the unique index. |
| 220 | const [row] |
| 221 | .insert(schema.release |
| 222 | .values({ |
| 223 | repositoryId: repository.id |
| 224 | tagName: body.tagName |
| 225 | name: body.name |
| 226 | body: body.body |
| 227 | isDraft, |
| 228 | isPrerelease: body.isPrerelease |
| 229 | authorId: target.requesterId |
| 230 | publishedAt: isDraft ? |
| 231 | }) |
| 232 | .onConflictDoNothing() |
| 233 | .returning({ id: |
| 234 | if (!row) |
| 235 | const event = |
| 236 | repositoryId: repository.id |
| 237 | actorId: target.requesterId |
| 238 | payload: { releaseId: row |
| 239 | }; |
| 240 | await publishEvent(tx |
| 241 | if (!isDraft) |
| 242 | await publishEvent(tx |
| 243 | } |
| 244 | return row; |
| 245 | }); |
| 246 | |
| 247 | return this.readOne |
| 248 | } |
| 249 | |
| 250 | async updateRelease({ |
| 251 | id, |
| 252 | body, |
| 253 | ...target |
| 254 | }: RepositoryRef |
| 255 | id: string |
| 256 | requesterId: string |
| 257 | body: UpdateReleaseRequestDTO |
| 258 | }): Promise |
| 259 | const repository = |
| 260 | ...target, |
| 261 | operation: 'write', |
| 262 | }); |
| 263 | |
| 264 | const updated = |
| 265 | const [before] |
| 266 | .select(editableColumns) |
| 267 | .from(schema.release |
| 268 | .where(this.ownRelease |
| 269 | .for('update') |
| 270 | if (!before) |
| 271 | |
| 272 | const [row] |
| 273 | .update(schema.release |
| 274 | .set({ |
| 275 | // always set, so an empty edit still finds the row instead of failing to build the query |
| 276 | updatedAt: new Date |
| 277 | ...(body.name |
| 278 | ...(body.body |
| 279 | ...(body.isPrerelease |
| 280 | isPrerelease: body.isPrerelease |
| 281 | }), |
| 282 | ...(body.isDraft |
| 283 | // stamped the first time it is published, and kept through any later unpublishing |
| 284 | ...(body.isDraft |
| 285 | publishedAt: sql`coalesce(${ |
| 286 | }), |
| 287 | }) |
| 288 | .where(this.ownRelease |
| 289 | .returning({ id: |
| 290 | if (!row) |
| 291 | const event = |
| 292 | repositoryId: repository.id |
| 293 | actorId: target.requesterId |
| 294 | payload: { releaseId: row |
| 295 | }; |
| 296 | // GitHub sends `edited` only for a change, so publishing an already published release again is silent. |
| 297 | const changed = |
| 298 | Object.keys(editableColumns |
| 299 | ).some((column |
| 300 | if (changed) await |
| 301 | if (before.isDraft |
| 302 | await publishEvent(tx |
| 303 | } |
| 304 | return row; |
| 305 | }); |
| 306 | |
| 307 | return this.readOne |
| 308 | } |
| 309 | |
| 310 | /** The tag stays: deleting a release deletes its notes and its assets. */ |
| 311 | async deleteRelease({ |
| 312 | id, |
| 313 | ...target |
| 314 | }: RepositoryRef |
| 315 | const repository = |
| 316 | ...target, |
| 317 | operation: 'write', |
| 318 | }); |
| 319 | |
| 320 | const [release] |
| 321 | .select({ |
| 322 | id: schema.release |
| 323 | tagName: schema.release |
| 324 | name: schema.release |
| 325 | }) |
| 326 | .from(schema.release |
| 327 | .where(this.ownRelease |
| 328 | if (!release) |
| 329 | |
| 330 | // storage first: the rows go with the release, and an object nothing points at could never be found again |
| 331 | await this.assets |
| 332 | await this.db |
| 333 | await tx.delete |
| 334 | await publishEvent(tx |
| 335 | type: 'release.deleted', |
| 336 | repositoryId: repository.id |
| 337 | actorId: target.requesterId |
| 338 | payload: { release |
| 339 | }); |
| 340 | }); |
| 341 | } |
| 342 | |
| 343 | /** A ref-only entry in the log, pinned to the tag's current target so a push that moved it in between wins. Releases on the tag stay, pointing at nothing. */ |
| 344 | async deleteTag({ |
| 345 | tagName, |
| 346 | ...target |
| 347 | }: RepositoryRef |
| 348 | const repository = |
| 349 | ...target, |
| 350 | operation: 'write', |
| 351 | }); |
| 352 | const ref = |
| 353 | // The tag object's own id, not the commit it peels to: that is what the ref holds. |
| 354 | const oid = |
| 355 | ref, |
| 356 | ); |
| 357 | if (!oid) |
| 358 | |
| 359 | await this.pushTransaction |
| 360 | repoId: repository.id |
| 361 | transitions: [ |
| 362 | { |
| 363 | ref, |
| 364 | oldOid: Buffer.from |
| 365 | newOid: ZERO_OID, |
| 366 | }, |
| 367 | ], |
| 368 | body: bufferBody(Buffer |
| 369 | packOffset: 0, |
| 370 | pushedBy: target.requesterId |
| 371 | }); |
| 372 | } |
| 373 | |
| 374 | /** An annotated tag, as `git tag -a` makes, so the tag carries its own date and author rather than borrowing its commit's. Its one object is packed and pushed through `commitPush`. */ |
| 375 | private async createTag |
| 376 | repository, |
| 377 | directory, |
| 378 | sha, |
| 379 | name, |
| 380 | message, |
| 381 | requesterId, |
| 382 | }: { |
| 383 | repository: AuthorizedRepository |
| 384 | directory: string |
| 385 | sha: string |
| 386 | name: string |
| 387 | message: string |
| 388 | requesterId: string |
| 389 | }) { |
| 390 | const tagger = |
| 391 | const oid = |
| 392 | gitDir: directory, |
| 393 | sha, |
| 394 | name, |
| 395 | message, |
| 396 | tagger, |
| 397 | }); |
| 398 | |
| 399 | await withTempDir('ghost-tag- |
| 400 | const pack = |
| 401 | gitDir: directory, |
| 402 | include: [oid], |
| 403 | exclude: [sha], |
| 404 | prefix: path.join |
| 405 | }); |
| 406 | await this.pushTransaction |
| 407 | repoId: repository.id |
| 408 | transitions: [ |
| 409 | { |
| 410 | ref: `refs/tags/${name |
| 411 | oldOid: ZERO_OID, |
| 412 | newOid: Buffer.from |
| 413 | }, |
| 414 | ], |
| 415 | body: fileBody(pack |
| 416 | packOffset: 0, |
| 417 | pushedBy: requesterId, |
| 418 | }); |
| 419 | }); |
| 420 | } |
| 421 | |
| 422 | private ownRelease(repository |
| 423 | return and( |
| 424 | eq(schema.release |
| 425 | eq(schema.release |
| 426 | ); |
| 427 | } |
| 428 | |
| 429 | private async resolveTarget |
| 430 | repository: AuthorizedRepository |
| 431 | directory: string, |
| 432 | tags: { |
| 433 | requested: string |
| 434 | ) { |
| 435 | const name = |
| 436 | const sha = |
| 437 | gitDir: directory, |
| 438 | defaultBranch: repository.defaultBranch |
| 439 | branches: await listBranches |
| 440 | tags, |
| 441 | requested: name, |
| 442 | }); |
| 443 | if (!sha) |
| 444 | throw new TagTargetNotFoundError( |
| 445 | return sha; |
| 446 | } |
| 447 | |
| 448 | private async readOne |
| 449 | const [row] |
| 450 | if (!row) |
| 451 | |
| 452 | const [release] |
| 453 | return release; |
| 454 | } |
| 455 | |
| 456 | /** Drafts are left out for anyone who cannot write to the repository. */ |
| 457 | private visible(repository |
| 458 | return and( |
| 459 | eq(schema.release |
| 460 | atLeast(repository.viewerRole |
| 461 | ? undefined |
| 462 | : eq(schema. |
| 463 | ); |
| 464 | } |
| 465 | |
| 466 | /** Newest first unless `order` says otherwise. */ |
| 467 | private select( |
| 468 | repository: AuthorizedRepository |
| 469 | where: SQL |
| 470 | order: SQL |
| 471 | ) { |
| 472 | return this.db |
| 473 | .select({ |
| 474 | id: schema.release |
| 475 | tagName: schema.release |
| 476 | name: schema.release |
| 477 | body: schema.release |
| 478 | isDraft: schema.release |
| 479 | isPrerelease: schema.release |
| 480 | isLatest: sql<boolean |
| 481 | authorUsername: schema.user |
| 482 | publishedAt: isoTimestamp(schema |
| 483 | createdAt: isoTimestamp(schema |
| 484 | updatedAt: isoTimestamp(schema |
| 485 | }) |
| 486 | .from(schema.release |
| 487 | .leftJoin(schema.user |
| 488 | .where(and(this |
| 489 | .orderBy(...order |
| 490 | } |
| 491 | |
| 492 | /** Commits come from git, not the row: a tag can be moved or deleted by a push at any time. Assets still uploading are left out. */ |
| 493 | private async expand |
| 494 | repository: AuthorizedRepository |
| 495 | releases: T |
| 496 | ) { |
| 497 | if (releases.length |
| 498 | |
| 499 | const [tags, |
| 500 | this.materializer.open |
| 501 | this.db |
| 502 | .select({ |
| 503 | releaseId: schema.releaseAsset |
| 504 | ...releaseAssetColumns, |
| 505 | }) |
| 506 | .from(schema.releaseAsset |
| 507 | .where( |
| 508 | and( |
| 509 | inArray( |
| 510 | schema.releaseAsset.releaseId |
| 511 | releases.map((release |
| 512 | ), |
| 513 | eq(schema.releaseAsset |
| 514 | ), |
| 515 | ) |
| 516 | .orderBy(asc(schema |
| 517 | ]); |
| 518 | const shas = |
| 519 | const viewerCanEdit = |
| 520 | |
| 521 | return releases.map |
| 522 | ...release, |
| 523 | commitSha: shas.get |
| 524 | assets: assets |
| 525 | .filter((asset) |
| 526 | .map(({ releaseId |
| 527 | viewerCanEdit, |
| 528 | })); |
| 529 | } |
| 530 | } |