Files
breeze/scripts/generate-sync-retry.mjs
T

91 lines
4.3 KiB
JavaScript

import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { checkLaws } from '../vendor/kryon/tools/bend-laws.mjs';
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const results = ['Success', 'InvalidUrl', 'NoAccount', 'PayloadFailed', 'ChallengeFailed',
'SignFailed', 'RequestFailed', 'AuthFailed', 'Unknown'];
const codes = ['SYNC_OK', 'SYNC_INVALID_URL', 'SYNC_NO_ACCOUNT', 'SYNC_PAYLOAD_FAILED',
'SYNC_CHALLENGE_FAILED', 'SYNC_SIGN_FAILED', 'SYNC_REQUEST_FAILED', 'SYNC_AUTH_FAILED'];
const attempts = ['Initial', 'First', 'Second', 'Third', 'Capped'];
const requiredLaws = ['success_resets', 'challenge_retries', 'request_retries',
'invalid_url_stops', 'no_account_stops', 'payload_failure_stops',
'signing_failure_stops', 'authentication_failure_stops', 'unknown_result_stops',
'saved_delay_matches', 'attempt_number_matches'];
export async function generateSyncRetry(packageDir, output, syncHeader) {
const proof = await checkLaws(path.join(packageDir, 'PROOF.bend'));
assert.deepEqual(proof.laws.toSorted(), requiredLaws.toSorted(), 'sync.retry.required_laws');
const decisions = proof.table('main.decide');
const delays = proof.table('main.delay');
const domain = names => names.map(name => `main.${name}`);
assert.deepEqual(decisions.domains, [domain(results), domain(attempts)], 'sync.retry.domains');
assert.deepEqual(delays.domains, [domain(attempts)], 'sync.retry.delay_domain');
const enumBody = fs.readFileSync(syncHeader, 'utf8').match(/typedef enum SyncResult\s*\{([^}]+)\}/)?.[1];
assert.ok(enumBody, 'sync.retry.result_enum_missing');
assert.deepEqual(enumBody.match(/\bSYNC_[A-Z_]+\b/g), codes, 'sync.retry.result_enum_changed');
const rows = decisions.rows.map(row => {
assert.equal(row.value.constructor, 'main.Decision');
assert.equal(row.value.fields.length, 3);
const [attempt, delay, action] = row.value.fields;
assert.ok(Number.isInteger(attempt) && attempt >= 0 && attempt <= 4);
assert.ok(Number.isInteger(delay) && delay >= 0 && delay <= 60);
assert.ok(action === 0 || action === 1);
return `{${attempt}, ${delay}, ${action}}`;
});
const body = [];
for (let index = 0; index < results.length; index++) {
body.push(` {${rows.slice(index * 5, index * 5 + 5).join(', ')}}, /* ${results[index]} */`);
}
const seconds = delays.rows.map(row => {
assert.ok(Number.isInteger(row.value) && row.value > 0 && row.value <= 60);
return row.value;
});
const text = `/* Generated by scripts/generate-sync-retry.mjs from proved Bend ${proof.version} policy. */
#ifndef SYNC_RETRY_TABLE_H
#define SYNC_RETRY_TABLE_H
#include "sync.h"
typedef struct RetryDecision {
int attempt;
int delay;
int needs_action;
} RetryDecision;
/* Reject changed wire-code ordering at the C boundary, including Plan 9. */
typedef char RetryResultCodesMatch[(${codes.map((code, index) => `${code} == ${index}`).join(' && ')}) ? 1 : -1];
static const RetryDecision retry_decisions[9][5] = {
${body.join('\n')}
};
static const int retry_delays[5] = {${seconds.join(', ')}};
#endif
`;
fs.mkdirSync(path.dirname(output), { recursive: true });
if (!fs.existsSync(output) || fs.readFileSync(output, 'utf8') !== text) {
const temporary = `${output}.${process.pid}.tmp`;
try {
fs.writeFileSync(temporary, text);
fs.renameSync(temporary, output);
} finally {
fs.rmSync(temporary, { force: true });
}
}
return proof;
}
if (process.argv[1] && pathToFileURL(path.resolve(process.argv[1])).href === import.meta.url) {
try {
assert.ok(process.argv.length <= 3, 'usage: node scripts/generate-sync-retry.mjs [output.h]');
const output = path.resolve(process.argv[2] ?? path.join(root, 'build/proofs/sync_retry_table.h'));
const proof = await generateSyncRetry(path.join(root, 'laws/sync_retry'), output,
path.join(root, 'vendor/kryon/include/sync.h'));
console.log(`sync.retry: ${proof.laws.length} Bend laws proved; 45 decisions generated`);
} catch (error) {
console.error(error.message);
process.exitCode = 1;
}
}