| 1 | import { Injectable, Logger } from '@nestjs/common'; |
| 2 | import { createHash } |
| 3 | import { pipeline } |
| 4 | import { setTimeout as |
| 5 | |
| 6 | import type { GitRequestBody |
| 7 | |
| 8 | import { encodeEntryHeader } |
| 9 | import { WalStoreService } |
| 10 | import { NonFastForwardError, WalContentionError |
| 11 | import { |
| 12 | applyTransitions, |
| 13 | emptyIndex, |
| 14 | ZERO_OID, |
| 15 | type RefTransition, |
| 16 | type WalIndex, |
| 17 | } from './wal.types.js'; |
| 18 | import { createUlid } |
| 19 | |
| 20 | const MAX_ATTEMPTS = 8 |
| 21 | const BASE_BACKOFF_MS = 50 |
| 22 | const MAX_BACKOFF_MS = 1000 |
| 23 | |
| 24 | export interface CommitPushOptions |
| 25 | repoId: string; |
| 26 | transitions: RefTransition |
| 27 | /** The whole request body; the packfile starts at `packOffset`. */ |
| 28 | body: GitRequestBody |
| 29 | packOffset: number; |
| 30 | pushedBy?: string |
| 31 | } |
| 32 | |
| 33 | export interface CommitPushResult |
| 34 | seq: number; |
| 35 | ulid: string; |
| 36 | } |
| 37 | |
| 38 | @Injectable() |
| 39 | export class PushTransactionService |
| 40 | private readonly logger |
| 41 | |
| 42 | constructor(private readonly |
| 43 | |
| 44 | async commitPush({ |
| 45 | repoId, |
| 46 | transitions, |
| 47 | body, |
| 48 | packOffset, |
| 49 | pushedBy = null, |
| 50 | }: CommitPushOptions |
| 51 | const ulid = |
| 52 | const packSize = |
| 53 | const packHash = |
| 54 | await pipeline(body |
| 55 | const packSha = |
| 56 | |
| 57 | // Durable before the loop: expensive, idempotent, and unaffected by ordering. |
| 58 | // An entry orphaned by a failed transaction is garbage, never corruption. |
| 59 | await this.store |
| 60 | repoId, |
| 61 | ulid, |
| 62 | encodeEntryHeader({ ulid, |
| 63 | body, |
| 64 | packOffset, |
| 65 | ); |
| 66 | |
| 67 | for (let attempt |
| 68 | const current = |
| 69 | const index = |
| 70 | |
| 71 | if (index.layers |
| 72 | return { seq: |
| 73 | } |
| 74 | |
| 75 | this.assertFastForward(index |
| 76 | |
| 77 | const next: |
| 78 | seq: index.seq |
| 79 | compactedThroughSeq: index.compactedThroughSeq |
| 80 | refs: applyTransitions(index |
| 81 | layers: [...index |
| 82 | }; |
| 83 | |
| 84 | if (await this |
| 85 | return { seq: |
| 86 | } |
| 87 | |
| 88 | this.logger.debug |
| 89 | await sleep(backoffMs |
| 90 | } |
| 91 | |
| 92 | throw new WalContentionError( |
| 93 | } |
| 94 | |
| 95 | private assertFastForward(index |
| 96 | for (const transition |
| 97 | const live = |
| 98 | if (!live.equals |
| 99 | throw new NonFastForwardError( |
| 100 | } |
| 101 | } |
| 102 | } |
| 103 | } |
| 104 | |
| 105 | function seqOfLayer(index: |
| 106 | return ( |
| 107 | index.compactedThroughSeq + |
| 108 | index.layers.findIndex |
| 109 | 1 |
| 110 | ); |
| 111 | } |
| 112 | |
| 113 | function backoffMs(attempt: |
| 114 | const ceiling = |
| 115 | return Math.round |
| 116 | } |