Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
112 changes: 112 additions & 0 deletions service/src/bridge/checkpoint.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
/** Private receipt data. Admission/negotiation must write this alongside the
* exact ownership metadata and epoch; no production path enrolls it yet. */
export interface CheckpointAdmission {
version: 1;
epoch: string;
ownerScope: string;
tenantId: string;
pairingGeneration: string;
}

export interface CheckpointCandidate {
epoch: string;
commitment: string;
}

export function isCheckpointDigest(value: string | undefined): value is string {
return value != null && value.length === 64 && /^[a-f0-9]+$/.test(value);
}

function decimal(value: unknown): value is string {
return typeof value === 'string' && /^(0|[1-9][0-9]*)$/.test(value) && value.length <= 19;
}

export function readCheckpointAdmission(raw: string | undefined, epoch: string | undefined): CheckpointAdmission | undefined {
if (raw == null || !decimal(epoch) || epoch === '0') return;
try {
const value = JSON.parse(raw) as Partial<CheckpointAdmission> | null;
if (value?.version === 1 && value.epoch === epoch &&
typeof value.ownerScope === 'string' && isCheckpointDigest(value.ownerScope) &&
typeof value.tenantId === 'string' && value.tenantId.length > 0 &&
decimal(value.pairingGeneration)) return value as CheckpointAdmission;
} catch { /* Malformed optional metadata never blocks ordinary work. */ }
}

export interface CheckpointContext {
keys: string[];
args: string[];
epoch: string;
}

type CheckpointVote =
| { kind: 'settlement'; candidate: CheckpointCandidate; digest: string; ackKey: string }
| { kind: 'cleanup'; candidate: CheckpointCandidate }
| { kind: 'finalization'; digest: string; key: string; outcome: string; assignment: string };

/** Append an advisory transition to an existing Redis CAS. The caller still
* owns all normal commit, cleanup and release decisions. Keys/args match the
* layout constructed by RedisBridgeStore.checkpointContext. */
export function checkpointTransition(
keys: string[], args: (string | number)[], context: CheckpointContext | undefined, vote: CheckpointVote,
): string[] {
if (context == null || (vote.kind !== 'finalization' &&
(vote.candidate.epoch !== context.epoch || !isCheckpointDigest(vote.candidate.commitment)))) return [];
const keyOffset = keys.length;
const argOffset = args.length;
const k = (i: number) => `KEYS[${keyOffset + i}]`;
const a = (i: number) => `ARGV[${argOffset + i}]`;
const receipt = k(1);
const field = (name: string) => `redis.pcall('HGET', ${receipt}, '${name}')`;
const get = (i: number) => `redis.pcall('GET', ${k(i)})`;
const put = (name: string, value: string) => `redis.call('HSET', ${receipt}, '${name}', ${value})`;
const value = a(10);
if (vote.kind === 'finalization') keys.push(...context.keys, vote.key);
else if (vote.kind === 'settlement') keys.push(...context.keys, vote.ackKey);
else keys.push(...context.keys);
args.push(...context.args, ...(vote.kind === 'finalization' ? [vote.digest, vote.outcome, vote.assignment]
: vote.kind === 'settlement' ? [vote.candidate.commitment, vote.digest] : [vote.candidate.commitment]));
// The optional reads use pcall and fail closed on wrong types. No proof
// writes can create a receipt, and HSET leaves its original expiry intact.
return [
'do',
' local function eligible()',
` if ${field('metadata')} ~= ${a(1)} or ${field('checkpointAdmissionV1')} ~= ${a(2)} or ${field('epoch')} ~= ${a(3)} then return false end`,
` if ${get(2)} ~= ${a(3)} or ${get(3)} ~= ${a(4)} or redis.call('EXISTS', ${k(4)}) ~= 0 then return false end`,
` if ${get(5)} ~= ${a(5)} or ${get(6)} ~= ${a(6)} then return false end`,
` if (${get(7)} or '0') ~= ${a(7)} or redis.call('EXISTS', ${k(8)}, ${k(9)}) ~= 0 then return false end`,
` local raw = ${get(10)}`,
" if type(raw) ~= 'string' then return false end",
' local ok, registration = pcall(cjson.decode, raw)',
" return ok and type(registration) == 'table' and type(registration.binding) == 'table'",
` and registration.incarnationId == ${a(5)} and registration.identityId == ${a(6)} and registration.binding.tenantId == ${a(8)}`,
' end',
` if eligible() and ${field('checkpointCertificateV1')} == false then`,
...(vote.kind === 'settlement' ? [
` if ${get(11)} == ${a(4)} and ${field('checkpointCommitment')} == false and ${field('localCleanup')} == false then`,
` redis.call('HSET', ${receipt}, 'checkpointCommitment', ${value}, 'checkpointSettlementDigest', ${a(11)}, 'checkpointReceiptDigest', ${a(9)})`,
' end',
] : [
` local commitment = ${field('checkpointCommitment')}`,
` local digest = ${field('checkpointSettlementDigest')}`,
" if type(commitment) == 'string' and type(digest) == 'string' and",
` ${field('checkpointReceiptDigest')} == ${a(9)} and`,
...(vote.kind === 'cleanup' ? [
` commitment == ${value} and ${field('localCleanup')} == false then`,
` ${put('checkpointCleanupVote', 'digest')}`,
] : [
` digest == ${value} and ${field('resultCommitted')} == false and`,
` redis.pcall('HGET', ${k(11)}, 'state') == 'completed' and`,
` redis.pcall('HGET', ${k(11)}, 'outcome') == ${a(11)} and`,
` redis.pcall('HGET', ${k(11)}, 'assignment') == ${a(12)} then`,
` ${put('checkpointFinalizationVote', 'digest')}`,
]),
` if ${field('checkpointCleanupVote')} == digest and ${field('checkpointFinalizationVote')} == digest then`,
" local time = redis.call('TIME')",
` ${put('checkpointCertificateV1', `cjson.encode({version = 1, epoch = ${a(3)}, commitment = commitment, settlementDigest = digest, committedAtMs = tonumber(time[1]) * 1000 + math.floor(tonumber(time[2]) / 1000)})`)}`,
' end',
' end',
]),
' end',
'end',
];
}
Loading
Loading