/** * Gapless ledger sequences + hash-chain heads, one document per * (skrType, fiscalYear). Allocation runs inside the caller's transaction * session, so an aborted posting rolls the $inc back and gaplessness holds. */ import * as plugins from './plugins.js'; import { getDbSync, type TDbSession } from './skr.database.js'; import { genesisHash } from './core/core.hash.js'; import { SequenceConflictError } from './skr.errors.js'; import type { TSKRType } from './skr.types.js'; export const LEDGER_SEQUENCE_COLLECTION = 'LedgerSequence'; /** The counter and chain head of one (skrType, fiscalYear). */ @plugins.nosqldb.compoundIndex({ name: 'skrType_1_fiscalYear_1', key: { skrType: 1, fiscalYear: 1 }, options: { unique: true }, }) @plugins.nosqldb.Collection(() => getDbSync(), { collectionName: LEDGER_SEQUENCE_COLLECTION }) export class LedgerSequence extends plugins.nosqldb.SmartDataDbDoc { @plugins.nosqldb.svDb() public skrType!: TSKRType; @plugins.nosqldb.svDb() public fiscalYear!: number; @plugins.nosqldb.svDb() public value!: number; @plugins.nosqldb.svDb() public headHash!: string; } export interface ILedgerSequenceAllocation { sequenceNumber: number; prevHash: string; } export interface ILedgerSequenceState { skrType: TSKRType; fiscalYear: number; value: number; headHash: string; } /** * Allocate the next sequence number and return the current chain head. * Must run inside a transaction — the $inc participates in the rollback. */ export async function allocateSequence( skrType: TSKRType, fiscalYear: number, session: TDbSession, ): Promise { const result = await LedgerSequence.atomicFindOneAndUpdate( { skrType, fiscalYear }, { $inc: { value: 1 }, $setOnInsert: { headHash: genesisHash(skrType, fiscalYear) } }, { upsert: true, returnDocument: 'after', session }, ); if (result.status === 'not_matched') { throw new Error(`Sequence allocation failed for ${skrType}/${fiscalYear}`); } return { sequenceNumber: result.document.value, prevHash: result.document.headHash }; } /** * Compare-and-swap the chain head. The filter on the old head serializes * concurrent posters — a lost race aborts the surrounding transaction. */ export async function advanceHead( skrType: TSKRType, fiscalYear: number, prevHash: string, newHash: string, session: TDbSession, ): Promise { const result = await LedgerSequence.atomicUpdate( { skrType, fiscalYear, headHash: prevHash }, { $set: { headHash: newHash } }, { session }, ); if (result.matchedCount !== 1) { throw new SequenceConflictError(skrType, fiscalYear); } } export async function getSequenceState( skrType: TSKRType, fiscalYear: number, ): Promise { const doc = await LedgerSequence.getInstance({ skrType, fiscalYear }); if (!doc) return null; return { skrType, fiscalYear, value: doc.value, headHash: doc.headHash }; }