尽量服用,和优化采样区块,交易所在区块的资源参数 获取不需要每次获取有下单租赁订单都获取一遍,应该是全局异步获取是不是就可以,帮我设计合理方案。 和清理逻辑

This commit is contained in:
lu7213 committed 2026-10-31 19:10:27 -04:00
1 parent 13665668ac
commit 1538cd0819
24 files changed
+1894 -230

No files matched your search

@@ -36,6 +36,8 @@ public class RentalBusinessTest {
private long wallet;
private long node;
private boolean proofAvailable = true;
private long verifiedResourceQuantity = 78000;
private long verificationBlockAgeSeconds = 5;
private boolean receiverActivated;
private boolean activationRpcFailed;
private int activationChecks;
@@ -696,7 +698,7 @@ public class RentalBusinessTest {
"block_height",
101,
"block_time",
now().minusSeconds(5),
now().minusSeconds(verificationBlockAgeSeconds),
"after_sun",
"DELEGATE".equals(text(task, "task_type"))
? task.get("delegate_sun")
@@ -706,7 +708,7 @@ public class RentalBusinessTest {
"verified_total_weight",
1000000,
"verified_resource_quantity",
78000,
verifiedResourceQuantity,
"delivery_proven",
proofAvailable);
}
@@ -1141,6 +1143,111 @@ public class RentalBusinessTest {
ADDRESS)));
}
@Test
public void orderAndTaskEventsArePublishedOnlyAfterCommit() throws Exception {
List<RentalDeliveryEvents> events = new ArrayList<>();
org.springframework.context.ApplicationEventPublisher publisher = event -> events.add((RentalDeliveryEvents) event);
injectPublisher(orders, publisher);
injectPublisher(tasks, publisher);
long orderId = tx.execute(status -> {
long id = number(create("AFTER-COMMIT"), "id");
assertTrue(events.isEmpty());
return id;
});
assertEquals(1, events.size());
assertTrue(events.get(0).order);
assertEquals(orderId, events.get(0).id);
tx.execute(status -> {
tasks.dispatch(orderId);
assertEquals(1, events.size());
return null;
});
assertEquals(2, events.size());
assertFalse(events.get(1).order);
assertEquals(node, events.get(1).id);
}
@Test
public void rolledBackOrderDoesNotScheduleDelivery() throws Exception {
List<Object> events = new ArrayList<>();
injectPublisher(orders, events::add);
tx.execute(status -> {
create("ROLLBACK-DELIVERY");
status.setRollbackOnly();
return null;
});
assertTrue(events.isEmpty());
assertNull(store.one("SELECT id FROM rent_order WHERE merchant_order_no='ROLLBACK-DELIVERY'"));
}
@Test
public void committedOrderDispatchesOnIndependentDeliveryWorker() throws Exception {
org.springframework.beans.factory.support.DefaultListableBeanFactory factory =
new org.springframework.beans.factory.support.DefaultListableBeanFactory();
RentalSocket socket = new RentalSocket(store, identity, tasks, json);
factory.registerSingleton("tasks", tasks);
factory.registerSingleton("socket", socket);
RentalDeliveryDispatcher dispatcher = new RentalDeliveryDispatcher(
factory.getBeanProvider(RentalTasks.class), factory.getBeanProvider(RentalSocket.class));
dispatcher.start();
CountDownLatch taskCommitted = new CountDownLatch(1);
java.util.concurrent.atomic.AtomicReference<String> dispatchThread = new java.util.concurrent.atomic.AtomicReference<>();
injectPublisher(orders, event -> dispatcher.receive((RentalDeliveryEvents) event));
injectPublisher(tasks, event -> {
dispatchThread.set(Thread.currentThread().getName());
taskCommitted.countDown();
});
try {
long id = number(create("IMMEDIATE-DISPATCH"), "id");
assertTrue(taskCommitted.await(5, TimeUnit.SECONDS));
assertTrue(dispatchThread.get().startsWith("rental-delivery-"));
assertNotNull(store.one("SELECT id FROM rent_task WHERE order_id=?", id));
} finally {
dispatcher.close();
}
}
private void injectPublisher(Object target, org.springframework.context.ApplicationEventPublisher publisher)
throws Exception {
java.lang.reflect.Field field = target.getClass().getDeclaredField("deliveryEvents");
field.setAccessible(true);
field.set(target, publisher);
}
@Test
public void historyCleanupReadsRealBusinessSchemaAndKeepsFunds() throws Exception {
String ddl = new String(Files.readAllBytes(Paths.get("../sql/rent_history_init.sql")), StandardCharsets.UTF_8)
.replaceAll("(?m)^--.*$", "")
.replace("ENGINE=InnoDB ROW_FORMAT=DYNAMIC DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin", "");
for (String statement : ddl.split(";")) {
if (!statement.trim().isEmpty()) { store.execute(statement); }
}
// 此测试的完整业务DDL来自setup;清理器只能读业务状态,不能改动账户/流水。
store.execute("CREATE ALIAS IF NOT EXISTS UTC_TIMESTAMP FOR \"com.ruoyi.system.rental.RentalHistoryTest.utcTimestamp\"");
Map<String, Object> oldAccount = new LinkedHashMap<>(store.get("account", payer, false));
Map<String, Object> order = create("CLEANUP-PRESERVE-FUNDS");
Map<String, Object> heldAccount = new LinkedHashMap<>(store.get("account", payer, false));
store.execute("INSERT INTO rent_history_cursor (network,scanned_height,scanned_block_id,updated_at)"
+ " VALUES ('NILE',30000,?,?)", String.format("%064x", 30000), now());
store.execute("INSERT INTO rent_history_block (network,block_height,block_id,parent_id,block_time,"
+ "events_complete,created_at) VALUES ('NILE',100,?,?,?,1,?)", String.format("%064x", 100),
String.format("%064x", 99), System.currentTimeMillis() - 45L * 86400000,
now().minusDays(45));
java.nio.file.Path directory = Files.createTempDirectory("rental-history-cleanup-business-");
RentalHistoryCleaner cleaner = new RentalHistoryCleaner(store, json, new RentalHistoryArchive(json), tx.getTransactionManager());
java.lang.reflect.Field archiveDirectory = RentalHistoryCleaner.class.getDeclaredField("archiveDirectory");
archiveDirectory.setAccessible(true);
archiveDirectory.set(cleaner, directory.toString());
assertEquals(1, cleaner.clean("NILE"));
assertEquals(heldAccount, store.get("account", payer, false));
assertEquals("HELD", text(store.get("order", number(order, "id"), false), "fund_status"));
assertEquals(1, store.rows("SELECT id FROM rent_ledger WHERE order_id=?", order.get("id")).size());
assertTrue(amount(oldAccount, "available_amount").compareTo(amount(heldAccount, "available_amount")) > 0);
// 只删除本测试创建的临时归档文件,不访问部署归档目录。
for (java.io.File file : directory.toFile().listFiles()) { Files.delete(file.toPath()); }
Files.delete(directory);
}
private void expectFailure(Runnable action) {
try {
action.run();
@@ -1296,7 +1403,15 @@ public class RentalBusinessTest {
tasks.dispatch(deliveryOrder);
RentalWorkers workers = new RentalWorkers(store, tasks, socket, identity);
workers.validateDeliveryIntervals();
workers.pushTasks();
ExecutorService competingPushes = Executors.newFixedThreadPool(2);
try {
Future<?> immediate = competingPushes.submit(() -> socket.push(node));
Future<?> periodic = competingPushes.submit(workers::pushTasks);
immediate.get(5, TimeUnit.SECONDS);
periodic.get(5, TimeUnit.SECONDS);
} finally {
competingPushes.shutdownNow();
}
Map<String, Object> delivered = store.one("SELECT * FROM rent_task WHERE order_id=?", deliveryOrder);
assertNotNull(delivered);
assertEquals(1, number(delivered, "delivery_count"));
@@ -1792,6 +1907,16 @@ public class RentalBusinessTest {
Map<String, Object> order = store.get("order", id, false);
assertEquals("MANUAL_REVIEW", text(order, "status"));
assertEquals("HELD", text(order, "fund_status"));
Map<String, Object> diagnostic = store.one("SELECT * FROM rent_event WHERE object_type='ORDER'"
+ " AND object_id=? AND action='DELIVERY_REVIEW'", id);
assertTrue(text(diagnostic, "reason").contains("缺少完整历史履约证明"));
List<Map<String, Object>> visible = new RentalQueries(store).list("order", 10L, 1);
assertEquals(text(diagnostic, "reason"), text(visible.get(0), "fulfillment_reason"));
assertFalse(visible.get(0).containsKey("review_evidence"));
assertTrue(new RentalQueries(store).list("order", 999L, 1).isEmpty());
store.execute("DELETE FROM rent_event WHERE id=?", diagnostic.get("id"));
assertTrue(text(new RentalQueries(store).list("order", 10L, 1).get(0), "fulfillment_reason")
.contains("缺少完整历史履约证明"));
expectFailure(() -> tasks.resolveRecovered(id, 99, "not recovered"));
store.update("order", id, map("next_reclaim_at", after(-1)));
tasks.reclaim(id);
@@ -1815,6 +1940,31 @@ public class RentalBusinessTest {
assertEquals("FAILED", text(store.get("order", id, false), "status"));
}
@Test
public void insufficientQuantityAndExpiredLeaseAreBothRecordedWithoutCharging() {
verifiedResourceQuantity = 1;
verificationBlockAgeSeconds = 100000;
long id = confirmed("INSUFFICIENT-EXPIRED");
Map<String, Object> order = store.get("order", id, false);
assertEquals("MANUAL_REVIEW", text(order, "status"));
assertEquals("HELD", text(order, "fund_status"));
String reason = text(new RentalQueries(store).list("order", null, 1).get(0), "fulfillment_reason");
assertTrue(reason.contains("实际核验资源数量不足"));
assertTrue(reason.contains("核验完成时租期已结束"));
assertFalse(reason.contains("缺少完整历史履约证明"));
}
@Test
public void fulfillmentDiagnosticsRespectBoundaryAndDoNotGuessMissingProofQuantity() {
java.time.Instant expiry = java.time.Instant.parse("2026-10-31T12:00:00Z");
assertEquals("", RentalDeliveryDiagnostics.explain(true, 18L, 18, expiry, expiry.minusMillis(1)));
assertTrue(RentalDeliveryDiagnostics.explain(true, 18L, 18, expiry, expiry).contains("租期已结束"));
assertTrue(RentalDeliveryDiagnostics.explain(false, null, 18, expiry, expiry.minusMillis(1))
.contains("缺少完整历史履约证明"));
assertFalse(RentalDeliveryDiagnostics.explain(false, null, 18, expiry, expiry.minusMillis(1))
.contains("实际核验资源数量不足"));
}
@Test
public void merchantAndSupplierSameAccountNoDoubleLockOrWrongBalance() {
store.update("node", node, map("user_id", 10));