diff --git a/service/src/bridge/restore-reservation.test.ts b/service/src/bridge/restore-reservation.test.ts new file mode 100644 index 00000000..1dd7c6cf --- /dev/null +++ b/service/src/bridge/restore-reservation.test.ts @@ -0,0 +1,116 @@ +import { afterEach, beforeEach, expect, test } from 'bun:test'; +import Redis from 'ioredis'; + +import type { RestoreReservation } from './restore-reservation'; + +import { startTestRedis } from '../test/redis'; +import { RedisRestoreReservations } from './restore-reservation'; + +const intent: RestoreReservation = { + checkout: { + workerId: 'worker-1', workerIdentityId: 'a'.repeat(24), pairingGeneration: 1, + tenantId: 'tenant-1', checkoutIncarnation: '1'.repeat(64), device: '21', inode: '123', + }, + ownerScope: '2'.repeat(64), sourceIncarnation: '3'.repeat(64), + sourceGuard: { ownerId: 'assignment-1', quarantinedAt: '2026-01-01T00:00:00.000Z' }, + restoreId: '4'.repeat(64), destination: '5'.repeat(64), +}; +const checkout = intent.checkout; +const other = { ...checkout, inode: '124', checkoutIncarnation: '6'.repeat(64) }; +const key = `codeapi:bridge:restore-reservations:v1:${checkout.workerId}`; +let redis: Awaited>; +let peer: Redis; +let store: RedisRestoreReservations; +let contender: RedisRestoreReservations; + +beforeEach(async () => { + redis = await startTestRedis(); + peer = new Redis({ path: redis.options.path, retryStrategy: () => null, maxRetriesPerRequest: 0 }); + store = new RedisRestoreReservations(redis); + contender = new RedisRestoreReservations(peer); +}); + +afterEach(async () => { + peer?.disconnect(); + await redis?.closeTestServer(); +}); + +test('writer and restore contend atomically through separate connections', async () => { + expect(await store.enroll(checkout)).toBe(true); + const [writer, reservation] = await Promise.all([ + contender.claimWriter(checkout), store.reserve(intent), + ]); + if (reservation === 'reserved') { + expect(writer).toBeUndefined(); + } else { + expect(reservation).toBe('unavailable'); + expect(writer).toBe(1); + expect(await store.finishWriter(checkout, 2)).toBe(false); + expect(await store.reserve(intent)).toBe('unavailable'); + expect(await contender.finishWriter(checkout, 1)).toBe(true); + expect(await store.reserve(intent)).toBe('reserved'); + } + expect(await contender.claimWriter(checkout)).toBeUndefined(); + expect(await contender.has(intent)).toBe(true); + expect(await redis.pttl(key)).toBe(-1); +}); + +test('a retried writer completion cannot release a newer writer', async () => { + await store.enroll(checkout); + expect(await store.claimWriter(checkout)).toBe(1); + expect(await contender.finishWriter(checkout, 1)).toBe(true); + expect(await contender.claimWriter(checkout)).toBe(2); + expect(await store.finishWriter(checkout, 1)).toBe(false); + expect(await store.reserve(intent)).toBe('unavailable'); + expect(await contender.finishWriter(checkout, 2)).toBe(true); + expect(await store.reserve(intent)).toBe('reserved'); +}); + +test('same operation converges only on the exact paired source, guard and destination', async () => { + await store.enroll(checkout); + await store.enroll(other); + const replies = await Promise.all([store.reserve(intent), contender.reserve(intent)]); + expect(replies.sort()).toEqual(['existing', 'reserved']); + for (const wrong of [ + { checkout: { ...checkout, workerId: 'worker-2' } }, + { checkout: { ...checkout, workerIdentityId: 'b'.repeat(24) } }, + { checkout: { ...checkout, pairingGeneration: 2 } }, + { checkout: { ...checkout, tenantId: 'tenant-2' } }, + { checkout: { ...checkout, checkoutIncarnation: other.checkoutIncarnation } }, + { checkout: other }, + { ownerScope: '7'.repeat(64) }, + { sourceIncarnation: '8'.repeat(64) }, + { sourceGuard: { ...intent.sourceGuard, ownerId: 'assignment-2' } }, + { sourceGuard: { ...intent.sourceGuard, quarantinedAt: '2026-01-02T00:00:00.000Z' } }, + { restoreId: '9'.repeat(64) }, + { destination: 'a'.repeat(64) }, + ]) { + expect(await contender.has({ ...intent, ...wrong })).toBe(false); + expect(await contender.reserve({ ...intent, ...wrong })).toBe('unavailable'); + } + expect(await contender.enroll({ ...checkout, pairingGeneration: 2 })).toBe(false); + expect(await contender.enroll({ ...checkout, inode: '125' })).toBe(false); + expect(await contender.claimWriter(other)).toBe(1); + expect(await store.has(intent)).toBe(true); +}); + +test('missing, expiring or incomplete state never becomes an idle checkout', async () => { + expect(await store.has(intent)).toBe(false); + expect(await store.reserve(intent)).toBe('unavailable'); + expect(await store.claimWriter(checkout)).toBeUndefined(); + expect(await redis.exists(key)).toBe(0); + await store.enroll(checkout); + expect(await store.reserve(intent)).toBe('reserved'); + await redis.pexpire(key, 60_000); + expect(await store.has(intent)).toBe(false); + expect(await store.reserve(intent)).toBe('unavailable'); + expect(await store.claimWriter(checkout)).toBeUndefined(); + await redis.persist(key); + await redis.hdel(key, `operation:${intent.restoreId}`); + expect(await store.has(intent)).toBe(false); + expect(await store.reserve(intent)).toBe('unavailable'); + expect(await store.claimWriter(checkout)).toBeUndefined(); + await redis.hdel(key, `checkout:${checkout.device}:${checkout.inode}`); + expect(await store.enroll(checkout)).toBe(false); + expect(await store.reserve(intent)).toBe('unavailable'); +}); diff --git a/service/src/bridge/restore-reservation.ts b/service/src/bridge/restore-reservation.ts new file mode 100644 index 00000000..4288b901 --- /dev/null +++ b/service/src/bridge/restore-reservation.ts @@ -0,0 +1,151 @@ +import type Redis from 'ioredis'; + +import { isValidBridgeWorkerId } from '../../../packages/code/src/protocol'; + +export interface RestoreCheckout { + workerId: string; + workerIdentityId: string; + pairingGeneration: number; + tenantId: string; + /** Durable enrollment, not the bridge registration incarnation or a path. */ + checkoutIncarnation: string; + /** Device and inode of the pinned physical checkout; decimal strings. */ + device: string; + inode: string; +} + +export interface RestoreReservation { + checkout: RestoreCheckout; + ownerScope: string; + sourceIncarnation: string; + sourceGuard: Readonly<{ ownerId: string; quarantinedAt: string }>; + restoreId: string; + /** Deterministic reservation key; the lane name is `restore-${destination}`. */ + destination: string; +} + +const digest = /^[0-9a-f]{64}$/; +const decimal = /^(0|[1-9][0-9]{0,19})$/; +const maxRevision = 2147483647; + +function matches(value: string, pattern: RegExp): boolean { + return typeof value === 'string' && pattern.test(value); +} + +function text(value: string, max: number): boolean { + return typeof value === 'string' && value.length > 0 && value.length <= max; +} + +function checkoutKeys(input: RestoreCheckout) { + const { workerId, workerIdentityId, pairingGeneration, tenantId, checkoutIncarnation, device, inode } = input; + if ((typeof workerId !== 'string' || !isValidBridgeWorkerId(workerId)) || + !matches(workerIdentityId, /^[a-zA-Z0-9_-]{24}$/) || + !Number.isSafeInteger(pairingGeneration) || pairingGeneration < 0 || + !text(tenantId, 256) || !matches(checkoutIncarnation, digest) || + !matches(device, decimal) || !matches(inode, decimal) || inode === '0') { + throw new Error('Invalid restore checkout identity'); + } + return { + key: `codeapi:bridge:restore-reservations:v1:${workerId}`, + // An alias or pairing change must not put writers in a different gate. + field: `checkout:${device}:${inode}`, + enrollment: `enrollment:${checkoutIncarnation}`, + binding: JSON.stringify([workerId, workerIdentityId, pairingGeneration, tenantId, checkoutIncarnation, device, inode]) + ':', + }; +} + +// A single key and one mutating command per transition. Redis Lua does not roll +// back earlier writes if a subsequent write errors. +const transition = ` +local command, checkout, enrollment, binding, operation, exact = unpack(ARGV) +local key = KEYS[1] +local ttl = redis.call('PTTL', key) +if ttl ~= -1 and ttl ~= -2 then return 'unavailable' end +local state = redis.call('HGET', key, checkout) +local enrolled = redis.call('HGET', key, enrollment) +if command == 'enroll' then + if state or enrolled then return 'unavailable' end + redis.call('HSET', key, checkout, binding .. 'idle:0', enrollment, binding) + return 'enrolled' +end +if enrolled ~= binding or not state or string.sub(state, 1, #binding) ~= binding then + return 'unavailable' +end +state = string.sub(state, #binding + 1) +local idle = string.match(state, '^idle:(%d+)$') +if idle and (#idle > 10 or tonumber(idle) > 2147483647 or tostring(tonumber(idle)) ~= idle) then + return 'unavailable' +end +if command == 'claim' then + if not idle or tonumber(idle) == 2147483647 then return 'unavailable' end + local revision = tostring(tonumber(idle) + 1) + redis.call('HSET', key, checkout, binding .. 'writer:' .. revision) + return revision +end +if command == 'finish' then + if state ~= 'writer:' .. operation then return 'unavailable' end + redis.call('HSET', key, checkout, binding .. 'idle:' .. operation) + return 'finished' +end +local record = redis.call('HGET', key, operation) +exact = binding .. exact +local held = 'restore:' .. operation +if state == held and record == exact then return 'existing' end +if command ~= 'reserve' or not idle or record then return 'unavailable' end +redis.call('HSET', key, checkout, binding .. held, operation, exact) +return 'reserved' +`; + +/** Dark persistence only: no caller authentication, local quiet proof, or attach. + * A restore has no release transition here. Its exact retry is a read, not a + * second execution claim. Requires a durable, non-evicting Redis; do not enroll + * a previously enrolled checkout on missing state or use this after data loss. + */ +export class RedisRestoreReservations { + constructor(private readonly redis: Pick) {} + + /** Only for a newly verified physical checkout, never restart/recovery. */ + async enroll(checkout: RestoreCheckout): Promise { + return (await this.run(checkout, 'enroll')) === 'enrolled'; + } + + /** One competing writer per checkout. A lost reply does not free its claim. */ + async claimWriter(checkout: RestoreCheckout): Promise { + const reply = await this.run(checkout, 'claim'); + if (typeof reply === 'string' && /^[1-9][0-9]{0,9}$/.test(reply) && Number(reply) <= maxRevision) { + return Number(reply); + } + } + + /** The future caller must independently prove this exact writer stopped. */ + async finishWriter(checkout: RestoreCheckout, revision: number): Promise { + if (!Number.isInteger(revision) || revision < 1 || revision > maxRevision) return false; + return (await this.run(checkout, 'finish', String(revision))) === 'finished'; + } + + async reserve(input: RestoreReservation): Promise<'reserved' | 'existing' | 'unavailable'> { + const reply = await this.reservation(input, 'reserve'); + return reply === 'reserved' || reply === 'existing' ? reply : 'unavailable'; + } + + async has(input: RestoreReservation): Promise { + return (await this.reservation(input, 'lookup')) === 'existing'; + } + + private reservation(input: RestoreReservation, command: 'lookup' | 'reserve') { + const { checkout, ownerScope, sourceIncarnation, sourceGuard, restoreId, destination } = input; + if (![ownerScope, sourceIncarnation, restoreId, destination].every(value => matches(value, digest)) || + !text(sourceGuard?.ownerId, 512) || !text(sourceGuard?.quarantinedAt, 64) || + !Number.isFinite(Date.parse(sourceGuard.quarantinedAt))) { + throw new Error('Invalid restore reservation identity'); + } + return this.run(checkout, command, `operation:${restoreId}`, JSON.stringify([ + ownerScope, sourceIncarnation, sourceGuard.ownerId, sourceGuard.quarantinedAt, restoreId, destination, + ])); + } + + private run(checkout: RestoreCheckout, command: 'enroll' | 'claim' | 'finish' | 'lookup' | 'reserve', operation = '', exact = '') { + const { key, field, enrollment, binding } = checkoutKeys(checkout); + return this.redis.eval(transition, 1, key, command, field, enrollment, binding, operation, exact); + } +}