Separate account bookkeeping from report staging #90
No files matched your search
@@ -756,12 +756,12 @@ it('reuses IDs by exact account identity and avoids collisions with removed and
|
||||
expect(previous.accounts.map((account) => account.id)).toEqual(['00000000', '00000001']);
|
||||
generated.push(0, 1, 2, 2, 3);
|
||||
const stage = await createReportStage(snapshots, newer, previous.accounts);
|
||||
const accounts = [
|
||||
const accountsInWriteOrder = [
|
||||
{ name: '資産/../銀行:Ω', id: '00000001', nativeIndex: 1 },
|
||||
{ name: 'new:Ω', id: '00000002', nativeIndex: 2 },
|
||||
{ name: 'NEW:Ω', id: '00000003', nativeIndex: 3 }
|
||||
];
|
||||
for (const { name, nativeIndex } of accounts) {
|
||||
for (const { name, nativeIndex } of accountsInWriteOrder) {
|
||||
const json = JSON.stringify(nativeTransactionFixture(nativeIndex, [name]));
|
||||
await stage.transactions.insertOriginal(json);
|
||||
await stage.transactions.attachTransacted(json);
|
||||
@@ -770,16 +770,17 @@ it('reuses IDs by exact account identity and avoids collisions with removed and
|
||||
preparedAccountRowsFromExports([{ originalJson: json, transactedJson: json }])
|
||||
);
|
||||
}
|
||||
const accountsInCatalogOrder = accountsInWriteOrder.toReversed();
|
||||
await stage.publish(
|
||||
fixture(),
|
||||
accounts.map(({ name }) => ready(name)),
|
||||
accountsInCatalogOrder.map(({ name }) => ready(name)),
|
||||
journal
|
||||
);
|
||||
const publication = await selected();
|
||||
expect(publication.accounts.map(({ name, id }) => ({ name, id }))).toEqual(
|
||||
accounts.map(({ name, id }) => ({ name, id }))
|
||||
accountsInCatalogOrder.map(({ name, id }) => ({ name, id }))
|
||||
);
|
||||
for (const { id, nativeIndex } of accounts) {
|
||||
for (const { id, nativeIndex } of accountsInWriteOrder) {
|
||||
const page = await readAccountPage(publication, id, { order: 'asc', offset: 0 });
|
||||
expect(page?.rows.map(({ transaction }) => transaction.index)).toEqual([nativeIndex]);
|
||||
}
|
||||
@@ -943,30 +944,33 @@ it('keeps the stage until a failed connection close can be retried', async () =>
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ condition: 'incorrect row counts', summary: ready('assets:cash', 2), writeActivity: true },
|
||||
{ condition: 'incorrect row counts', summary: ready('assets:cash', 2), rowCountToWrite: 1 },
|
||||
{
|
||||
condition: 'written rows declared ambiguous',
|
||||
condition: 'an ambiguous account after even an empty write',
|
||||
summary: ambiguous('assets:cash'),
|
||||
writeActivity: true
|
||||
rowCountToWrite: 0
|
||||
},
|
||||
{
|
||||
condition: 'an ambiguous account declaring a numeric count',
|
||||
summary: { ...ambiguous('assets:cash'), rowCount: 0 },
|
||||
writeActivity: false
|
||||
rowCountToWrite: null
|
||||
}
|
||||
])('rejects $condition without replacing the saved report', async ({ summary, writeActivity }) => {
|
||||
await publish();
|
||||
const pinned = await selected();
|
||||
const stage = await createReportStage(snapshots, newer, pinned.accounts);
|
||||
if (writeActivity) {
|
||||
await importNativeExports(stage);
|
||||
await stage.writeRows('assets:cash', rows());
|
||||
])(
|
||||
'rejects $condition without replacing the saved report',
|
||||
async ({ summary, rowCountToWrite }) => {
|
||||
await publish();
|
||||
const pinned = await selected();
|
||||
const stage = await createReportStage(snapshots, newer, pinned.accounts);
|
||||
if (rowCountToWrite !== null) {
|
||||
await importNativeExports(stage, rowCountToWrite);
|
||||
await stage.writeRows('assets:cash', rows(rowCountToWrite));
|
||||
}
|
||||
await expect(stage.publish(fixture(), [summary], journal)).rejects.toSatisfy(
|
||||
safeError('Unable to prepare reports')
|
||||
);
|
||||
expect(await selected()).toEqual(pinned);
|
||||
}
|
||||
await expect(stage.publish(fixture(), [summary], journal)).rejects.toSatisfy(
|
||||
safeError('Unable to prepare reports')
|
||||
);
|
||||
expect(await selected()).toEqual(pinned);
|
||||
});
|
||||
);
|
||||
|
||||
it('leaves the saved report unchanged and removes only its own stage if replacement fails', async () => {
|
||||
await publish();
|
||||
|
||||
@@ -357,22 +357,7 @@ export async function createReportStage(
|
||||
|
||||
try {
|
||||
const request = reportRequestKey(run);
|
||||
if (previousAccounts != null && !isAccountCatalog(previousAccounts)) throw new Error();
|
||||
const prior = new Map((previousAccounts ?? []).map((account) => [account.name, account.id]));
|
||||
const used = new Set(prior.values());
|
||||
function accountId(name: string): string {
|
||||
const existing = prior.get(name);
|
||||
if (existing) return existing;
|
||||
let id: string;
|
||||
do {
|
||||
id = randomInt(36 ** 8)
|
||||
.toString(36)
|
||||
.padStart(8, '0');
|
||||
} while (used.has(id));
|
||||
used.add(id);
|
||||
prior.set(name, id);
|
||||
return id;
|
||||
}
|
||||
const stagedAccounts = createStagedAccounts(previousAccounts);
|
||||
await privateDirectory(snapshotDirectory, true);
|
||||
const uuid = randomUUID();
|
||||
const requestKey = request + uuid;
|
||||
@@ -384,17 +369,6 @@ export async function createReportStage(
|
||||
await runMigrations(database);
|
||||
transaction = await database.startTransaction().execute();
|
||||
const writer = transaction;
|
||||
const writtenAccounts = new Map<
|
||||
string,
|
||||
{ id: string; rowCount: number; summaryBuilder: AccountActivitySummaryBuilder }
|
||||
>();
|
||||
let currentName: string | undefined;
|
||||
|
||||
async function writePreparedRegisterRows(catalog: readonly StoredAccount[]) {
|
||||
for (const { name, rowCount: entryCount } of catalog) {
|
||||
if (entryCount !== null) await writeRegisterRowsAndPostingCount(writer, name, entryCount);
|
||||
}
|
||||
}
|
||||
|
||||
async function operation<T>(action: () => Promise<T>): Promise<T> {
|
||||
try {
|
||||
@@ -442,22 +416,7 @@ export async function createReportStage(
|
||||
}
|
||||
},
|
||||
writeRows(name, rows) {
|
||||
return operation(async () => {
|
||||
if (typeof name !== 'string' || !Array.isArray(rows)) throw new Error();
|
||||
if (currentName !== name) {
|
||||
if (writtenAccounts.has(name)) throw new Error();
|
||||
currentName = name;
|
||||
writtenAccounts.set(name, {
|
||||
id: accountId(name),
|
||||
rowCount: 0,
|
||||
summaryBuilder: new AccountActivitySummaryBuilder()
|
||||
});
|
||||
}
|
||||
const writtenAccount = writtenAccounts.get(name)!;
|
||||
await writeAccountRows(writer, name, writtenAccount.rowCount, rows);
|
||||
writtenAccount.summaryBuilder.append(rows);
|
||||
writtenAccount.rowCount += rows.length;
|
||||
});
|
||||
return operation(() => writeStagedAccountRows(writer, stagedAccounts, name, rows));
|
||||
},
|
||||
publish(overview, accounts, journal, investmentOverview) {
|
||||
return operation(async () => {
|
||||
@@ -468,35 +427,11 @@ export async function createReportStage(
|
||||
!Array.isArray(accounts)
|
||||
)
|
||||
throw new Error();
|
||||
const remaining = new Set(writtenAccounts.keys());
|
||||
const names = new Set<string>();
|
||||
const catalog: StoredAccount[] = [];
|
||||
const activitySummaries = new Map<string, AccountActivitySummary>();
|
||||
for (const account of accounts) {
|
||||
if (
|
||||
!isStorableAccountSummary(account) ||
|
||||
!summaryMatchesDate(account, overview.asOf) ||
|
||||
names.has(account.name)
|
||||
)
|
||||
throw new Error();
|
||||
names.add(account.name);
|
||||
const writtenAccount = writtenAccounts.get(account.name);
|
||||
remaining.delete(account.name);
|
||||
if (account.access === 'ambiguous') {
|
||||
if (writtenAccount !== undefined) throw new Error();
|
||||
} else {
|
||||
if ((writtenAccount?.rowCount ?? 0) !== account.rowCount) throw new Error();
|
||||
const summaryBuilder =
|
||||
writtenAccount?.summaryBuilder ?? new AccountActivitySummaryBuilder();
|
||||
activitySummaries.set(account.name, summaryBuilder.build());
|
||||
}
|
||||
catalog.push({
|
||||
...account,
|
||||
id: writtenAccount?.id ?? accountId(account.name),
|
||||
summary: storedSummary(account.summary)
|
||||
});
|
||||
}
|
||||
if (remaining.size) throw new Error();
|
||||
const { catalog, activitySummaries } = reconcileStagedAccounts(
|
||||
stagedAccounts,
|
||||
accounts,
|
||||
overview.asOf
|
||||
);
|
||||
await assertTransactionImportComplete(writer);
|
||||
const investmentOverviewJson =
|
||||
investmentOverview === undefined
|
||||
@@ -511,7 +446,10 @@ export async function createReportStage(
|
||||
}
|
||||
);
|
||||
await writeAccountActivitySummaries(writer, activitySummaries);
|
||||
await writePreparedRegisterRows(catalog);
|
||||
for (const { name, rowCount: entryCount } of catalog) {
|
||||
if (entryCount !== null)
|
||||
await writeRegisterRowsAndPostingCount(writer, name, entryCount);
|
||||
}
|
||||
await writer.commit().execute();
|
||||
await closeDatabase();
|
||||
const outcome = await replaceSavedReportIfNewer(
|
||||
@@ -538,3 +476,104 @@ export async function createReportStage(
|
||||
throw new Error('Unable to prepare reports');
|
||||
}
|
||||
}
|
||||
|
||||
interface WrittenAccountActivity {
|
||||
rowCount: number;
|
||||
summaryBuilder: AccountActivitySummaryBuilder;
|
||||
}
|
||||
|
||||
interface StagedAccounts {
|
||||
accountIdsByName: Map<string, string>;
|
||||
reservedAccountIds: Set<string>;
|
||||
writtenAccounts: Map<string, WrittenAccountActivity>;
|
||||
currentAccountName?: string;
|
||||
}
|
||||
|
||||
function createStagedAccounts(
|
||||
previousAccounts: readonly StoredAccount[] | null | undefined
|
||||
): StagedAccounts {
|
||||
if (previousAccounts != null && !isAccountCatalog(previousAccounts)) throw new Error();
|
||||
const accountIdsByName = new Map((previousAccounts ?? []).map(({ name, id }) => [name, id]));
|
||||
return {
|
||||
accountIdsByName,
|
||||
reservedAccountIds: new Set(accountIdsByName.values()),
|
||||
writtenAccounts: new Map()
|
||||
};
|
||||
}
|
||||
|
||||
async function writeStagedAccountRows(
|
||||
writer: ReportTransaction,
|
||||
stagedAccounts: StagedAccounts,
|
||||
name: string,
|
||||
rows: readonly PreparedAccountRow[]
|
||||
): Promise<void> {
|
||||
if (typeof name !== 'string' || !Array.isArray(rows)) throw new Error();
|
||||
let writtenAccount = stagedAccounts.writtenAccounts.get(name);
|
||||
if (writtenAccount) {
|
||||
if (stagedAccounts.currentAccountName !== name) throw new Error();
|
||||
} else {
|
||||
// Reserve in write order, even when the first batch is empty.
|
||||
reserveAccountId(stagedAccounts, name);
|
||||
writtenAccount = {
|
||||
rowCount: 0,
|
||||
summaryBuilder: new AccountActivitySummaryBuilder()
|
||||
};
|
||||
stagedAccounts.writtenAccounts.set(name, writtenAccount);
|
||||
stagedAccounts.currentAccountName = name;
|
||||
}
|
||||
await writeAccountRows(writer, name, writtenAccount.rowCount, rows);
|
||||
writtenAccount.summaryBuilder.append(rows);
|
||||
writtenAccount.rowCount += rows.length;
|
||||
}
|
||||
|
||||
function reconcileStagedAccounts(
|
||||
stagedAccounts: StagedAccounts,
|
||||
accounts: readonly PreparedAccountSummary[],
|
||||
asOf: OverviewData['asOf']
|
||||
) {
|
||||
const unmatchedWrites = new Set(stagedAccounts.writtenAccounts.keys());
|
||||
const catalogNames = new Set<string>();
|
||||
const catalog: StoredAccount[] = [];
|
||||
const activitySummaries = new Map<string, AccountActivitySummary>();
|
||||
for (const account of accounts) {
|
||||
if (
|
||||
!isStorableAccountSummary(account) ||
|
||||
!summaryMatchesDate(account, asOf) ||
|
||||
catalogNames.has(account.name)
|
||||
)
|
||||
throw new Error();
|
||||
catalogNames.add(account.name);
|
||||
const writtenAccount = stagedAccounts.writtenAccounts.get(account.name);
|
||||
unmatchedWrites.delete(account.name);
|
||||
if (account.access === 'ambiguous') {
|
||||
if (writtenAccount !== undefined) throw new Error();
|
||||
} else {
|
||||
if ((writtenAccount?.rowCount ?? 0) !== account.rowCount) throw new Error();
|
||||
const summaryBuilder = writtenAccount?.summaryBuilder ?? new AccountActivitySummaryBuilder();
|
||||
activitySummaries.set(account.name, summaryBuilder.build());
|
||||
}
|
||||
const id = reserveAccountId(stagedAccounts, account.name);
|
||||
catalog.push({
|
||||
...account,
|
||||
id,
|
||||
summary: storedSummary(account.summary)
|
||||
});
|
||||
}
|
||||
if (unmatchedWrites.size) throw new Error();
|
||||
return { catalog, activitySummaries };
|
||||
}
|
||||
|
||||
function reserveAccountId(stagedAccounts: StagedAccounts, name: string): string {
|
||||
const { accountIdsByName, reservedAccountIds } = stagedAccounts;
|
||||
const existing = accountIdsByName.get(name);
|
||||
if (existing) return existing;
|
||||
let id: string;
|
||||
do {
|
||||
id = randomInt(36 ** 8)
|
||||
.toString(36)
|
||||
.padStart(8, '0');
|
||||
} while (reservedAccountIds.has(id));
|
||||
reservedAccountIds.add(id);
|
||||
accountIdsByName.set(name, id);
|
||||
return id;
|
||||
}
|
||||
Reference in new issue
Block a user