{{ message }}
Repository navigation
Expand file tree
/
Copy pathrepo-ref-maintenance-real-git.test.ts
More file actions
455 lines (416 loc) · 15.9 KB
/
Copy pathrepo-ref-maintenance-real-git.test.ts
File metadata and controls
455 lines (416 loc) · 15.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
import { execFileSync } from 'node:child_process'
import { cp, mkdir, mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterAll, afterEach, beforeAll, describe, expect, it } from 'vitest'
import { countLooseRefs } from '../../shared/loose-ref-count'
import { RepoRefMaintenance } from '../../shared/repo-ref-maintenance'
import { PACK_INDEX_MAINTENANCE_COOLDOWN_MS } from '../../shared/repo-pack-index-maintenance-policy'
import {
_resetLocalRepoRefMaintenanceForTests,
createLocalRepoRefMaintenanceTarget,
getLocalRepoRefMaintenance,
setRepoMaintenanceActivityProbe
} from './local-repo-ref-maintenance'
import { forceDeleteLocalBranch } from './worktree-branch-removal'
import { maintainRepoPackIndex, PACK_INDEX_THRESHOLD } from './repo-pack-index-maintenance'
const roots: string[] = []
// Let the capped deferral ladder outlast three real pack-refs runs.
const QUIET_MS = 25
const THRESHOLD = 20
let packFixtureRoot = ''
let packFixtureBlobs: string[] = []
function git(cwd: string, args: string[], input?: string): string {
return execFileSync('git', args, {
cwd,
encoding: 'utf8',
input,
stdio: ['pipe', 'pipe', 'pipe']
}).trim()
}
function hasWriteOption(option: string): boolean {
try {
git(process.cwd(), ['multi-pack-index', 'write', '-h'])
} catch (error) {
if (typeof error === 'object' && error !== null) {
return (
('stderr' in error && String(error.stderr).includes(option)) ||
('stdout' in error && String(error.stdout).includes(option))
)
}
}
return false
}
async function createFragmentedPacks(repoPath: string): Promise<string[]> {
await cp(
join(packFixtureRoot, '.git', 'objects', 'pack'),
join(repoPath, '.git', 'objects', 'pack'),
{
recursive: true
}
)
return packFixtureBlobs
}
beforeAll(async () => {
packFixtureRoot = await mkdtemp(join(tmpdir(), 'orca-fragmented-packs-'))
git(packFixtureRoot, ['init', '--quiet'])
packFixtureBlobs = await buildFragmentedPacks(packFixtureRoot)
})
afterAll(async () => {
await rm(packFixtureRoot, { recursive: true, force: true })
})
async function buildFragmentedPacks(repoPath: string): Promise<string[]> {
const objects = join(repoPath, '.git', 'objects')
const files = Array.from({ length: PACK_INDEX_THRESHOLD }, (_, index) => `packed-${index}`)
await Promise.all(files.map((file) => writeFile(join(repoPath, file), `${file}\n`)))
const blobs = git(repoPath, ['hash-object', '-w', ...files]).split('\n')
for (const blob of blobs) {
git(repoPath, ['pack-objects', join(objects, 'pack', 'pack')], `${blob}\n`)
await rm(join(objects, blob.slice(0, 2), blob.slice(2)))
}
return blobs
}
function maintainIndex(repoPath: string) {
return maintainRepoPackIndex({
repoPath,
commonDir: join(repoPath, '.git'),
signal: new AbortController().signal,
span: { setAttribute: () => {} },
canWrite: () => true
})
}
async function createRepo(looseRefs: number): Promise<{ repoPath: string; refsDir: string }> {
const root = await mkdtemp(join(tmpdir(), 'orca-ref-maintenance-git-'))
roots.push(root)
const repoPath = join(root, 'repo')
execFileSync('git', ['init', '--quiet', repoPath])
git(repoPath, ['symbolic-ref', 'HEAD', 'refs/heads/main'])
git(repoPath, ['config', 'user.email', 'test@example.com'])
git(repoPath, ['config', 'user.name', 'Test User'])
await writeFile(join(repoPath, 'file.txt'), 'one\n')
git(repoPath, ['add', 'file.txt'])
git(repoPath, ['commit', '--quiet', '-m', 'initial'])
const head = git(repoPath, ['rev-parse', 'HEAD'])
// Written directly: `update-ref` for thousands of refs is the slow part of the fixture.
const namespace = join(repoPath, '.git', 'refs', 'remotes', 'origin')
await mkdir(namespace, { recursive: true })
for (let index = 0; index < looseRefs; index += 1) {
await writeFile(join(namespace, `branch-${index}`), `${head}\n`)
}
return { repoPath, refsDir: join(repoPath, '.git', 'refs') }
}
function createMaintenance(
onPackRefs: () => void = () => {},
now?: () => number
): {
maintenance: RepoRefMaintenance
arm: (repoPath: string) => void
} {
const maintenance = new RepoRefMaintenance({
quietPeriodMs: QUIET_MS,
looseRefThreshold: THRESHOLD,
...(now ? { now } : {})
})
return {
maintenance,
arm: (repoPath: string) => {
const target = createLocalRepoRefMaintenanceTarget({
key: `local::${repoPath}`,
repoPath
})
maintenance.arm({
...target,
packRefs: async (signal) => {
onPackRefs()
await target.packRefs(signal)
}
})
}
}
}
async function settle(maintenance: RepoRefMaintenance): Promise<void> {
await new Promise((resolve) => setTimeout(resolve, QUIET_MS * 4))
await maintenance.whenAttemptSettled()
}
/** Deferred repos re-arm for another quiet period, so drain rather than count rounds. */
async function settleUntil(
maintenance: RepoRefMaintenance,
done: () => Promise<boolean>
): Promise<void> {
for (let round = 0; round < 100; round += 1) {
if (await done()) {
return
}
await settle(maintenance)
}
}
afterEach(async () => {
_resetLocalRepoRefMaintenanceForTests()
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })))
})
describe('idle ref maintenance against real Git', () => {
it('indexes fragmented packs without rewriting objects or requiring loose-ref debt', async () => {
const { repoPath } = await createRepo(0)
git(repoPath, ['config', 'maintenance.auto', 'true'])
git(repoPath, ['config', 'gc.auto', '6700'])
const objects = join(repoPath, '.git', 'objects')
const packs = join(objects, 'pack')
const blobs = await createFragmentedPacks(repoPath)
const originalPacks = (await readdir(packs)).sort()
const lock = join(packs, 'multi-pack-index.lock')
await writeFile(lock, 'another writer')
const blocked = createMaintenance()
blocked.arm(repoPath)
await settle(blocked.maintenance)
blocked.maintenance.dispose()
await expect(readFile(lock, 'utf8')).resolves.toBe('another writer')
await expect(readFile(join(packs, 'multi-pack-index'))).rejects.toMatchObject({
code: 'ENOENT'
})
await rm(lock)
const { maintenance, arm } = createMaintenance()
arm(repoPath)
await settle(maintenance)
maintenance.dispose()
const index = await readFile(join(packs, 'multi-pack-index'))
expect(index.subarray(0, 4).toString()).toBe('MIDX')
expect((await readdir(packs)).filter((name) => name !== 'multi-pack-index').sort()).toEqual(
originalPacks
)
expect(git(repoPath, ['multi-pack-index', 'verify'])).toBe('')
expect(git(repoPath, ['-c', 'core.multiPackIndex=true', 'cat-file', '-p', blobs[0]])).toBe(
'packed-0'
)
expect(
git(repoPath, [
'-c',
'core.multiPackIndex=true',
'cat-file',
'-p',
blobs[PACK_INDEX_THRESHOLD - 1]
])
).toBe(`packed-${PACK_INDEX_THRESHOLD - 1}`)
await expect(readFile(join(repoPath, '.git', 'packed-refs'))).rejects.toMatchObject({
code: 'ENOENT'
})
})
it('refreshes new packs during ref cooldown and keeps readers working between writes', async () => {
const { repoPath } = await createRepo(0)
const blobs = await createFragmentedPacks(repoPath)
const packs = join(repoPath, '.git', 'objects', 'pack')
let clock = 0
const { maintenance, arm } = createMaintenance(
() => {},
() => clock
)
arm(repoPath)
await settle(maintenance)
expect((await readFile(join(packs, 'multi-pack-index'))).readUInt32BE(8)).toBe(
PACK_INDEX_THRESHOLD
)
const added = git(repoPath, ['hash-object', '-w', '--stdin'], 'new fetched object\n')
git(repoPath, ['pack-objects', join(packs, 'pack')], `${added}\n`)
await rm(join(repoPath, '.git', 'objects', added.slice(0, 2), added.slice(2)))
expect(git(repoPath, ['cat-file', '-p', added])).toBe('new fetched object')
expect(git(repoPath, ['cat-file', '-p', blobs[0]])).toBe('packed-0')
clock = PACK_INDEX_MAINTENANCE_COOLDOWN_MS + 1
arm(repoPath)
await settle(maintenance)
maintenance.dispose()
expect((await readFile(join(packs, 'multi-pack-index'))).readUInt32BE(8)).toBe(
PACK_INDEX_THRESHOLD + 1
)
expect(git(repoPath, ['multi-pack-index', 'verify'])).toBe('')
await expect(readFile(join(repoPath, '.git', 'packed-refs'))).rejects.toMatchObject({
code: 'ENOENT'
})
})
it.skipIf(!hasWriteOption('bitmap'))(
'preserves a real MIDX bitmap and its index byte for byte',
async () => {
const { repoPath } = await createRepo(0)
await createFragmentedPacks(repoPath)
const packs = join(repoPath, '.git', 'objects', 'pack')
git(repoPath, ['pack-objects', '--revs', join(packs, 'pack')], 'HEAD\n')
git(repoPath, ['multi-pack-index', 'write', '--bitmap'])
const metadata = (await readdir(packs)).filter((name) => name.startsWith('multi-pack-index'))
expect(metadata.some((name) => name.endsWith('.bitmap'))).toBe(true)
const before = await Promise.all(metadata.map((name) => readFile(join(packs, name))))
await expect(maintainIndex(repoPath)).resolves.toBe('protected')
const after = await Promise.all(metadata.map((name) => readFile(join(packs, name))))
expect(after).toEqual(before)
}
)
it.skipIf(!hasWriteOption('incremental'))(
'preserves a real incremental MIDX chain and its layers',
async () => {
const { repoPath } = await createRepo(0)
await createFragmentedPacks(repoPath)
const chain = join(repoPath, '.git', 'objects', 'pack', 'multi-pack-index.d')
git(repoPath, ['multi-pack-index', 'write', '--incremental'])
const metadata = (await readdir(chain)).sort()
expect(metadata).toContain('multi-pack-index-chain')
const before = await Promise.all(metadata.map((name) => readFile(join(chain, name))))
await expect(maintainIndex(repoPath)).resolves.toBe('protected')
expect((await readdir(chain)).sort()).toEqual(metadata)
expect(await Promise.all(metadata.map((name) => readFile(join(chain, name))))).toEqual(before)
}
)
it('packs a backlogged repository down to zero loose refs', async () => {
const { repoPath, refsDir } = await createRepo(THRESHOLD + 30)
const { maintenance, arm } = createMaintenance()
await expect(countLooseRefs(refsDir, 10_000)).resolves.toMatchObject({
count: THRESHOLD + 31
})
arm(repoPath)
await settle(maintenance)
maintenance.dispose()
await expect(countLooseRefs(refsDir, 10_000)).resolves.toEqual({ count: 0, saturated: false })
expect(git(repoPath, ['for-each-ref', '--format=%(refname)']).split('\n')).toHaveLength(
THRESHOLD + 31
)
expect(git(repoPath, ['rev-parse', '--verify', 'refs/remotes/origin/branch-0'])).toMatch(
/^[0-9a-f]{40}$/
)
}, 30_000)
it('leaves a healthy repository untouched', async () => {
const { repoPath, refsDir } = await createRepo(2)
let packed = 0
const { maintenance, arm } = createMaintenance(() => {
packed += 1
})
arm(repoPath)
await settle(maintenance)
maintenance.dispose()
expect(packed).toBe(0)
await expect(countLooseRefs(refsDir, 10_000)).resolves.toMatchObject({ count: 3 })
}, 30_000)
it('honours maintenance.auto=false in the repository config', async () => {
const { repoPath, refsDir } = await createRepo(THRESHOLD + 30)
git(repoPath, ['config', 'maintenance.auto', 'false'])
let packed = 0
const { maintenance, arm } = createMaintenance(() => {
packed += 1
})
arm(repoPath)
await settle(maintenance)
maintenance.dispose()
expect(packed).toBe(0)
await expect(countLooseRefs(refsDir, 10_000)).resolves.toMatchObject({
count: THRESHOLD + 31
})
}, 30_000)
it('runs one repository at a time even when several go quiet together', async () => {
const repos = await Promise.all([
createRepo(THRESHOLD + 5),
createRepo(THRESHOLD + 5),
createRepo(THRESHOLD + 5)
])
let concurrent = 0
let peak = 0
const maintenance = new RepoRefMaintenance({
quietPeriodMs: QUIET_MS,
looseRefThreshold: THRESHOLD
})
for (const { repoPath } of repos) {
const target = createLocalRepoRefMaintenanceTarget({
key: `local::${repoPath}`,
repoPath
})
maintenance.arm({
...target,
packRefs: async (signal) => {
concurrent += 1
peak = Math.max(peak, concurrent)
try {
await target.packRefs(signal)
} finally {
concurrent -= 1
}
}
})
}
const allPacked = async (): Promise<boolean> => {
const counts = await Promise.all(repos.map(({ refsDir }) => countLooseRefs(refsDir, 10_000)))
return counts.every((scan) => scan.count === 0)
}
await settleUntil(maintenance, allPacked)
maintenance.dispose()
expect(peak).toBe(1)
for (const { refsDir } of repos) {
await expect(countLooseRefs(refsDir, 10_000)).resolves.toEqual({
count: 0,
saturated: false
})
}
}, 60_000)
})
describe('yielding the repository to work that deletes refs', () => {
it('waits for the packed-refs lock and succeeds while the prune continues', async () => {
// Await the packed-refs rewrite window; killing the later prune can strand per-ref locks.
const { repoPath } = await createRepo(0)
git(repoPath, ['branch', 'doomed'])
const head = git(repoPath, ['rev-parse', 'refs/heads/doomed'])
let packing = false
let releaseLock: (() => void) | undefined
_resetLocalRepoRefMaintenanceForTests({ quietPeriodMs: QUIET_MS, looseRefThreshold: 1 })
setRepoMaintenanceActivityProbe(() => false)
getLocalRepoRefMaintenance().arm({
key: `local::${repoPath}`,
resolveRefsDirectory: async () => join(repoPath, '.git', 'refs'),
packRefs: async (lock) => {
packing = true
lock.setHeld(true)
await new Promise<void>((resolve) => {
releaseLock = () => {
lock.setHeld(false)
resolve()
}
})
}
})
for (let attempt = 0; attempt < 200 && !packing; attempt += 1) {
await new Promise((resolve) => setTimeout(resolve, QUIET_MS))
}
expect(packing).toBe(true)
let deleted = false
const deletion = forceDeleteLocalBranch(repoPath, 'doomed', head).then(() => {
deleted = true
})
await new Promise((resolve) => setTimeout(resolve, QUIET_MS * 4))
expect(deleted).toBe(false)
expect(git(repoPath, ['branch', '--list', 'doomed'])).toContain('doomed')
releaseLock?.()
await deletion
expect(deleted).toBe(true)
expect(git(repoPath, ['branch', '--list', 'doomed'])).toBe('')
}, 30_000)
it('does not block the caller once the rewrite window has closed', async () => {
const { repoPath } = await createRepo(0)
git(repoPath, ['branch', 'doomed'])
const head = git(repoPath, ['rev-parse', 'refs/heads/doomed'])
let pruning = false
let finishPrune: (() => void) | undefined
_resetLocalRepoRefMaintenanceForTests({ quietPeriodMs: QUIET_MS, looseRefThreshold: 1 })
setRepoMaintenanceActivityProbe(() => false)
getLocalRepoRefMaintenance().arm({
key: `local::${repoPath}`,
resolveRefsDirectory: async () => join(repoPath, '.git', 'refs'),
packRefs: async (lock) => {
lock.setHeld(true)
lock.setHeld(false)
pruning = true
await new Promise<void>((resolve) => {
finishPrune = resolve
})
}
})
for (let attempt = 0; attempt < 200 && !pruning; attempt += 1) {
await new Promise((resolve) => setTimeout(resolve, QUIET_MS))
}
const startedAt = Date.now()
await expect(forceDeleteLocalBranch(repoPath, 'doomed', head)).resolves.toBeUndefined()
expect(Date.now() - startedAt).toBeLessThan(2_000)
finishPrune?.()
}, 30_000)
})
You can’t perform that action at this time.
