快照修复 跨区块时重新采集整套数据,最多尝试 3 次。

每次重试重新查询全部数据,不能拼接不同尝试的结果。
记录每次耗时、前后高度及最终失败原因。
全部失败后保留旧快照,等待下一轮。
如果持续跨区块,则检查 RPC 延迟;仅靠重试无法解决长期慢响应。
This commit is contained in:
lu7213 committed 2026-11-02 01:23:42 -05:00
1 parent b84675df3c
commit 41190a25ae
4 files changed
+197 -8

No files matched your search

@@ -22,6 +22,17 @@ import static com.ruoyi.system.rental.RentalValues.*;
@Slf4j
@Service
public class RentalChain {
/** 总尝试次数(含首次),仅区块夹读冲突触发整套重采集。 */
private static final int SNAPSHOT_MAX_ATTEMPTS = 3;
/** 内部类型区分可重试的区块变化与RPC、参数及本金错误,禁止按异常文案判断。 */
private static final class SnapshotBlockChangedException extends IllegalArgumentException {
private static final long serialVersionUID = 1L;
private SnapshotBlockChangedException() {
super("快照区块不一致,整套重采集仍未通过");
}
}
@Value("${rental.rpc.nile:https://nile.trongrid.io}")
private String nile;
@@ -122,6 +133,32 @@ public class RentalChain {
}
public Map<String, Object> snapshot(String network, String address) {
long started = System.nanoTime();
for (int attempt = 1; attempt <= SNAPSHOT_MAX_ATTEMPTS; attempt++) {
try {
// 每次调用重新查询前区块、资源、两类本金、后区块,不复用失败尝试的数据。
Map<String, Object> result = snapshotOnce(network, address, attempt);
if (attempt > 1) {
log.info("租赁快照重采集成功 network={} address={} attempt={} maxAttempts={}"
+ " blockHeight={} totalElapsedMs={}",
network, address, attempt, SNAPSHOT_MAX_ATTEMPTS, result.get("snapshot_block_height"),
TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started));
}
return result;
} catch (SnapshotBlockChangedException ex) {
if (attempt == SNAPSHOT_MAX_ATTEMPTS) {
log.warn("租赁快照重采集耗尽 network={} address={} attempts={} totalElapsedMs={};保留旧快照,等待下一轮扫描",
network, address, attempt, TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started));
throw ex;
}
log.info("租赁快照跨区块重试 network={} address={} nextAttempt={} maxAttempts={}",
network, address, attempt + 1, SNAPSHOT_MAX_ATTEMPTS);
}
}
throw new IllegalStateException("快照重采集未产生结果");
}
private Map<String, Object> snapshotOnce(String network, String address, int attempt) {
long started = System.nanoTime();
String stage = "BEFORE_BLOCK";
try {
@@ -148,15 +185,14 @@ public class RentalChain {
if (before < 0 || before != after
|| !beforeBlock.path("blockID").asText().matches("[0-9a-fA-F]{64}")
|| !beforeBlock.path("blockID").asText().equalsIgnoreCase(afterBlock.path("blockID").asText())) {
log.warn("租赁快照区块不一致 network={} address={} beforeHeight={} afterHeight={}"
log.warn("租赁快照区块不一致 network={} address={} attempt={} maxAttempts={} beforeHeight={} afterHeight={}"
+ " reason=BLOCK_CHANGED_OR_INVALID;本次不更新,禁止混用不同区块资源",
network, address, before, after);
network, address, attempt, SNAPSHOT_MAX_ATTEMPTS, before, after);
throw new SnapshotBlockChangedException();
}
require(
before >= 0 && before == after && energy >= 0 && bandwidth >= 0
&& beforeBlock.path("blockID").asText().matches("[0-9a-fA-F]{64}")
&& beforeBlock.path("blockID").asText().equalsIgnoreCase(afterBlock.path("blockID").asText()),
"快照跨区块或本金查询不完整,请重试");
energy >= 0 && bandwidth >= 0,
"快照本金查询不完整");
Map<String, Object> result =
map(
"snapshot_block_height",
@@ -211,8 +247,8 @@ public class RentalChain {
}
return result;
} catch (RuntimeException ex) {
log.warn("租赁链上快照采集失败 network={} address={} stage={} elapsedMs={} diagnostic={}",
network, address, stage, TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started),
log.warn("租赁链上快照采集失败 network={} address={} attempt={} stage={} elapsedMs={} diagnostic={}",
network, address, attempt, stage, TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started),
RentalDiagnostics.describe(ex));
throw ex;
}
@@ -755,6 +755,26 @@ public class RentalBusinessTest {
expectFailure(() -> tx.execute(status -> orders.create(app, 10, request)));
}
@Test
public void failedSnapshotCollectionPreservesStoredSnapshotAndVersion() {
Map<String, Object> before = store.get("wallet", wallet, false);
RentalChain unavailable = new RentalChain(json) {
@Override
public Map<String, Object> snapshot(String network, String address) {
throw new IllegalArgumentException("controlled snapshot failure after retries");
}
};
RentalTasks failingTasks = new RentalTasks(store, unavailable, identity, orders, funds,
tx.getTransactionManager());
expectFailure(() -> failingTasks.refresh(wallet));
Map<String, Object> after = store.get("wallet", wallet, false);
assertEquals(before.get("snapshot_at"), after.get("snapshot_at"));
assertEquals(before.get("snapshot_expires_at"), after.get("snapshot_expires_at"));
assertEquals(before.get("snapshot_block_height"), after.get("snapshot_block_height"));
assertEquals(before.get("energy_delegatable_sun"), after.get("energy_delegatable_sun"));
assertEquals(before.get("version"), after.get("version"));
}
@Test
public void onchainDispatchDoesNotRequireStakeSnapshotAndStillVerifiesTransfer() {
store.update("node", node, map("transfer_enabled", 1));
@@ -0,0 +1,131 @@
package com.ruoyi.system.rental;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import java.util.Map;
import static com.ruoyi.system.rental.RentalValues.*;
import static org.junit.Assert.*;
/** 可控RPC验证整套重采集与有界重试;不访问外网、不广播真实交易。 */
public class RentalSnapshotTest {
@Test
public void changedBlockRetriesWholeSampleAndReturnsOnlyLatestValues() {
FakeChain chain = new FakeChain(1);
Map<String, Object> result = chain.snapshot("NILE", "test-address");
assertEquals(2, chain.resourceCalls);
assertEquals(4, chain.principalCalls);
assertEquals(4, chain.blockCalls);
assertEquals(200, number(result, "energy_available"));
assertEquals(2000, number(result, "energy_delegatable_sun"));
assertEquals(2000, number(result, "bandwidth_delegatable_sun"));
assertEquals(104, number(result, "snapshot_block_height"));
}
@Test
public void thirdAttemptCanSucceedAndSameHeightHashChangesAlsoRetry() {
FakeChain chain = new FakeChain(2);
chain.sameHeightConflict = true;
Map<String, Object> result = chain.snapshot("NILE", "test-address");
assertEquals(3, chain.resourceCalls);
assertEquals(6, chain.principalCalls);
assertEquals(6, chain.blockCalls);
assertEquals(300, number(result, "energy_available"));
assertEquals(106, number(result, "snapshot_block_height"));
}
@Test
public void repeatedBlockChangesStopAfterThreeCompleteAttempts() {
FakeChain chain = new FakeChain(3);
try {
chain.snapshot("NILE", "test-address");
fail("跨区块不能返回不一致快照");
} catch (IllegalArgumentException expected) {
assertEquals(3, chain.resourceCalls);
assertEquals(6, chain.principalCalls);
assertEquals(6, chain.blockCalls);
}
}
@Test
public void stableSnapshotDoesNotMakeExtraRequests() {
FakeChain chain = new FakeChain(0);
assertEquals(102, number(chain.snapshot("NILE", "test-address"), "snapshot_block_height"));
assertEquals(1, chain.resourceCalls);
assertEquals(2, chain.principalCalls);
assertEquals(2, chain.blockCalls);
}
@Test
public void resourceRpcFailureIsNotBlindlyRetried() {
FakeChain chain = new FakeChain(0);
chain.resourceRpcFailed = true;
try {
chain.snapshot("NILE", "test-address");
fail("RPC失败不能生成快照");
} catch (IllegalStateException expected) {
assertEquals(1, chain.resourceCalls);
assertEquals(1, chain.blockCalls);
assertEquals(0, chain.principalCalls);
}
}
@Test
public void incompleteParametersAreNotTreatedAsBlockChanges() {
FakeChain chain = new FakeChain(0);
chain.invalidParameters = true;
try {
chain.snapshot("NILE", "test-address");
fail("全网参数缺失应拒绝");
} catch (IllegalArgumentException expected) {
assertEquals(1, chain.resourceCalls);
assertEquals(2, chain.blockCalls);
}
}
private static final class FakeChain extends RentalChain {
private final ObjectMapper json = new ObjectMapper();
private final int conflictingAttempts;
private int blockCalls;
private int resourceCalls;
private int principalCalls;
private boolean invalidParameters;
private boolean resourceRpcFailed;
private boolean sameHeightConflict;
private FakeChain(int conflictingAttempts) {
super(new ObjectMapper());
this.conflictingAttempts = conflictingAttempts;
}
@Override
public JsonNode call(String network, String path, Map<String, Object> body) {
assertEquals("NILE", network);
if ("/wallet/getnowblock".equals(path)) {
int attempt = blockCalls / 2 + 1;
boolean after = ++blockCalls % 2 == 0;
boolean conflict = after && attempt <= conflictingAttempts;
long height = 100 + attempt * 2 + (conflict && !sameHeightConflict ? 1 : 0);
long blockIdentity = height + (conflict && sameHeightConflict ? 1000 : 0);
return json.valueToTree(map("blockID", String.format("%064x", blockIdentity),
"block_header", map("raw_data", map("number", height))));
}
if ("/wallet/getaccountresource".equals(path)) {
resourceCalls++;
if (resourceRpcFailed) {
throw new IllegalStateException("controlled RPC failure");
}
return json.valueToTree(map("EnergyLimit", resourceCalls * 100,
"TotalEnergyLimit", invalidParameters ? 0 : 60000000,
"TotalEnergyWeight", 1000000, "TotalNetLimit", 1000000, "TotalNetWeight", 1000));
}
if ("/wallet/getcandelegatedmaxsize".equals(path)) {
principalCalls++;
return json.valueToTree(map("max_size", resourceCalls * 1000));
}
throw new AssertionError("意外RPC路径: " + path);
}
}
}