Skip to content
Open
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
Binary file added docs/images/testnet-peer-registry.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
6 changes: 6 additions & 0 deletions node/production/operator-status.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,12 @@ Zero is an observed balance. A timeout, wrong chain or invalid reply returns exi

For offline gas caps from the same selected installation, use [`gas-policy`](gas-policy.md) instead of `status`.

### Compare the selected address with the testnet registry

Choose **View public registry** in the health table. The viewer fetches the current [public testnet address book](peers/README.md) from the official repository and marks the selected node address if it is listed. An IPFS-only profile can still browse the table. Entries are routing information, not a check that a node is online or authorized by your installation.

Watching health does not fetch the registry. Reload the registry page for a fresh read. Concurrent reads share one download, limited to ten seconds and 1 MiB. An unavailable list is reported as an error rather than an empty table. Listed endpoints are displayed as text and are never contacted.

## Results and recovery

- Exit **0**: matching direct `ready`/`busy`, or matching worker `idle`/`processing` with a fresh poll.
Expand Down
2 changes: 1 addition & 1 deletion node/production/peers/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ Once this feature is merged into upstream `main`, new or existing operators can
node node/production/scripts/peer-directory.mjs fetch
```

`fetch` reads only the fixed official GitHub source, with a ten-second timeout and no redirects. It prints the list only after a successful HTTP response and basic JSON/record checks. It does not contact listed nodes. Exit codes are 0 for success, 1 for loading failure and 2 for incorrect arguments.
`fetch` reads only the fixed official GitHub source, with a ten-second timeout, a 1 MiB response limit and no redirects. It prints the list only after a successful HTTP response and basic JSON/record checks. It does not contact listed nodes. Exit codes are 0 for success, 1 for loading failure and 2 for incorrect arguments.

To save a refreshed copy without losing an existing copy on a failed download, run this from the directory where you keep the public registry:

Expand Down
24 changes: 23 additions & 1 deletion node/production/scripts/operator-view.mjs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { createServer } from 'node:http';
import { fetchDirectory } from './peer-directory.mjs';
import { loadProfile } from './operator-profile.mjs';
import { operatorStatus } from './operator-status.mjs';

Expand All @@ -10,11 +11,26 @@ function text(value) {
return String(value).replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;');
}

async function registryPage(selected) {
const nodes = await fetchDirectory();
const matches = node => selected && node.nodeAddress.toLowerCase() === selected.toLowerCase();
const identity = !selected ? 'No node address selected in this profile.' : nodes.some(matches)
? 'The selected address is listed.' : 'The selected address is not listed.';
const rows = nodes.map(node => `<tr><td><code>${text(node.nodeAddress)}</code>${matches(node) ? ' (selected)' : ''}</td>` +
`<td>${text(node.url)}</td><td>${text(node.target)}</td></tr>`).join('');
return `<!doctype html><html lang="en"><head><meta charset="utf-8"><title>Testnet peer registry</title>
<meta name="viewport" content="width=device-width, initial-scale=1"></head><body><main><a href="/">Local node health</a>
<h1>Testnet peer registry</h1><p>Public address book from the Oya repository on GitHub. Listing does not indicate whether a node is online.</p>
<p>${identity}</p>${rows ? `<table><thead><tr><th>Node address</th><th>Inbox endpoint</th><th>Inbox target</th></tr></thead><tbody>${rows}</tbody></table>` : '<p>No entries in the testnet registry.</p>'}
<p>Read at ${new Date().toISOString()}. Reload to fetch again.</p></main></body></html>`;
}

async function observe(profile) {
const status = await operatorStatus(profile);
const rows = Object.entries(labels).filter(([key]) => status[key] !== null).map(([key, label]) =>
`<tr><th scope="row">${label}</th><td>${typeof status[key] === 'boolean'
? (status[key] ? '<span aria-hidden="true">✅</span> Yes' : 'No') : text(status[key])}</td></tr>`).join('\n');
? (status[key] ? '<span aria-hidden="true">✅</span> Yes' : 'No') : text(status[key])}</td></tr>`)
.concat('<tr><th scope="row">Testnet peers</th><td><a href="/peers">View public registry</a></td></tr>').join('\n');
return `<!doctype html><html lang="en"><head><meta charset="utf-8"><title>Local node health</title>
<meta name="viewport" content="width=device-width, initial-scale=1"><meta http-equiv="refresh" content="${refreshSeconds}"></head>
<body><main><h1>Local node health</h1><p>${text(status.message)}</p><table><tbody>${rows}</tbody></table>
Expand All @@ -31,6 +47,12 @@ function serve(profile) {
if (req.headers.host !== `127.0.0.1:${server.address().port}` || req.headers['sec-fetch-site'] === 'cross-site') {
return res.writeHead(403).end();
}
if (req.method === 'GET' && req.url === '/peers') {
try {
const html = await registryPage(profile.nodeAddress);
return res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }).end(html);
} catch { return res.writeHead(503).end('Testnet registry unavailable. Reload to retry.'); }
}
if (req.method !== 'GET') return res.writeHead(405, { Allow: 'GET' }).end();
if (req.url !== '/') return res.writeHead(404).end();
try {
Expand Down
69 changes: 45 additions & 24 deletions node/production/scripts/peer-directory.mjs
Original file line number Diff line number Diff line change
@@ -1,31 +1,52 @@
import { readFile } from 'node:fs/promises';
import { readFile, realpath } from 'node:fs/promises';

const registry = new URL('../peers/testnet-directory.json', import.meta.url);
const upstream = 'https://raw.githubusercontent.com/oyaprotocol/oya-commitments/main/node/production/peers/testnet-directory.json';
const [command = 'list', ...args] = process.argv.slice(2);

if (!((command === 'list' && args.length <= 1) || (command === 'fetch' && args.length === 0))) {
console.error('Usage: peer-directory.mjs [list [FILE] | fetch]');
process.exitCode = 2;
} else {
try {
let text;
if (command === 'fetch') {
const response = await fetch(upstream, { redirect: 'error', signal: AbortSignal.timeout(10_000) });
if (!response.ok) throw new Error('Download failed');
text = await response.text();
} else {
text = await readFile(args[0] ?? registry, 'utf8');
}
const nodes = JSON.parse(text);
// Catch accidental file/response errors; repository review establishes trust.
if (!Array.isArray(nodes) || !nodes.every(node => node &&
['nodeAddress', 'url', 'target'].every(key => typeof node[key] === 'string' && node[key].length > 0))) {
throw new Error('Expected node records');
function parseDirectory(text) {
const nodes = JSON.parse(text);
// Catch accidental file/response errors; repository review establishes trust.
if (!Array.isArray(nodes) || !nodes.every(node => node &&
['nodeAddress', 'url', 'target'].every(key => typeof node[key] === 'string' && node[key].length > 0))) {
throw new Error('Expected node records');
}
return nodes;
}

// All callers read the same public URL. Share an active download, not a stale result.
let download;
export function fetchDirectory() {
return download ??= readUpstream().finally(() => { download = undefined; });
}

async function readUpstream() {
const response = await fetch(upstream, { redirect: 'error', signal: AbortSignal.timeout(10_000) });
if (!response.ok) {
await response.body?.cancel();
throw new Error('Download failed');
}
const chunks = [];
let size = 0;
for await (const chunk of response.body) {
size += chunk.length;
if (size > 1048576) throw new Error('Registry exceeds 1 MiB');
chunks.push(chunk);
}
return parseDirectory(new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks, size)));
}

if (process.argv[1] && import.meta.filename === await realpath(process.argv[1]).catch(() => null)) {
const [command = 'list', ...args] = process.argv.slice(2);
if (!((command === 'list' && args.length <= 1) || (command === 'fetch' && args.length === 0))) {
console.error('Usage: peer-directory.mjs [list [FILE] | fetch]');
process.exitCode = 2;
} else {
try {
const nodes = command === 'fetch' ? await fetchDirectory() : parseDirectory(await readFile(args[0] ?? registry, 'utf8'));
console.log(JSON.stringify(nodes, null, 2));
} catch {
console.error('Unable to load peer registry. Check the file or retry the upstream fetch.');
process.exitCode = 1;
}
console.log(JSON.stringify(nodes, null, 2));
} catch {
console.error('Unable to load peer registry. Check the file or retry the upstream fetch.');
process.exitCode = 1;
}
}
63 changes: 63 additions & 0 deletions node/production/test/operator-registry-view.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import assert from 'node:assert/strict';
import { spawn } from 'node:child_process';
import { once } from 'node:events';
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import test from 'node:test';

const viewer = fileURLToPath(new URL('../scripts/operator-view.mjs', import.meta.url));
const address = `0x${'ab'.repeat(20)}`;
const entry = { nodeAddress: `0x${'AB'.repeat(20)}`, url: 'https://one.example/v1/jobs', target: 'alpha' };

for (const mode of ['ledger', 'ipfs']) {
test(`registry view (${mode}) reads upstream only on demand, distinguishes absence from failure, and recovers`, { timeout: 12000 }, async t => {
const dir = await mkdtemp(join(tmpdir(), 'registry-view-'));
const profile = join(dir, 'operator.json'), preload = join(dir, 'mock.mjs'), data = join(dir, 'response'), calls = join(dir, 'calls');
t.after(() => rm(dir, { recursive: true, force: true }));
await writeFile(join(dir, 'node.json'), JSON.stringify(mode === 'ipfs' ? { mode } : { mode, chainId: 1, ledgerContract: address }));
await writeFile(profile, JSON.stringify({ version: 1, role: 'direct', nodeConfig: 'node.json', healthUrl: 'http://127.0.0.1:1/healthz',
...(mode === 'ledger' ? { nodeAddress: address } : {}) }), { mode: 0o600 });
await writeFile(calls, '');
await writeFile(preload, `import { appendFile, readFile } from 'node:fs/promises';
import { setTimeout } from 'node:timers/promises';
globalThis.fetch = async (url, options) => {
await appendFile(${JSON.stringify(calls)}, url+'\\n');
if (url !== 'https://raw.githubusercontent.com/oyaprotocol/oya-commitments/main/node/production/peers/testnet-directory.json'
|| options.redirect !== 'error' || options.headers || !options.signal) throw new Error('Unexpected fetch');
await setTimeout(50);
return new Response(await readFile(${JSON.stringify(data)}));
};`);
const child = spawn(process.execPath, ['--import', preload, viewer, '--profile', profile], { cwd: dir, stdio: ['ignore', 'pipe', 'ignore'] });
t.after(() => child.kill());
const [line] = await once(child.stdout, 'data');
const root = line.toString().trim(), peers = root + 'peers';
assert.match(await (await fetch(root)).text(), /href="\/peers"/);
assert.equal((await fetch(peers, { method: 'POST' })).status, 405);
assert.equal((await fetch(peers, { headers: { 'sec-fetch-site': 'cross-site' } })).status, 403);
assert.equal((await fetch(peers + '?source=other')).status, 404);
assert.equal(await readFile(calls, 'utf8'), '');
await writeFile(data, JSON.stringify([{ ...entry, target: '<one & two>', extra: 'ignored-field' }]));
const [a, b] = await Promise.all([fetch(peers), fetch(peers)]);
assert.equal(a.status, 200);
const html = await a.text();
assert.equal(b.status, 200);
assert.match(await b.text(), /&lt;one &amp; two&gt;/);
assert.equal((await readFile(calls, 'utf8')).trim().split('\n').length, 1);
assert.match(html, /&lt;one &amp; two&gt;/);
assert.match(html, /https:\/\/one\.example\/v1\/jobs/);
assert.doesNotMatch(html, /href="https:|ignored-field|<one & two>|http-equiv="refresh"/);
assert.match(html, mode === 'ledger' ? /The selected address is listed/ : /No node address selected/);
await writeFile(data, 'invalid-sentinel');
const error = await fetch(peers);
assert.equal(error.status, 503);
assert.match(await error.text(), /^Testnet registry unavailable\. Reload to retry\.$/);
await writeFile(data, '[]');
const empty = await fetch(peers);
assert.equal(empty.status, 200);
const page = await empty.text();
assert.match(page, /No entries in the testnet registry/);
if (mode === 'ledger') assert.match(page, /The selected address is not listed/);
});
}
20 changes: 12 additions & 8 deletions node/production/test/peer-directory.test.mjs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import assert from 'node:assert/strict';
import { spawnSync } from 'node:child_process';
import { mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
import { mkdtempSync, readFileSync, readdirSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
Expand Down Expand Up @@ -28,6 +28,11 @@ test('default loads the bundled registry from any working directory without netw
assert.equal(result.status, 0, result.stderr);
assert.deepEqual(JSON.parse(result.stdout), JSON.parse(readFileSync(official, 'utf8')));
assert.equal(result.stderr, '');
const link = join(f.dir, 'peer-list.mjs');
symlinkSync(cli, link);
const linked = spawnSync(process.execPath, [link], { cwd: f.dir, encoding: 'utf8', timeout: 5000 });
assert.equal(linked.status, 0, linked.stderr);
assert.equal(linked.stdout, result.stdout);
});

test('local list preserves records and recovers from malformed or missing files', t => {
Expand Down Expand Up @@ -74,7 +79,8 @@ test('failed fetches emit no partial list and do not change an existing copy', t
'return new Response("private-marker", {status: 500})',
'return new Response("not JSON")',
'return new Response("{}")',
'return {ok: true, text: async () => { throw new Error("body interrupted"); }}',
'return new Response(new ReadableStream({ start(c) { c.error(new Error("body interrupted")); } }))',
'return new Response("[]" + " ".repeat(1048576))',
'await new Promise((resolve, reject) => options.signal.addEventListener("abort", () => reject(options.signal.reason)))',
]) {
f.mock(`const timeout = AbortSignal.timeout;
Expand All @@ -96,12 +102,10 @@ test('deadline also covers response body reading', t => {
const f = fixture(t);
f.mock(`const timeout = AbortSignal.timeout;
AbortSignal.timeout = () => timeout(20);
globalThis.fetch = async (url, options) => ({ok: true, text: async () => {
const hold = setTimeout(() => {}, 500);
try {
await new Promise((resolve, reject) => options.signal.addEventListener('abort', () => reject(options.signal.reason)));
} finally { clearTimeout(hold); }
}});`);
globalThis.fetch = async (url, options) => new Response(new ReadableStream({ start(controller) {
const hold = setTimeout(() => { controller.enqueue(new TextEncoder().encode('[]')); controller.close(); }, 500);
options.signal.addEventListener('abort', () => { clearTimeout(hold); controller.error(options.signal.reason); });
}}));`);
const result = f.run('fetch');
assert.equal(result.status, 1, result.stderr);
assert.equal(result.stdout, '');
Expand Down
Loading
Loading