Files
breeze/scripts/generate-sync-retry.mjs
T
waozi b5356aaac7 Port Inbe screens, storage, and platform hosts to Ziran
Replace the remaining .kry and C application sources with Ziran modules,
move vendored dependencies to their current pointers, and add Ziran tests for
the ported hosts and policies.
2026-09-27 15:40:52 -03:00

140 lines
6.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 './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, resultModule) {
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(resultModule, 'utf8').match(/SyncResult\s*::\s*enum\s*\{([^}]+)\}/)?.[1];
assert.ok(enumBody, 'sync.retry.result_enum_missing');
const enumEntries = enumBody.split('\n').map(entry => entry.replace(/\/\/.*/, '').trim()).filter(Boolean);
assert.deepEqual(enumEntries.map(entry => entry.match(/^(SYNC_[A-Z_]+)/)?.[1]),
codes, 'sync.retry.result_enum_changed');
let wireCode = -1;
for (let index = 0; index < enumEntries.length; index++) {
const entry = enumEntries[index].match(/^SYNC_[A-Z_]+\s*::\s*(-?\d+)\s*;?$/);
assert.ok(entry, 'sync.retry.result_enum_changed');
wireCode = Number(entry[1]);
assert.equal(wireCode, index, '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 };
});
assert.equal(rows.length, results.length * attempts.length,
'sync.retry.decision_count');
const seconds = delays.rows.map(row => {
assert.ok(Number.isInteger(row.value) && row.value > 0 && row.value <= 60);
return row.value;
});
assert.equal(seconds.length, attempts.length, 'sync.retry.delay_count');
const decisionCode = [];
for (let result = 0; result < results.length; result++) {
const indent = result === results.length - 1 ? '' : ' ';
if (result !== results.length - 1) {
decisionCode.push(` if result == ${result} {`);
}
decisionCode.push(`${indent} // ${results[result]}`);
for (let attempt = 0; attempt < attempts.length; attempt++) {
const row = rows[result * attempts.length + attempt];
if (attempt !== attempts.length - 1) {
decisionCode.push(`${indent} if attempt == ${attempt} {`);
decisionCode.push(`${indent} return RetryDecision.{${row.attempt}, ${row.delay}, ${row.action}}`);
decisionCode.push(`${indent} }`);
} else {
decisionCode.push(`${indent} return RetryDecision.{${row.attempt}, ${row.delay}, ${row.action}}`);
}
}
if (result !== results.length - 1) {
decisionCode.push(' }');
}
}
const delayCode = seconds.flatMap((delay, index) =>
index === seconds.length - 1
? [` return ${delay}.0`]
: [` if attempt == ${index} {`, ` return ${delay}.0`, ' }']);
const text = `#import, file "../storage/sync_result.zi";
// Generated by scripts/generate-sync-retry.mjs from proved Bend ${proof.version} policy.
// SyncResult wire codes are verified against src/storage/sync_result.zi.
RetryDecision :: struct {
attempt: s32
delay: s32
needs_action: s32
}
retry_attempt_index :: (attempt: s32) -> s32 {
if attempt < 0 { return 0 }
if attempt > 4 { return 4 }
return attempt
}
#program_export
sync_retry_decision :: (result: s32, attempt: s32) -> RetryDecision {
if result < 0 || result > 7 { result = 8 }
attempt = retry_attempt_index(attempt)
${decisionCode.join('\n')}
}
#program_export
app_sync_failure_needs_action :: (result: s32) -> s32 {
decision: RetryDecision = sync_retry_decision(result, 0)
return decision.needs_action
}
#program_export
app_sync_retry_delay :: (attempt: s32) -> float64 {
attempt = retry_attempt_index(attempt)
${delayCode.join('\n')}
}
`;
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.zi]');
const output = path.resolve(process.argv[2] ?? path.join(root, 'src/app/sync_retry.zi'));
const proof = await generateSyncRetry(path.join(root, 'laws/sync_retry'), output,
path.join(root, 'src/storage/sync_result.zi'));
console.log(`sync.retry: ${proof.laws.length} Bend laws proved; 45 decisions generated`);
} catch (error) {
console.error(error.message);
process.exitCode = 1;
}
}