Skip to content
Merged
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
36 changes: 23 additions & 13 deletions ZelBack/src/services/explorerService.js
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,16 @@ const BOOTSTRAP_RETRY_MS = 60_000;
const RECOVERY_RETRY_MS = 15 * 60 * 1000;
// How long a block waits for fluxd to sync before it is asked for again.
const BLOCK_SYNC_RETRY_MS = 2 * 60 * 1000;
// How long the explorer waits before asking again whether the chain has moved,
// and before it recovers from a block that failed, so a block fluxd keeps
// refusing is retried at this pace rather than as fast as fluxd answers.
//
// This is the floor on how fast a node can process blocks: a block is not looked
// at until the next poll, so nothing downstream of block processing - expiring
// app records, trimming surplus instances, the give-up pass - can run more often
// than this however fast blocks are produced. Production wants 5s against a 30s
// block; a harness driving its own chain sets it shorter.
const POLL_INTERVAL_MS = config.fluxapps.explorerPollIntervalMs ?? 5000;

/**
* The block processor's steps. Each step function answers `{ next, waitMs }`:
Expand Down Expand Up @@ -521,7 +531,8 @@ async function scheduleUpnpBench(tipBlock, period) {
* The block processor's step for one block.
* @param {number} blockHeight
* @returns {Promise<{next: object, waitMs: number}>} The next block while fluxd
* holds one, the poll at the tip, the recovery when this block fails.
* holds one, the poll at the tip or while fluxd does not hold this block yet,
* the recovery when this block fails, after POLL_INTERVAL_MS.
*/
async function processBlock(blockHeight) {
try {
Expand All @@ -532,7 +543,15 @@ async function processBlock(blockHeight) {
const database = db.db(config.database.daemon.database);
// get Block information
const verbosity = 2;
const blockDataVerbose = await getVerboseBlock(blockHeight, verbosity);
let blockDataVerbose;
try {
blockDataVerbose = await getVerboseBlock(blockHeight, verbosity);
} catch (error) {
// fluxd's chain does not reach this height yet. Nothing has been written
// for the block, so there is nothing to restore: the poller asks again.
if (error?.code === -8) return after(Step.poll(), POLL_INTERVAL_MS);
throw error;
}
const parent = await scannedBlockAt(database, blockDataVerbose.height - 1);
if (parent && blockDataVerbose.previousblockhash !== parent.hash) {
const restoredHeight = await rewindToFork(database, parent);
Expand Down Expand Up @@ -630,7 +649,7 @@ async function processBlock(blockHeight) {
log.error('Block processor encountered an error.');
log.error(error);
const deep = Boolean(error.message && error.message.includes('duplicate key'));
return after(Step.recover(true, deep));
return after(Step.recover(true, deep), POLL_INTERVAL_MS);
}
}

Expand Down Expand Up @@ -1160,16 +1179,6 @@ async function rewindToFork(database, parent) {
return height;
}

// How long the explorer waits before asking again whether the chain has moved.
//
// This is the floor on how fast a node can process blocks: a block is not looked
// at until the next poll, so nothing downstream of block processing - expiring
// app records, trimming surplus instances, the give-up pass - can run more often
// than this however fast blocks are produced. Production wants 5s against a 30s
// block; a harness driving its own chain wants it far shorter, and had no way to
// say so.
const POLL_INTERVAL_MS = config.fluxapps.explorerPollIntervalMs ?? 5000;

/**
* The block processor's step at the tip: whether fluxd holds a block the
* explorer has not processed, or a reorganisation moved the explorer back.
Expand Down Expand Up @@ -1205,6 +1214,7 @@ async function pollForNewBlocks() {
async function recoverAndRestart(restoreDatabase, deepRestore) {
const syncWaitMs = untilDaemonSyncedMs();
if (syncWaitMs) return after(Step.recover(restoreDatabase, deepRestore), syncWaitMs);
fluxEventBus.count('explorer:recovery');
try {
const db = dbHelper.databaseConnection();
const database = db.db(config.database.daemon.database);
Expand Down
13 changes: 11 additions & 2 deletions test-infra/daemon-stub/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,12 @@ function hashAt(height) {
return forkedHashes.get(height) ?? `000000000000stub${height}`;
}

// An error a handler throws to answer with fluxd's RPC error code; any other
// throw answers -1.
function rpcError(code, message) {
return Object.assign(new Error(message), { rpcCode: code });
}

// height -> block time, epoch seconds. A block's time is fixed when it is mined,
// or when it is first asked about if it predates this stub, and every later read
// returns the same value - as the chain does, where every node reads one header
Expand Down Expand Up @@ -397,10 +403,13 @@ const rpcHandlers = {
return pending?.hash ?? hashAt(height);
},

getblock: (params) => {
// A height above the asking node's chain is refused as fluxd refuses it.
getblock: (params, sourceIp) => {
const hashOrHeight = params[0];
const verbosity = params[1] || 1;
const asNum = Number(hashOrHeight);
const byHeight = typeof hashOrHeight === 'number' || /^\d{1,12}$/.test(String(hashOrHeight));
if (byHeight && asNum > localHeightFor(sourceIp)) throw rpcError(-8, 'Block height out of range');

const pending = pendingBlocks.find((b) => b.height === asNum || b.height === hashOrHeight || b.hash === hashOrHeight);
if (pending) {
Expand Down Expand Up @@ -715,7 +724,7 @@ async function answerRpc(handlers, request, sourceIp, port) {
return { body: { result, error: null, id } };
} catch (e) {
console.error(`RPC error for ${method} from ${sourceIp}:`, e.message);
return { body: { result: null, error: { code: -1, message: e.message }, id } };
return { body: { result: null, error: { code: e.rpcCode ?? -1, message: e.message }, id } };
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -111,8 +111,16 @@ describe('a standby that lost a delete hears the primary again', function () {
`mkdir -p ${primaryRoot}/${STALE} && head -c 70000 /dev/urandom > ${primaryRoot}/${STALE}/world.sav && echo meta > ${primaryRoot}/${STALE}/meta.sav && chown -R 1000:1000 ${primaryRoot}/${STALE}`);
expect(made.exitCode).to.equal(0);
await scanFolder(env.clients[primary], folder);
await waitFor(async () => (await onLeaver(`${STALE}/meta.sav`)) !== null, {
timeout: 120000, interval: 2000, label: 'the standby holds the backup',
// Both standbys hold the files before they are deleted. A standby that never held
// them takes the delete in its own order, so its directory's delete can land after
// the sequence read below and reach the leaver on its own, which syncthing cannot
// apply while the directory holds the files.
const standbys = HOLDERS.filter((i) => i !== primary);
const rootOf = Object.fromEntries(await Promise.all(standbys.map(async (i) => [i, (await getFolderConfig(env.clients[i], folder)).path])));
const staleFiles = staleItems.filter((name) => name !== STALE);
await waitFor(async () => (await Promise.all(standbys.flatMap((i) => staleFiles.map((name) => readPath(env.clients[i], `${rootOf[i]}/${name}`)))))
.every((content) => content !== null), {
timeout: 120000, interval: 2000, label: 'every standby holds the backup',
});
// The delete is lost from every device that holds it, which needs a record of
// each in the standby's index: every holder's index has reached it.
Expand All @@ -126,8 +134,15 @@ describe('a standby that lost a delete hears the primary again', function () {
await execInContainer(env.clients[primary].container, `rm -rf ${primaryRoot}/${STALE}`);
await scanFolder(env.clients[primary], folder);
const other = HOLDERS.find((i) => i !== primary && i !== leaver);
await waitFor(async () => (await readPath(env.clients[other], `${path}/${STALE}/meta.sav`)) === null, {
timeout: 120000, interval: 2000, label: 'the other standby took the delete',
// Its sequence is read once it has applied the whole delete, directory included, so
// it holds no record of the delete above that sequence.
await waitFor(async () => {
const gone = await execInContainer(env.clients[other].container, `test ! -e "${rootOf[other]}/${STALE}"`);
if (gone.exitCode !== 0) return false;
const { state, needTotalItems } = await getFolderStatus(env.clients[other], folder);
return state === 'idle' && needTotalItems === 0;
}, {
timeout: 120000, interval: 2000, label: 'the other standby took the whole delete',
});
// Every device that holds the delete would otherwise repeat it.
// eslint-disable-next-line no-restricted-syntax
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
/*
* A block fluxd refuses is asked for again no faster than the explorer polls for a
* new block, however long fluxd goes on refusing it, and once fluxd gives it the
* explorer processes it and reaches the tip.
*
* fluxd answers every call but getblock for the node under test, so the node keeps
* reading fluxd as synced and its sync wait never paces the retry. The window is the
* time between two of the node's reads of fluxd's height (daemonInfoIntervalMs):
* paced by explorerPollIntervalMs, the explorer asks for the block at most
* window / poll + 1 times in it.
*
* A block above fluxd's chain is answered out of range (-8), and the explorer waits
* for it at the poll without recovering. The fixture holds the explorer's request
* for the next block, takes fluxd's chain back to the tip, then lets fluxd answer;
* the recovery count (explorer:recovery) must not move.
*/
import { describe, it, before } from 'mocha';
import { expect } from 'chai';
import { createTestEnv } from '../framework/test-env.js';
import { bootAndPeer } from '../framework/reconciler-suite.js';
import {
stopTicker, advanceBlock, getState, setHeight, failRpc, clearRpcFailures, holdRpc, releaseRpc,
getJournal, clearJournal,
} from '../framework/daemon-control.js';
import { loadSharedConfig } from '../framework/coupled-knobs.js';
import { waitFor, assertNoEvent } from '../framework/wait.js';
import { dumpLogsOnFailure } from '../framework/log-on-failure.js';
import { afterTeardown } from '../framework/teardown-hook.js';

const NODES = 3;
// The middle of the ring: every backward arc wraps onto index 0.
const NODE = 1;
const { daemonInfoIntervalMs, explorerPollIntervalMs } = loadSharedConfig().fluxapps;

describe('a block fluxd refuses is asked for again at the pace of the explorer\'s poll', function () {
let env;
let client;
let ip;

dumpLogsOnFailure(() => env);

before(async function () {
this.timeout(420000);
env = await createTestEnv({ hookCtx: this, nodes: NODES, tickerAutostart: false });
await bootAndPeer(env);
await stopTicker();
client = env.clients[NODE];
ip = client.ip;
});

afterTeardown(async function () {
await clearRpcFailures(ip).catch(() => {});
await releaseRpc(ip).catch(() => {});
await env?.teardown();
});

async function tipProcessed(afterId) {
const { currentHeight } = await getState();
await client.waitForEvent('block:processed', (d) => d.height === currentHeight, 120000, { afterId });
return currentHeight;
}

const nextDaemonPoll = (afterId) => client.waitForEvent('daemon:polled', () => true, daemonInfoIntervalMs * 4, { afterId });

it('asks for the refused block once a poll at most, and processes it once fluxd gives it', async function () {
this.timeout(240000);
let mark = client.getLastEventId();
await advanceBlock();
await tipProcessed(mark);

await failRpc(ip, 'getblock', { times: 1000000 });
mark = client.getLastEventId();
await advanceBlock();
const { currentHeight: refused } = await getState();
// The node has read the new height: from its next poll the explorer asks for
// the block fluxd refuses.
const learned = await client.waitForEvent('daemon:polled', (d) => d.height === refused, daemonInfoIntervalMs * 4, { afterId: mark });
const opened = await nextDaemonPoll(learned.id);
await clearJournal();
const openedAt = Date.now();
await nextDaemonPoll(opened.id);
const { total: asked } = await getJournal({ method: 'getblock', sourceIp: ip });

const windowMs = Date.now() - openedAt;
const ceiling = Math.floor(windowMs / explorerPollIntervalMs) + 1;
expect(asked, 'the explorer never asked for the refused block').to.be.at.least(1);
expect(asked, `getblock asked ${asked} times in ${windowMs}ms against a poll of ${explorerPollIntervalMs}ms`).to.be.at.most(ceiling);

mark = client.getLastEventId();
await clearRpcFailures(ip);
expect(await tipProcessed(mark)).to.equal(refused);
});

it('waits for a block above fluxd\'s chain without recovering, and processes it once fluxd holds it', async function () {
this.timeout(240000);
let mark = client.getLastEventId();
await advanceBlock();
const tip = await tipProcessed(mark);

// The explorer asks for the next block, and fluxd's chain is back at the tip
// by the time it answers: out of range.
await holdRpc(ip, 'getblock');
await clearJournal();
mark = client.getLastEventId();
await advanceBlock();
await waitFor(async () => (await getJournal({ method: 'getblock', sourceIp: ip })).total >= 1, {
timeout: daemonInfoIntervalMs * 4, interval: 200, label: `the explorer asking for block ${tip + 1}`,
});
const lowered = client.getLastEventId();
await setHeight(tip);
const recoveries = (await client.getTestCounters())['explorer:recovery'] ?? 0;
await releaseRpc(ip);

// The node reads fluxd's height as the tip again: from here the poller asks
// for nothing above it.
await client.waitForEvent('daemon:polled', (d) => d.height === tip, daemonInfoIntervalMs * 4, { afterId: lowered });
await nextDaemonPoll(client.getLastEventId());
expect((await client.getTestCounters())['explorer:recovery'] ?? 0, 'recoveries from a block fluxd does not hold').to.equal(recoveries);
await assertNoEvent(client, 'block:processed', (d) => d.height > tip, 0, { afterId: mark });

mark = client.getLastEventId();
await advanceBlock();
expect(await tipProcessed(mark)).to.equal(tip + 1);
});
});
35 changes: 35 additions & 0 deletions tests/unit/explorerService.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -924,6 +924,41 @@ describe('explorerService tests', () => {
sinon.assert.notCalled(removeDocumentsStub);
});
});

describe('a block fluxd does not give', () => {
const pollIntervalMs = config.fluxapps.explorerPollIntervalMs;
const blockHeight = 100000;

beforeEach(() => {
daemonServiceMiscRpcsStub.returns({ data: { synced: true, height: blockHeight } });
});

it('is asked for again at the next poll, with nothing written, while fluxd\'s chain does not reach it', async () => {
daemonServiceBlockchainRpcsStub.resolves({ status: 'error', data: { code: -8, name: 'RPCError', message: 'Block height out of range' } });

const step = await explorerService.processBlock(blockHeight);

expect(step).to.deep.equal({ next: explorerService.Step.poll(), waitMs: pollIntervalMs });
sinon.assert.notCalled(dbStubUpdate);
});

it('is recovered from one poll interval later when fluxd refuses it for another reason', async () => {
daemonServiceBlockchainRpcsStub.resolves({ status: 'error', data: { code: -28, name: 'RPCError', message: 'Loading block index...' } });

const step = await explorerService.processBlock(blockHeight);

expect(step).to.deep.equal({ next: explorerService.Step.recover(true, false), waitMs: pollIntervalMs });
});

it('is recovered from when out of range is raised after the block was fetched', async () => {
daemonServiceBlockchainRpcsStub.resolves({ status: 'success', data: { tx: [], height: blockHeight, confirmations: 1 } });
sinon.stub(fluxnodeAddressRecord, 'recordBlock').rejects(Object.assign(new Error('Block height out of range'), { code: -8 }));

const step = await explorerService.processBlock(blockHeight);

expect(step).to.deep.equal({ next: explorerService.Step.recover(true, false), waitMs: pollIntervalMs });
});
});
});

describe('the fluxnode address record', () => {
Expand Down
Loading