尽量服用,和优化采样区块,交易所在区块的资源参数 获取不需要每次获取有下单租赁订单都获取一遍,应该是全局异步获取是不是就可以,帮我设计合理方案。 和清理逻辑
This commit is contained in:
1 parent
13665668ac
commit
1538cd0819
24 files changed
+1894
-230
No files matched your search
@@ -118,29 +118,21 @@ public class RentalChain {
|
||||
}
|
||||
|
||||
public Map<String, Object> snapshot(String network, String address) {
|
||||
long before = block(call(network, "/wallet/getnowblock", map()));
|
||||
JsonNode beforeBlock = call(network, "/wallet/getnowblock", map());
|
||||
long before = block(beforeBlock);
|
||||
JsonNode resources =
|
||||
call(
|
||||
network,
|
||||
"/wallet/getaccountresource",
|
||||
map("address", address, "visible", true));
|
||||
long energy =
|
||||
call(
|
||||
network,
|
||||
"/wallet/getcandelegatedmaxsize",
|
||||
map("owner_address", address, "type", 1, "visible", true))
|
||||
.path("max_size")
|
||||
.asLong(-1);
|
||||
long bandwidth =
|
||||
call(
|
||||
network,
|
||||
"/wallet/getcandelegatedmaxsize",
|
||||
map("owner_address", address, "type", 0, "visible", true))
|
||||
.path("max_size")
|
||||
.asLong(-1);
|
||||
long after = block(call(network, "/wallet/getnowblock", map()));
|
||||
long energy = delegatable(network, address, 1);
|
||||
long bandwidth = delegatable(network, address, 0);
|
||||
JsonNode afterBlock = call(network, "/wallet/getnowblock", map());
|
||||
long after = block(afterBlock);
|
||||
require(
|
||||
before >= 0 && before == after && energy >= 0 && bandwidth >= 0,
|
||||
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()),
|
||||
"快照跨区块或本金查询不完整,请重试");
|
||||
Map<String, Object> result =
|
||||
map(
|
||||
@@ -178,9 +170,30 @@ public class RentalChain {
|
||||
&& number(result, "total_bandwidth_limit") > 0
|
||||
&& number(result, "total_bandwidth_weight") > 0,
|
||||
"全网参数不完整");
|
||||
if (embeddedHistory && historyService != null) {
|
||||
// 复用本次夹读,不再为每个订单额外请求全网资源参数;不读取旧rent_wallet快照。
|
||||
try {
|
||||
historyService.getObject().offerParameters(network, beforeBlock, afterBlock, resources);
|
||||
} catch (RuntimeException ex) {
|
||||
log.warn("钱包全局参数采样未入库 network={},独立采样器将继续重试", network);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/** protobuf省略零字段的空对象表示0;显式错误和非整数绝不能当作0。 */
|
||||
private long delegatable(String network, String address, int type) {
|
||||
JsonNode row = call(network, "/wallet/getcandelegatedmaxsize",
|
||||
map("owner_address", address, "type", type, "visible", true));
|
||||
require(row.isObject() && (row.size() == 0 || row.has("max_size"))
|
||||
&& !row.has("Error") && !row.has("error") && !row.has("code") && !row.has("result"),
|
||||
"可代理本金查询失败");
|
||||
JsonNode value = row.path("max_size");
|
||||
require(value.isMissingNode() || (value.isIntegralNumber() && value.canConvertToLong()
|
||||
&& value.longValue() >= 0), "可代理本金响应无效");
|
||||
return value.isMissingNode() ? 0 : value.longValue();
|
||||
}
|
||||
|
||||
public long relation(String network, String owner, String receiver, String resource) {
|
||||
JsonNode rows =
|
||||
call(
|
||||
@@ -278,6 +291,8 @@ public class RentalChain {
|
||||
Map<String, Object> archived = historyService.getObject().proof(
|
||||
network, txId, height, owner, receiver, text(task, "resource_type"));
|
||||
if (archived == null) {
|
||||
result.put("delivery_evidence_gap", historyService.getObject().missingProofCode(
|
||||
network, height, owner, receiver, text(task, "resource_type")));
|
||||
// 参数漏采或缺少派单前基线:保留原有MANUAL_REVIEW路径,绝不降级为当前快照。
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.ruoyi.system.rental;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/** 履约核验说明只使用可信布尔值、精确数量和UTC时间,不接收RPC异常原文。 */
|
||||
final class RentalDeliveryDiagnostics {
|
||||
private RentalDeliveryDiagnostics() { }
|
||||
|
||||
static String evidenceGap(String code) {
|
||||
switch (code) {
|
||||
case "BLOCK_NOT_ARCHIVED": return "目标交易区块尚未归档";
|
||||
case "PARAMETERS_MISSING": return "目标交易区块缺少当时的全网资源参数,不能用当前参数替代";
|
||||
case "BASELINE_MISSING": return "缺少委托交易之前已确认的地址对关系基线";
|
||||
case "HISTORY_INCOMPLETE": return "历史区块或关系证据不完整";
|
||||
default: return "";
|
||||
}
|
||||
}
|
||||
|
||||
static String explain(boolean proven, Long verified, long target, Instant expires, Instant checked) {
|
||||
List<String> reasons = new ArrayList<>();
|
||||
if (!proven) {
|
||||
reasons.add("缺少完整历史履约证明,无法确认委托区块的实际资源数量");
|
||||
} else if (verified == null) {
|
||||
reasons.add("履约证据未包含已核验资源数量");
|
||||
} else if (verified < target) {
|
||||
reasons.add("实际核验资源数量不足:已核验=" + verified + ",订单目标=" + target);
|
||||
}
|
||||
if (expires == null || checked == null) {
|
||||
reasons.add("缺少租期或核验时间,无法确认是否在有效租期内完成核验");
|
||||
} else if (!expires.isAfter(checked)) {
|
||||
reasons.add("核验完成时租期已结束:租期截止=" + expires + ",核验时间=" + checked);
|
||||
}
|
||||
return String.join(";", reasons);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package com.ruoyi.system.rental;
|
||||
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.context.event.EventListener;
|
||||
import org.springframework.stereotype.Component;
|
||||
import javax.annotation.PostConstruct;
|
||||
import javax.annotation.PreDestroy;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
/** 有界异步派单/推送;链上查询不占用下单HTTP线程,队列拥塞由持久化扫描兜底。 */
|
||||
@Component
|
||||
@lombok.extern.slf4j.Slf4j
|
||||
@ConditionalOnProperty(name = "rental.enabled", havingValue = "true")
|
||||
public class RentalDeliveryDispatcher {
|
||||
private final ObjectProvider<RentalTasks> tasks;
|
||||
private final ObjectProvider<RentalSocket> socket;
|
||||
private final Set<String> running = ConcurrentHashMap.newKeySet();
|
||||
private ThreadPoolExecutor executor;
|
||||
@Value("${rental.delivery.workers:4}")
|
||||
private int workers = 4;
|
||||
@Value("${rental.delivery.queue-capacity:200}")
|
||||
private int capacity = 200;
|
||||
|
||||
public RentalDeliveryDispatcher(ObjectProvider<RentalTasks> tasks, ObjectProvider<RentalSocket> socket) {
|
||||
this.tasks = tasks;
|
||||
this.socket = socket;
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
public void start() {
|
||||
RentalValues.require(workers >= 1 && workers <= 32 && capacity >= 1 && capacity <= 10000,
|
||||
"即时调度线程/队列配置越界");
|
||||
AtomicInteger sequence = new AtomicInteger();
|
||||
executor = new ThreadPoolExecutor(workers, workers, 0, TimeUnit.MILLISECONDS,
|
||||
new ArrayBlockingQueue<>(capacity), action -> {
|
||||
Thread thread = new Thread(action, "rental-delivery-" + sequence.incrementAndGet());
|
||||
thread.setDaemon(true);
|
||||
return thread;
|
||||
}, new ThreadPoolExecutor.AbortPolicy());
|
||||
}
|
||||
|
||||
@EventListener
|
||||
public void receive(RentalDeliveryEvents event) {
|
||||
enqueue(event.order, event.id);
|
||||
}
|
||||
|
||||
public void dispatch(long orderId) {
|
||||
enqueue(true, orderId);
|
||||
}
|
||||
|
||||
private void enqueue(boolean order, long id) {
|
||||
String key = (order ? "O" : "N") + id;
|
||||
if (!running.add(key)) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
executor.execute(() -> {
|
||||
try {
|
||||
if (order) {
|
||||
tasks.getObject().dispatch(id);
|
||||
} else {
|
||||
socket.getObject().push(id);
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
log.warn("即时租赁调度待扫描重试 order={} id={} diagnostic={}",
|
||||
order, id, RentalDiagnostics.describe(ex));
|
||||
} finally {
|
||||
running.remove(key);
|
||||
}
|
||||
});
|
||||
} catch (RejectedExecutionException ex) {
|
||||
running.remove(key);
|
||||
log.warn("即时租赁调度队列已满,持久化扫描将恢复 order={} id={}", order, id);
|
||||
}
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
public void close() {
|
||||
if (executor != null) {
|
||||
executor.shutdownNow();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.ruoyi.system.rental;
|
||||
|
||||
import org.springframework.context.ApplicationEventPublisher;
|
||||
import org.springframework.transaction.support.TransactionSynchronizationAdapter;
|
||||
import org.springframework.transaction.support.TransactionSynchronizationManager;
|
||||
|
||||
/** 提交成功才触发网络工作;回滚不发送,漏送由持久化扫描恢复。 */
|
||||
final class RentalDeliveryEvents {
|
||||
final boolean order;
|
||||
final long id;
|
||||
|
||||
RentalDeliveryEvents(boolean order, long id) {
|
||||
this.order = order;
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
static void afterCommit(ApplicationEventPublisher publisher, boolean order, long id) {
|
||||
if (publisher == null) {
|
||||
return;
|
||||
}
|
||||
Runnable publish = () -> publisher.publishEvent(new RentalDeliveryEvents(order, id));
|
||||
if (TransactionSynchronizationManager.isSynchronizationActive()
|
||||
&& TransactionSynchronizationManager.isActualTransactionActive()) {
|
||||
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
|
||||
@Override
|
||||
public void afterCommit() {
|
||||
publish.run();
|
||||
}
|
||||
});
|
||||
} else {
|
||||
publish.run();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package com.ruoyi.system.rental;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.springframework.stereotype.Component;
|
||||
import java.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
/** 删除前将完整批次写入不可变JSON归档。写盘、原子发布和校验任一步失败都阻止数据库删除。 */
|
||||
@Component
|
||||
public class RentalHistoryArchive {
|
||||
private final ObjectMapper json;
|
||||
|
||||
public RentalHistoryArchive(ObjectMapper json) {
|
||||
this.json = json;
|
||||
}
|
||||
|
||||
public String save(Path directory, Map<String, Object> batch) {
|
||||
try {
|
||||
Files.createDirectories(directory);
|
||||
byte[] data = json.writeValueAsBytes(batch);
|
||||
String digest = hex(MessageDigest.getInstance("SHA-256").digest(data));
|
||||
String name = batch.get("network") + "-" + UUID.randomUUID() + "-" + digest + ".json";
|
||||
Path pending = directory.resolve(name + ".pending");
|
||||
Path published = directory.resolve(name);
|
||||
try (FileChannel channel = FileChannel.open(pending, StandardOpenOption.CREATE_NEW,
|
||||
StandardOpenOption.WRITE)) {
|
||||
ByteBuffer buffer = ByteBuffer.wrap(data);
|
||||
while (buffer.hasRemaining()) {
|
||||
channel.write(buffer);
|
||||
}
|
||||
channel.force(true);
|
||||
}
|
||||
// 不退化成非原子覆盖;归档目录必须使用支持同目录原子移动的持久文件系统。
|
||||
Files.move(pending, published, StandardCopyOption.ATOMIC_MOVE);
|
||||
String actual = hex(MessageDigest.getInstance("SHA-256").digest(Files.readAllBytes(published)));
|
||||
if (!digest.equals(actual)) {
|
||||
throw new IOException("history archive checksum mismatch");
|
||||
}
|
||||
return name;
|
||||
} catch (Exception ex) {
|
||||
// 不暴露配置路径或归档原文。数据库事务回滚后保留已生成文件,允许重试产生冗余归档。
|
||||
throw new IllegalStateException("历史归档写入或校验失败,本批次不删除", ex);
|
||||
}
|
||||
}
|
||||
|
||||
private static String hex(byte[] bytes) {
|
||||
StringBuilder result = new StringBuilder(bytes.length * 2);
|
||||
for (byte value : bytes) {
|
||||
result.append(String.format("%02x", value & 255));
|
||||
}
|
||||
return result.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,278 @@
|
||||
package com.ruoyi.system.rental;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
import javax.annotation.PostConstruct;
|
||||
import java.nio.file.Paths;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import static com.ruoyi.system.rental.RentalValues.*;
|
||||
|
||||
/**
|
||||
* 只清理历史表,不修改订单、任务、交易或资金记录。
|
||||
* 每网络租约防重入,每批事务锁住网络游标后重新计算保护水位;证明读取、基线写入、参数归档共用该行锁。
|
||||
* 清理采用保守的网络低水位:一个久悬订单可能保护整个网络的一段旧数据,宁可多留,不能截断证据。
|
||||
*/
|
||||
@Component
|
||||
@lombok.extern.slf4j.Slf4j
|
||||
@ConditionalOnProperty(name = {"rental.enabled", "rental.history.embedded-enabled"}, havingValue = "true")
|
||||
public class RentalHistoryCleaner {
|
||||
private final RentalStore store;
|
||||
private final ObjectMapper json;
|
||||
private final RentalHistoryArchive archive;
|
||||
private final TransactionTemplate transaction;
|
||||
|
||||
@Value("${rental.history.cleanup.enabled:true}")
|
||||
private boolean enabled = true;
|
||||
@Value("${rental.history.networks:NILE}")
|
||||
private String networks = "NILE";
|
||||
@Value("${rental.history.cleanup.retention-days:30}")
|
||||
private int retentionDays = 30;
|
||||
@Value("${rental.history.cleanup.batch-size:500}")
|
||||
private int batchSize = 500;
|
||||
@Value("${rental.history.cleanup.max-batches:200}")
|
||||
private int maxBatches = 200;
|
||||
@Value("${rental.history.cleanup.archive-directory:./data/rental-history-archive}")
|
||||
private String archiveDirectory = "./data/rental-history-archive";
|
||||
|
||||
/** 限制单批保护关系计算的内存和锁持有时间,超量时停止删除并告警,不能忽略剩余任务。 */
|
||||
private static final int MAX_PROTECTED_TASKS = 100000;
|
||||
|
||||
public RentalHistoryCleaner(RentalStore store, ObjectMapper json, RentalHistoryArchive archive,
|
||||
PlatformTransactionManager manager) {
|
||||
this.store = store;
|
||||
this.json = json;
|
||||
this.archive = archive;
|
||||
transaction = new TransactionTemplate(manager);
|
||||
transaction.setTimeout(30);
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
public void validate() {
|
||||
require(retentionDays >= 1 && retentionDays <= 3650, "历史保留天数必须为1到3650");
|
||||
require(batchSize >= 1 && batchSize <= 1000, "历史清理批量必须为1到1000");
|
||||
require(maxBatches >= 1 && maxBatches <= 10000, "历史清理批次数必须为1到10000");
|
||||
require(archiveDirectory != null && !archiveDirectory.trim().isEmpty(), "历史归档目录不能为空");
|
||||
}
|
||||
|
||||
/** UTC低峰定时运行;每批有上限,关闭开关不会影响原本的采样确认和分叉丢弃。 */
|
||||
@Scheduled(cron = "${rental.history.cleanup.cron:0 15 3 * * ?}", zone = "UTC")
|
||||
public void scheduled() {
|
||||
if (!enabled) {
|
||||
return;
|
||||
}
|
||||
Set<String> selected = new LinkedHashSet<>();
|
||||
for (String value : networks.split(",")) {
|
||||
selected.add(network(value.trim()));
|
||||
}
|
||||
for (String network : selected) {
|
||||
try {
|
||||
clean(network);
|
||||
} catch (Exception ex) {
|
||||
log.warn("历史清理失败,本批事务已回滚 network={} diagnostic={}",
|
||||
network, RentalDiagnostics.describe(ex));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public int clean(String network) {
|
||||
network(network);
|
||||
validate();
|
||||
if (!enabled) {
|
||||
return 0;
|
||||
}
|
||||
String lease = id("HC");
|
||||
Boolean acquired = transaction.execute(status -> {
|
||||
Map<String, Object> cursor = RentalHistoryGuard.lock(store, network);
|
||||
return cursor.get("scanned_height") != null && store.execute("UPDATE rent_history_cursor"
|
||||
+ " SET cleanup_owner=?,cleanup_until=TIMESTAMPADD(SECOND,60,UTC_TIMESTAMP(3))"
|
||||
+ " WHERE network=? AND (cleanup_until IS NULL OR cleanup_until<UTC_TIMESTAMP(3))",
|
||||
lease, network) == 1;
|
||||
});
|
||||
if (!Boolean.TRUE.equals(acquired)) {
|
||||
return 0;
|
||||
}
|
||||
int total = 0;
|
||||
LocalDateTime cutoff = now().minusDays(retentionDays);
|
||||
try {
|
||||
for (int i = 0; i < maxBatches && !Thread.currentThread().isInterrupted(); i++) {
|
||||
int removed = transaction.execute(status -> cleanBatch(network, lease, cutoff));
|
||||
total += removed;
|
||||
if (removed == 0) {
|
||||
log.info("历史清理结束 network={} removed={} retentionDays={}", network, total, retentionDays);
|
||||
return total;
|
||||
}
|
||||
}
|
||||
log.warn("历史清理达到批次上限或被中断,剩余数据留待下次 network={} removed={}", network, total);
|
||||
return total;
|
||||
} finally {
|
||||
store.execute("UPDATE rent_history_cursor SET cleanup_owner=NULL,cleanup_until=NULL"
|
||||
+ " WHERE network=? AND cleanup_owner=?", network, lease);
|
||||
}
|
||||
}
|
||||
|
||||
private int cleanBatch(String network, String lease, LocalDateTime cutoff) {
|
||||
Map<String, Object> cursor = RentalHistoryGuard.lock(store, network);
|
||||
require(lease.equals(text(cursor, "cleanup_owner")) && validLease(network, lease), "历史清理租约失效");
|
||||
store.execute("UPDATE rent_history_cursor SET cleanup_until=TIMESTAMPADD(SECOND,60,UTC_TIMESTAMP(3))"
|
||||
+ " WHERE network=? AND cleanup_owner=?", network, lease);
|
||||
long floor = protectedFloor(network, number(cursor, "scanned_height"), cutoff);
|
||||
if (floor <= 0) {
|
||||
return 0;
|
||||
}
|
||||
long cutoffMillis = cutoff.toInstant(java.time.ZoneOffset.UTC).toEpochMilli();
|
||||
// 同时检查链上时间和入库时间,刚补采的老区块仍有完整保留期。
|
||||
List<Map<String, Object>> events = store.rows("SELECT e.* FROM rent_history_event e"
|
||||
+ " JOIN rent_history_block b ON b.network=e.network AND b.block_height=e.block_height"
|
||||
+ " WHERE e.network=? AND e.block_height<? AND b.block_time<? AND b.created_at<?"
|
||||
+ " AND e.created_at<? AND b.events_complete=1 ORDER BY e.block_height,e.tx_index LIMIT " + batchSize,
|
||||
network, floor, cutoffMillis, cutoff, cutoff);
|
||||
// 有事件的区块在后续批次再删除,单个高交易量区块也不会造成无界归档/删除。
|
||||
List<Map<String, Object>> blocks = store.rows("SELECT b.* FROM rent_history_block b"
|
||||
+ " WHERE b.network=? AND b.block_height<? AND b.block_time<? AND b.created_at<?"
|
||||
+ " AND b.events_complete=1 AND NOT EXISTS (SELECT 1 FROM rent_history_event e"
|
||||
+ " WHERE e.network=b.network AND e.block_height=b.block_height)"
|
||||
+ " AND NOT EXISTS (SELECT 1 FROM rent_history_sample s WHERE s.network=b.network"
|
||||
+ " AND s.block_height=b.block_height) ORDER BY b.block_height LIMIT " + batchSize,
|
||||
network, floor, cutoffMillis, cutoff);
|
||||
List<Map<String, Object>> anchors = store.rows("SELECT * FROM rent_history_anchor"
|
||||
+ " WHERE network=? AND block_height<? AND created_at<? ORDER BY block_height LIMIT " + batchSize,
|
||||
network, floor, cutoff);
|
||||
// 缓冲仅删除已存在完全相同确认参数的冗余记录,未确认、冲突或错误采样交给确认通道处理。
|
||||
List<Map<String, Object>> samples = store.rows("SELECT s.* FROM rent_history_sample s"
|
||||
+ " JOIN rent_history_block b ON b.network=s.network AND b.block_height=s.block_height"
|
||||
+ " WHERE s.network=? AND b.parameters_at IS NOT NULL AND b.block_id=s.block_id"
|
||||
+ " AND b.energy_limit=s.energy_limit AND b.energy_weight=s.energy_weight"
|
||||
+ " AND b.bandwidth_limit=s.bandwidth_limit AND b.bandwidth_weight=s.bandwidth_weight"
|
||||
+ " ORDER BY s.block_height LIMIT " + batchSize, network);
|
||||
int count = events.size() + blocks.size() + anchors.size() + samples.size();
|
||||
if (count == 0) {
|
||||
return 0;
|
||||
}
|
||||
String file = archive.save(Paths.get(archiveDirectory).toAbsolutePath().normalize(),
|
||||
map("format", "RENT_HISTORY_ARCHIVE_V1", "network", network, "cutoff", cutoff.toString(),
|
||||
"protected_from_height", floor, "cursor", cursor,
|
||||
"events", events, "blocks", blocks, "anchors", anchors, "samples", samples));
|
||||
require(validLease(network, lease), "归档期间清理租约失效,本批次不删除");
|
||||
for (Map<String, Object> row : events) {
|
||||
store.execute("DELETE FROM rent_history_event WHERE network=? AND tx_id=?", network, row.get("tx_id"));
|
||||
}
|
||||
for (Map<String, Object> row : blocks) {
|
||||
store.execute("DELETE FROM rent_history_block WHERE network=? AND block_height=?", network, row.get("block_height"));
|
||||
}
|
||||
for (Map<String, Object> row : anchors) {
|
||||
store.execute("DELETE FROM rent_history_anchor WHERE network=? AND owner_address=?"
|
||||
+ " AND receiver_address=? AND resource_type=? AND block_height=?", network,
|
||||
row.get("owner_address"), row.get("receiver_address"), row.get("resource_type"), row.get("block_height"));
|
||||
}
|
||||
for (Map<String, Object> row : samples) {
|
||||
store.execute("DELETE FROM rent_history_sample WHERE network=? AND block_height=? AND block_id=?",
|
||||
network, row.get("block_height"), row.get("block_id"));
|
||||
}
|
||||
log.info("历史清理批次 network={} floor={} events={} blocks={} anchors={} samples={} archive={}",
|
||||
network, floor, events.size(), blocks.size(), anchors.size(), samples.size(), file);
|
||||
return count;
|
||||
}
|
||||
|
||||
private boolean validLease(String network, String lease) {
|
||||
return store.one("SELECT network FROM rent_history_cursor WHERE network=? AND cleanup_owner=?"
|
||||
+ " AND cleanup_until>UTC_TIMESTAMP(3)", network, lease) != null;
|
||||
}
|
||||
|
||||
/** 订单/任务状态只作为保留条件,绝不由清理器推定失败、释放资源或资金。 */
|
||||
private long protectedFloor(String network, long scanned, LocalDateTime cutoff) {
|
||||
long floor = Math.max(0, scanned - RentalHistoryService.MAX_REPLAY_BLOCKS);
|
||||
List<Map<String, Object>> tasks = store.rows("SELECT t.intent,t.resource_type,o.id AS order_id,"
|
||||
+ "o.network AS order_network,o.resource_type AS order_resource_type,"
|
||||
+ "x.block_height FROM rent_task t LEFT JOIN rent_order o ON o.id=t.order_id"
|
||||
+ " LEFT JOIN rent_transaction x ON x.task_id=t.id WHERE t.network=?"
|
||||
+ " AND t.resource_type IN ('ENERGY','BANDWIDTH') AND (o.id IS NULL"
|
||||
+ " OR o.network<>t.network OR o.resource_type<>t.resource_type OR o.status IS NULL"
|
||||
+ " OR o.fund_status IS NULL OR o.reclaim_status IS NULL OR t.status IS NULL"
|
||||
+ " OR t.reservation_status IS NULL"
|
||||
+ " OR o.status NOT IN ('SUCCESS','FAILED','CANCELLED') OR o.fund_status='HELD'"
|
||||
+ " OR o.relation_slot IS NOT NULL OR o.reclaim_status NOT IN ('DONE','NOT_REQUIRED','NOT_STARTED')"
|
||||
+ " OR o.service_expires_at>? OR o.updated_at>=? OR t.updated_at>=? OR x.updated_at>=?"
|
||||
+ " OR t.status NOT IN ('VERIFIED','REJECTED','FAILED') OR t.wallet_execution_slot IS NOT NULL"
|
||||
+ " OR t.reservation_status='HELD' OR (x.id IS NOT NULL AND x.status NOT IN ('CONFIRMED','FAILED')))"
|
||||
+ " LIMIT " + (MAX_PROTECTED_TASKS + 1), network, now(), cutoff, cutoff, cutoff);
|
||||
if (tasks.size() > MAX_PROTECTED_TASKS) {
|
||||
log.warn("历史保护任务超出单批上限,停止本网络清理 network={}", network);
|
||||
return 0;
|
||||
}
|
||||
Map<String, Map<String, Object>> relations = new LinkedHashMap<>();
|
||||
for (Map<String, Object> task : tasks) {
|
||||
if (task.get("order_id") == null || !network.equals(text(task, "order_network"))
|
||||
|| !text(task, "resource_type").equals(text(task, "order_resource_type"))) {
|
||||
return 0;
|
||||
}
|
||||
try {
|
||||
// 使用签发时冻结的owner/receiver,禁止用后来换绑的钱包地址定位旧证据。
|
||||
JsonNode intent = json.readTree(text(task, "intent"));
|
||||
String owner = RentalHistoryService.addressHex(intent.path("owner").asText());
|
||||
String receiver = RentalHistoryService.addressHex(intent.path("receiver").asText());
|
||||
String type = text(task, "resource_type");
|
||||
String key = owner + ":" + receiver + ":" + type;
|
||||
Map<String, Object> relation = relations.get(key);
|
||||
long target = task.get("block_height") == null ? Long.MAX_VALUE : number(task, "block_height");
|
||||
if (relation == null) {
|
||||
relations.put(key, map("owner", owner, "receiver", receiver, "type", type, "target", target));
|
||||
} else {
|
||||
relation.put("target", Math.min(number(relation, "target"), target));
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
log.warn("受保护任务基线无法定位,停止本网络清理 network={}", network);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
// 按地址对去重并批量查基线,避免每个任务一次SQL造成长时间占用保护锁。
|
||||
List<Map<String, Object>> pairs = new ArrayList<>(relations.values());
|
||||
for (int offset = 0; offset < pairs.size(); offset += 100) {
|
||||
List<Map<String, Object>> selected = pairs.subList(offset, Math.min(pairs.size(), offset + 100));
|
||||
StringBuilder sql = new StringBuilder("SELECT owner_address,receiver_address,resource_type,"
|
||||
+ "MIN(block_height) AS first_height FROM rent_history_anchor WHERE network=? AND (");
|
||||
List<Object> args = new ArrayList<>();
|
||||
args.add(network);
|
||||
for (int i = 0; i < selected.size(); i++) {
|
||||
if (i > 0) { sql.append(" OR "); }
|
||||
sql.append("(owner_address=? AND receiver_address=? AND resource_type=?)");
|
||||
args.add(selected.get(i).get("owner"));
|
||||
args.add(selected.get(i).get("receiver"));
|
||||
args.add(selected.get(i).get("type"));
|
||||
}
|
||||
sql.append(") GROUP BY owner_address,receiver_address,resource_type");
|
||||
List<Map<String, Object>> found = store.rows(sql.toString(), args.toArray());
|
||||
if (found.size() != selected.size()) {
|
||||
log.warn("受保护地址对缺少基线,停止本网络清理 network={}", network);
|
||||
return 0;
|
||||
}
|
||||
for (Map<String, Object> anchor : found) {
|
||||
String key = text(anchor, "owner_address") + ":" + text(anchor, "receiver_address")
|
||||
+ ":" + text(anchor, "resource_type");
|
||||
if (number(anchor, "first_height") >= number(relations.get(key), "target")) {
|
||||
return 0;
|
||||
}
|
||||
floor = Math.min(floor, number(anchor, "first_height"));
|
||||
}
|
||||
}
|
||||
// 不完整业务数据也应保守处理,不能因缺任务就跳过已选定供应钱包的在途订单。
|
||||
Map<String, Object> orphan = store.one("SELECT o.id FROM rent_order o WHERE o.network=?"
|
||||
+ " AND o.resource_type IN ('ENERGY','BANDWIDTH') AND o.wallet_id IS NOT NULL"
|
||||
+ " AND (o.status NOT IN ('SUCCESS','FAILED','CANCELLED') OR o.fund_status='HELD'"
|
||||
+ " OR o.relation_slot IS NOT NULL OR o.reclaim_status NOT IN ('DONE','NOT_REQUIRED','NOT_STARTED'))"
|
||||
+ " AND NOT EXISTS (SELECT 1 FROM rent_task t WHERE t.order_id=o.id"
|
||||
+ " AND t.network=o.network AND t.resource_type=o.resource_type) LIMIT 1", network);
|
||||
return orphan == null ? floor : 0;
|
||||
}
|
||||
}
|
||||
@@ -44,24 +44,31 @@ public class RentalHistoryCollector {
|
||||
selected.add(RentalValues.network(name.trim()));
|
||||
}
|
||||
AtomicInteger sequence = new AtomicInteger();
|
||||
executor = new ScheduledThreadPoolExecutor(selected.size(), action -> {
|
||||
executor = new ScheduledThreadPoolExecutor(selected.size() * 3, action -> {
|
||||
Thread thread = new Thread(action, "rental-history-" + sequence.incrementAndGet());
|
||||
thread.setDaemon(true);
|
||||
return thread;
|
||||
});
|
||||
executor.setRemoveOnCancelPolicy(true);
|
||||
for (String network : selected) {
|
||||
executor.scheduleWithFixedDelay(() -> {
|
||||
schedule(network, "参数采样", () -> service.sample(network));
|
||||
schedule(network, "参数确认", () -> service.confirmSamples(network));
|
||||
schedule(network, "事件扫描", () -> service.collect(network));
|
||||
}
|
||||
}
|
||||
|
||||
private void schedule(String network, String operation, Runnable action) {
|
||||
executor.scheduleWithFixedDelay(() -> {
|
||||
try {
|
||||
service.collect(network);
|
||||
action.run();
|
||||
} catch (RentalHistoryService.PendingConfirmationException ex) {
|
||||
LOG.debug("租赁历史采样等待区块确认,network={}", network);
|
||||
} catch (Exception ex) {
|
||||
// 不记录异常原文,避免RPC配置、认证头或供应商数据进入日志。
|
||||
LOG.warn("租赁历史采集未完成,network={},请查看受保护的历史状态接口", network);
|
||||
LOG.warn("租赁历史采集未完成 network={} operation={} diagnostic={}",
|
||||
network, operation, RentalDiagnostics.describe(ex));
|
||||
}
|
||||
}, 0, interval, TimeUnit.MILLISECONDS);
|
||||
}
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.ruoyi.system.rental;
|
||||
|
||||
import java.util.Map;
|
||||
import org.springframework.dao.DuplicateKeyException;
|
||||
import org.springframework.transaction.support.TransactionSynchronizationManager;
|
||||
import static com.ruoyi.system.rental.RentalValues.*;
|
||||
|
||||
/** 历史读写和清理共用网络游标行锁。只在短数据库事务内持锁,禁止在锁内调用RPC。 */
|
||||
final class RentalHistoryGuard {
|
||||
private RentalHistoryGuard() { }
|
||||
|
||||
static Map<String, Object> lock(RentalStore store, String network) {
|
||||
require(TransactionSynchronizationManager.isActualTransactionActive(), "历史保护锁必须在事务内获取");
|
||||
Map<String, Object> row = store.one("SELECT * FROM rent_history_cursor WHERE network=? FOR UPDATE", network);
|
||||
if (row == null) {
|
||||
try {
|
||||
store.execute("INSERT INTO rent_history_cursor (network,updated_at) VALUES (?,?)", network, now());
|
||||
} catch (DuplicateKeyException ex) {
|
||||
// 首次基线、采样确认和扫描可以并发启动;最终必须锁定同一行。
|
||||
}
|
||||
row = store.one("SELECT * FROM rent_history_cursor WHERE network=? FOR UPDATE", network);
|
||||
}
|
||||
require(row != null, "历史网络保护行缺失");
|
||||
return row;
|
||||
}
|
||||
}
|
||||
@@ -32,7 +32,7 @@ import java.util.Map;
|
||||
*/
|
||||
@Service
|
||||
public class RentalHistoryService {
|
||||
private static final int MAX_REPLAY_BLOCKS = 10000;
|
||||
static final int MAX_REPLAY_BLOCKS = 10000;
|
||||
private static final String DEFAULT_PROBE = "T9yD14Nj9j7xAB4dbGeiX9h8unkKHxuWwb";
|
||||
private final RentalStore store;
|
||||
private final RentalChain chain;
|
||||
@@ -50,8 +50,14 @@ public class RentalHistoryService {
|
||||
@Value("${rental.confirmations:19}")
|
||||
private long confirmations = 19;
|
||||
|
||||
/** 未确认采样只驻留内存;重启丢弃,禁止回填或使用其他高度参数替代。 */
|
||||
private final Map<String, Snapshot> pendingSnapshots = new java.util.concurrent.ConcurrentHashMap<>();
|
||||
/** 同一进程每网络最多一个采样;不同网络和事件扫描互不阻塞。 */
|
||||
private final java.util.Set<String> sampling = java.util.concurrent.ConcurrentHashMap.newKeySet();
|
||||
|
||||
@Value("${rental.history.parameter-grace-seconds:120}")
|
||||
private long parameterGraceSeconds = 120;
|
||||
|
||||
@Value("${rental.history.max-sample-age-seconds:15}")
|
||||
private long maxSampleAgeSeconds = 15;
|
||||
|
||||
/** 确认预热属于正常等待,不作为RPC故障反复输出错误堆栈。 */
|
||||
public static final class PendingConfirmationException extends IllegalStateException {
|
||||
@@ -69,6 +75,92 @@ public class RentalHistoryService {
|
||||
this.transaction = new TransactionTemplate(manager);
|
||||
}
|
||||
|
||||
/** 全局采样按网络/高度去重;钱包刷新可直接提交同一次夹读,绝不从旧钱包快照回填。 */
|
||||
public void offerParameters(String network, JsonNode before, JsonNode after, JsonNode resources) {
|
||||
network(network);
|
||||
if (!Arrays.stream(enabledNetworks.split(",")).anyMatch(value -> network.equals(value.trim()))) {
|
||||
return;
|
||||
}
|
||||
require(height(before) == height(after) && hash(before).equals(hash(after)), "参数采样跨区块");
|
||||
long[] totals = parameters(resources);
|
||||
transaction.execute(status -> {
|
||||
RentalHistoryGuard.lock(store, network);
|
||||
try {
|
||||
store.execute("INSERT INTO rent_history_sample (network,block_height,block_id,"
|
||||
+ "energy_limit,energy_weight,bandwidth_limit,bandwidth_weight,created_at)"
|
||||
+ " VALUES (?,?,?,?,?,?,?,?)", network, height(before), hash(before),
|
||||
totals[0], totals[1], totals[2], totals[3], now());
|
||||
} catch (DuplicateKeyException ex) {
|
||||
// 同高度重复读允许复用,但不能让不一致的网关响应覆盖已采事实。
|
||||
}
|
||||
Map<String, Object> row = store.one("SELECT * FROM rent_history_sample"
|
||||
+ " WHERE network=? AND block_height=? FOR UPDATE", network, height(before));
|
||||
require(row != null && hash(before).equals(text(row, "block_id"))
|
||||
&& number(row, "energy_limit") == totals[0] && number(row, "energy_weight") == totals[1]
|
||||
&& number(row, "bandwidth_limit") == totals[2] && number(row, "bandwidth_weight") == totals[3],
|
||||
"同一采样高度状态不一致,请检查RPC后端一致性");
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
/** 不等待确认;独立线程持续采样,不能被订单或补区块的RPC阻塞。 */
|
||||
public void sample(String network) {
|
||||
network(network);
|
||||
if (!sampling.add(network)) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
for (int attempt = 0; attempt < 3; attempt++) {
|
||||
JsonNode before = chain.call(network, "/wallet/getnowblock", map());
|
||||
Map<String, Object> existing = store.one("SELECT block_id FROM rent_history_sample"
|
||||
+ " WHERE network=? AND block_height=?", network, height(before));
|
||||
if (existing != null && hash(before).equals(text(existing, "block_id"))) {
|
||||
return;
|
||||
}
|
||||
JsonNode resources = chain.call(network, "/wallet/getaccountresource",
|
||||
map("address", probeAddress, "visible", true));
|
||||
JsonNode after = chain.call(network, "/wallet/getnowblock", map());
|
||||
if (height(before) == height(after) && hash(before).equals(hash(after))) {
|
||||
offerParameters(network, before, after, resources);
|
||||
return;
|
||||
}
|
||||
}
|
||||
throw new IllegalStateException("最新头在采样期间变化,请重试");
|
||||
} finally {
|
||||
sampling.remove(network);
|
||||
}
|
||||
}
|
||||
|
||||
/** 待确认记录持久化跨重启保留;只有确认链同高度同哈希才提升到四张证据表。 */
|
||||
public void confirmSamples(String network) {
|
||||
network(network);
|
||||
long confirmed = height(head(network));
|
||||
for (Map<String, Object> row : store.rows("SELECT * FROM rent_history_sample WHERE network=?"
|
||||
+ " AND block_height<=? ORDER BY block_height LIMIT 200", network, confirmed)) {
|
||||
long sampledHeight = number(row, "block_height");
|
||||
JsonNode canonical = chain.call(network, "/walletsolidity/getblockbynum",
|
||||
map("num", sampledHeight, "visible", false));
|
||||
require(height(canonical) == sampledHeight, "确认采样高度不符");
|
||||
transaction.execute(status -> {
|
||||
RentalHistoryGuard.lock(store, network);
|
||||
Map<String, Object> pending = store.one("SELECT block_id FROM rent_history_sample"
|
||||
+ " WHERE network=? AND block_height=?", network, sampledHeight);
|
||||
if (pending == null || !text(row, "block_id").equals(text(pending, "block_id"))) {
|
||||
return null;
|
||||
}
|
||||
if (hash(canonical).equals(text(row, "block_id"))) {
|
||||
saveParameters(network, new Snapshot(canonical, new long[] {
|
||||
number(row, "energy_limit"), number(row, "energy_weight"),
|
||||
number(row, "bandwidth_limit"), number(row, "bandwidth_weight")}, 0, row.get("created_at")));
|
||||
}
|
||||
// 分叉采样只能丢弃,禁止把参数改标到确认链的另一个哈希。
|
||||
store.execute("DELETE FROM rent_history_sample WHERE network=? AND block_height=? AND block_id=?",
|
||||
network, sampledHeight, text(row, "block_id"));
|
||||
return null;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/** 仅接受合法TRON地址;库内统一十六进制,避免Base58大小写折叠或多种编码造成漏重放。 */
|
||||
static String addressHex(String address) {
|
||||
RentalOrders.address(address);
|
||||
@@ -106,76 +198,33 @@ public class RentalHistoryService {
|
||||
}
|
||||
|
||||
/**
|
||||
* 最新头夹读绑定采样高度;采样必须等该高度确认且哈希一致后才能用于历史证明。
|
||||
* 必须配置同一一致性FullNode(或保证会话一致性的网关),不能混用不同高度后端。
|
||||
* 确认头夹读绑定地址对基线。参数由全局独立采样,不与地址对或订单重复绑定。
|
||||
* 必须使用一致性确认节点;未知接口、错误响应或不稳定头均拒绝建基线。
|
||||
*/
|
||||
private synchronized Snapshot capture(String network, String owner, String receiver, String type) {
|
||||
String key = network + ":" + owner + ":" + receiver + ":" + type;
|
||||
// 有界缓存防止异常地址请求造成无限内存增长;过期快照不再用于新基线。
|
||||
long oldest = System.currentTimeMillis() - 10 * 60 * 1000L;
|
||||
pendingSnapshots.entrySet().removeIf(entry -> entry.getValue().sampledAt < oldest);
|
||||
require(pendingSnapshots.size() < 10000, "待确认资源采样过多,请稍后重试");
|
||||
private Snapshot capture(String network, String owner, String receiver, String type) {
|
||||
// 基线与全网参数独立。确认节点夹读成功即可使用,不再等最新头的确认周期。
|
||||
for (int attempt = 0; attempt < 3; attempt++) {
|
||||
JsonNode before = chain.call(network, "/wallet/getnowblock", map());
|
||||
long blockHeight = height(before);
|
||||
String blockId = hash(before);
|
||||
long[] totals = parameters(chain.call(network, "/wallet/getaccountresource",
|
||||
map("address", owner, "visible", true)));
|
||||
JsonNode before = head(network);
|
||||
long balance = 0;
|
||||
if (receiver != null) {
|
||||
// 锁定和非锁定本金都参与基线,锁定到期解锁不会改变合计本金。
|
||||
for (boolean locked : new boolean[] {false, true}) {
|
||||
JsonNode response = chain.call(network, "/wallet/getdelegatedresourcev2",
|
||||
map("fromAddress", owner, "toAddress", receiver,
|
||||
"lock", locked, "visible", true));
|
||||
require(!response.has("Error") && !response.has("error")
|
||||
&& (!response.has("result") || !response.path("result").isBoolean()
|
||||
|| response.path("result").asBoolean()), "确认关系查询失败");
|
||||
JsonNode rows = response.path("delegatedResource");
|
||||
require(rows.isMissingNode() || rows.isArray(), "确认关系响应结构错误");
|
||||
for (JsonNode row : rows) {
|
||||
String field = "ENERGY".equals(type)
|
||||
? "frozen_balance_for_energy" : "frozen_balance_for_bandwidth";
|
||||
// protobuf省略零字段;有值时必须为精确非负整数。
|
||||
balance = Math.addExact(balance, row.has(field)
|
||||
? positive(row.path(field), true) : 0);
|
||||
}
|
||||
for (boolean locked : new boolean[] {false, true}) {
|
||||
JsonNode response = chain.call(network, "/walletsolidity/getdelegatedresourcev2",
|
||||
map("fromAddress", owner, "toAddress", receiver, "lock", locked, "visible", true));
|
||||
require(response.isObject() && !response.has("Error") && !response.has("error")
|
||||
&& !response.has("code") && !response.has("result"), "确认关系查询失败");
|
||||
JsonNode rows = response.path("delegatedResource");
|
||||
require(response.size() == 0 || rows.isArray(), "确认关系响应结构错误");
|
||||
for (JsonNode row : rows) {
|
||||
String field = "ENERGY".equals(type)
|
||||
? "frozen_balance_for_energy" : "frozen_balance_for_bandwidth";
|
||||
balance = Math.addExact(balance, row.has(field) ? positive(row.path(field), true) : 0);
|
||||
}
|
||||
}
|
||||
JsonNode after = chain.call(network, "/wallet/getnowblock", map());
|
||||
if (blockHeight == height(after) && blockId.equals(hash(after))) {
|
||||
// 每轮继续采样,等待确认期间不能停止采样,否则会漏掉后续交易高度的参数。
|
||||
String sampleKey = key + ":" + blockHeight;
|
||||
Snapshot sampled = new Snapshot(before.deepCopy(), totals, balance);
|
||||
Snapshot original = pendingSnapshots.putIfAbsent(sampleKey, sampled);
|
||||
if (original != null) {
|
||||
if (!hash(original.block).equals(blockId)) {
|
||||
pendingSnapshots.remove(sampleKey);
|
||||
throw new IllegalStateException("未确认采样区块发生分叉,丢弃并重新采样");
|
||||
}
|
||||
require(hash(original.block).equals(blockId)
|
||||
&& Arrays.equals(original.totals, totals) && original.balance == balance,
|
||||
"同一采样高度状态不一致,请检查RPC后端一致性");
|
||||
}
|
||||
long confirmedHeight = height(head(network));
|
||||
Map.Entry<String, Snapshot> ready = pendingSnapshots.entrySet().stream()
|
||||
.filter(entry -> entry.getKey().startsWith(key + ":")
|
||||
&& height(entry.getValue().block) <= confirmedHeight)
|
||||
.min(java.util.Comparator.comparingLong(entry -> height(entry.getValue().block)))
|
||||
.orElse(null);
|
||||
if (ready == null) {
|
||||
throw new PendingConfirmationException();
|
||||
}
|
||||
Snapshot pending = ready.getValue();
|
||||
JsonNode canonical = chain.call(network, "/walletsolidity/getblockbynum",
|
||||
map("num", height(pending.block), "visible", false));
|
||||
pendingSnapshots.remove(ready.getKey());
|
||||
require(height(canonical) == height(pending.block)
|
||||
&& hash(canonical).equals(hash(pending.block)), "资源采样区块发生分叉,丢弃并重新采样");
|
||||
return pending;
|
||||
JsonNode after = head(network);
|
||||
if (height(before) == height(after) && hash(before).equals(hash(after))) {
|
||||
return new Snapshot(before.deepCopy(), null, balance);
|
||||
}
|
||||
}
|
||||
throw new IllegalStateException("最新头在采样期间变化,请重试,未记录历史证据");
|
||||
throw new IllegalStateException("确认头在基线读取期间变化,请重试");
|
||||
}
|
||||
|
||||
/** 派单前建立真实基线;非零关系拒绝派单,不用任务声明的0替代链上读取。 */
|
||||
@@ -186,10 +235,27 @@ public class RentalHistoryService {
|
||||
resource(type);
|
||||
String ownerHex = addressHex(owner);
|
||||
String receiverHex = addressHex(receiver);
|
||||
require(maxSampleAgeSeconds >= 1 && maxSampleAgeSeconds <= 300, "参数采样新鲜度必须为1到300秒");
|
||||
// 按主键倒序取最近高度,避免每次派单全表聚合越来越大的历史档案。
|
||||
Map<String, Object> healthy = store.one("SELECT created_at AS sampled_at FROM rent_history_sample"
|
||||
+ " WHERE network=? ORDER BY block_height DESC LIMIT 1", network);
|
||||
Map<String, Object> archived = store.one("SELECT parameters_at AS sampled_at FROM rent_history_block"
|
||||
+ " WHERE network=? AND parameters_at IS NOT NULL ORDER BY block_height DESC LIMIT 1", network);
|
||||
long cutoff = System.currentTimeMillis() - maxSampleAgeSeconds * 1000L;
|
||||
require((healthy != null && RentalValues.time(healthy.get("sampled_at")).toEpochMilli() >= cutoff)
|
||||
|| (archived != null && RentalValues.time(archived.get("sampled_at")).toEpochMilli() >= cutoff),
|
||||
"全网资源参数采样尚未就绪或已停滞,暂不派单");
|
||||
if (Boolean.TRUE.equals(transaction.execute(status -> {
|
||||
RentalHistoryGuard.lock(store, network);
|
||||
return reuseAnchor(network, ownerHex, receiverHex, type);
|
||||
}))) {
|
||||
return;
|
||||
}
|
||||
Snapshot snapshot = capture(network, owner, receiver, type);
|
||||
require(snapshot.balance == 0, "确认状态存在旧委托,暂不派单");
|
||||
transaction.execute(status -> {
|
||||
saveParameters(network, snapshot);
|
||||
RentalHistoryGuard.lock(store, network);
|
||||
saveBlock(network, snapshot.block);
|
||||
Map<String, Object> existing = store.one(
|
||||
"SELECT * FROM rent_history_anchor WHERE network=? AND owner_address=?"
|
||||
+ " AND receiver_address=? AND resource_type=? AND block_height=?",
|
||||
@@ -216,6 +282,59 @@ public class RentalHistoryService {
|
||||
});
|
||||
}
|
||||
|
||||
/** 仅完整连续且仍在推进的事件档案可复用;不完整时退回确认节点读取真实关系。 */
|
||||
private boolean reuseAnchor(String network, String owner, String receiver, String type) {
|
||||
Map<String, Object> cursor = store.one("SELECT * FROM rent_history_cursor WHERE network=?"
|
||||
+ " AND last_success_at>=?", network, RentalValues.after(-15));
|
||||
if (cursor == null || cursor.get("scanned_height") == null) {
|
||||
return false;
|
||||
}
|
||||
long end = number(cursor, "scanned_height");
|
||||
Map<String, Object> anchor = store.one("SELECT * FROM rent_history_anchor WHERE network=?"
|
||||
+ " AND owner_address=? AND receiver_address=? AND resource_type=? AND block_height<=?"
|
||||
+ " ORDER BY block_height DESC LIMIT 1", network, owner, receiver, type, end);
|
||||
if (anchor == null || end - number(anchor, "block_height") > MAX_REPLAY_BLOCKS) {
|
||||
return false;
|
||||
}
|
||||
long expected = number(anchor, "block_height");
|
||||
String previous = text(anchor, "block_id");
|
||||
for (Map<String, Object> row : store.rows("SELECT * FROM rent_history_block WHERE network=?"
|
||||
+ " AND block_height>? AND block_height<=? ORDER BY block_height", network, expected, end)) {
|
||||
if (number(row, "block_height") != ++expected || number(row, "events_complete") != 1
|
||||
|| !previous.equals(text(row, "parent_id"))) {
|
||||
return false;
|
||||
}
|
||||
previous = text(row, "block_id");
|
||||
}
|
||||
if (expected != end || !previous.equals(text(cursor, "scanned_block_id"))) {
|
||||
return false;
|
||||
}
|
||||
long balance = number(anchor, "balance_sun");
|
||||
for (Map<String, Object> event : store.rows("SELECT operation,amount_sun FROM rent_history_event"
|
||||
+ " WHERE network=? AND owner_address=? AND receiver_address=? AND resource_type=?"
|
||||
+ " AND block_height>? AND block_height<=? ORDER BY block_height,tx_index",
|
||||
network, owner, receiver, type, number(anchor, "block_height"), end)) {
|
||||
balance = "DELEGATE".equals(text(event, "operation"))
|
||||
? Math.addExact(balance, number(event, "amount_sun"))
|
||||
: Math.subtractExact(balance, number(event, "amount_sun"));
|
||||
require(balance >= 0, "历史委托本金重放出现负数");
|
||||
}
|
||||
require(balance == 0, "确认状态存在旧委托,暂不派单");
|
||||
// 追加检查点限制未来重放长度,保留原始基线,不覆盖事实。
|
||||
try {
|
||||
store.execute("INSERT INTO rent_history_anchor (network,owner_address,receiver_address,"
|
||||
+ "resource_type,block_height,block_id,balance_sun,created_at) VALUES (?,?,?,?,?,?,0,?)",
|
||||
network, owner, receiver, type, end, previous, now());
|
||||
} catch (DuplicateKeyException ex) {
|
||||
Map<String, Object> existing = store.one("SELECT * FROM rent_history_anchor WHERE network=?"
|
||||
+ " AND owner_address=? AND receiver_address=? AND resource_type=? AND block_height=?",
|
||||
network, owner, receiver, type, end);
|
||||
require(existing != null && number(existing, "balance_sun") == 0
|
||||
&& previous.equals(text(existing, "block_id")), "历史基线发生冲突");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 每网络一个数据库租约;RPC结束后落库前再次校验租约,过期实例不得推进游标。
|
||||
* 首次从当前确认头开始,后续只沿父哈希顺序前进。停机后交易可补,参数不能回填。
|
||||
@@ -236,13 +355,8 @@ public class RentalHistoryService {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
Snapshot snapshot = capture(network, probeAddress, null, null);
|
||||
transaction.execute(status -> {
|
||||
lockLease(network, lease);
|
||||
saveParameters(network, snapshot);
|
||||
return null;
|
||||
});
|
||||
long confirmed = height(snapshot.block);
|
||||
// 区块/事件扫描不依赖资源参数是否采到、是否已经提升为确认事实。
|
||||
long confirmed = height(head(network));
|
||||
Map<String, Object> cursor = store.one(
|
||||
"SELECT * FROM rent_history_cursor WHERE network=?", network);
|
||||
Map<String, Object> firstAnchor = store.one("SELECT MIN(block_height) AS first_height"
|
||||
@@ -341,7 +455,7 @@ public class RentalHistoryService {
|
||||
store.execute("UPDATE rent_history_block SET energy_limit=?,energy_weight=?,"
|
||||
+ "bandwidth_limit=?,bandwidth_weight=?,parameters_at=?"
|
||||
+ " WHERE network=? AND block_height=?", totals[0], totals[1], totals[2],
|
||||
totals[3], now(), network, height(snapshot.block));
|
||||
totals[3], snapshot.sampledAt, network, height(snapshot.block));
|
||||
} else {
|
||||
require(number(row, "energy_limit") == totals[0]
|
||||
&& number(row, "energy_weight") == totals[1]
|
||||
@@ -397,6 +511,31 @@ public class RentalHistoryService {
|
||||
String owner, String receiver, String type) {
|
||||
network(network);
|
||||
resource(type);
|
||||
addressHex(owner);
|
||||
addressHex(receiver);
|
||||
require(txId != null && txId.matches("[0-9a-fA-F]{64}") && targetHeight >= 0,
|
||||
"证明交易或高度无效");
|
||||
Map<String, Object> result = transaction.execute(status -> {
|
||||
RentalHistoryGuard.lock(store, network);
|
||||
return buildProof(network, txId, targetHeight, owner, receiver, type);
|
||||
});
|
||||
if (result == null) {
|
||||
return null;
|
||||
}
|
||||
// 连续区块/事件在同一保护事务内读成完整证明;RPC在释放行锁之后执行。
|
||||
require(confirmations > 0 && height(head(network)) - targetHeight + 1 >= confirmations,
|
||||
"历史证明交易确认深度不足");
|
||||
JsonNode canonical = chain.call(network, "/walletsolidity/getblockbynum",
|
||||
map("num", targetHeight, "visible", false));
|
||||
require(height(canonical) == targetHeight && hash(canonical).equals(text(result, "block_id")),
|
||||
"历史证明区块与确认链不一致");
|
||||
return result;
|
||||
}
|
||||
|
||||
private Map<String, Object> buildProof(String network, String txId, long targetHeight,
|
||||
String owner, String receiver, String type) {
|
||||
network(network);
|
||||
resource(type);
|
||||
require(txId != null && txId.matches("[0-9a-fA-F]{64}") && targetHeight >= 0,
|
||||
"证明交易或高度无效");
|
||||
String ownerHex = addressHex(owner);
|
||||
@@ -405,6 +544,15 @@ public class RentalHistoryService {
|
||||
require(cursor != null && cursor.get("scanned_height") != null
|
||||
&& number(cursor, "scanned_height") >= targetHeight, "历史区块正在采集中,请稍后重试");
|
||||
Map<String, Object> target = block(network, targetHeight);
|
||||
if (target != null && target.get("parameters_at") == null) {
|
||||
require(parameterGraceSeconds >= 0 && parameterGraceSeconds <= 3600, "参数等待期必须为0到3600秒");
|
||||
// 确认与事件扫描线程独立:先到的事件必须留出归档窗口,不能立即判为履约失败。
|
||||
long age = System.currentTimeMillis() - RentalValues.time(target.get("created_at")).toEpochMilli();
|
||||
if (age < parameterGraceSeconds * 1000L) {
|
||||
throw new PendingConfirmationException();
|
||||
}
|
||||
// 超过有界窗口仍未提升,即使存在待确认记录也不无限挂起结算。
|
||||
}
|
||||
if (target == null || target.get("parameters_at") == null) {
|
||||
return null;
|
||||
}
|
||||
@@ -427,13 +575,6 @@ public class RentalHistoryService {
|
||||
previous = text(row, "block_id");
|
||||
}
|
||||
require(expected == targetHeight, "历史区块覆盖不足");
|
||||
require(confirmations > 0 && height(head(network)) - targetHeight + 1 >= confirmations,
|
||||
"历史证明交易确认深度不足");
|
||||
// 再向配置节点核对目标区块哈希;节点换链/误切网络时不使用旧库证据继续结算。
|
||||
JsonNode canonical = chain.call(network, "/walletsolidity/getblockbynum",
|
||||
map("num", targetHeight, "visible", false));
|
||||
require(height(canonical) == targetHeight && hash(canonical).equals(text(target, "block_id")),
|
||||
"历史证明区块与确认链不一致");
|
||||
List<Map<String, Object>> events = store.rows("SELECT * FROM rent_history_event WHERE network=?"
|
||||
+ " AND owner_address=? AND receiver_address=? AND resource_type=?"
|
||||
+ " AND block_height>? AND block_height<=? ORDER BY block_height,tx_index",
|
||||
@@ -464,6 +605,21 @@ public class RentalHistoryService {
|
||||
return proof;
|
||||
}
|
||||
|
||||
/** proof返回null时细分缺口;只读数据库,返回固定代码,不用当前链上参数补造历史证明。 */
|
||||
public String missingProofCode(String network, long height, String owner, String receiver, String type) {
|
||||
Map<String, Object> target = block(network, height);
|
||||
if (target == null) {
|
||||
return "BLOCK_NOT_ARCHIVED";
|
||||
}
|
||||
if (target.get("parameters_at") == null) {
|
||||
return "PARAMETERS_MISSING";
|
||||
}
|
||||
Map<String, Object> anchor = store.one("SELECT block_height FROM rent_history_anchor WHERE network=?"
|
||||
+ " AND owner_address=? AND receiver_address=? AND resource_type=? AND block_height<? LIMIT 1",
|
||||
network, addressHex(owner), addressHex(receiver), type, height);
|
||||
return anchor == null ? "BASELINE_MISSING" : "HISTORY_INCOMPLETE";
|
||||
}
|
||||
|
||||
/** 仅供运营查看,不返回RPC地址、认证头、私钥或响应原文。 */
|
||||
public List<Map<String, Object>> status() {
|
||||
return store.rows("SELECT c.network,c.scanned_height,c.scanned_block_id,c.last_success_at,"
|
||||
@@ -471,6 +627,8 @@ public class RentalHistoryService {
|
||||
+ " WHERE b.network=c.network AND b.parameters_at IS NOT NULL) AS last_parameter_height,"
|
||||
+ "(SELECT COUNT(*) FROM rent_history_block b WHERE b.network=c.network"
|
||||
+ " AND b.events_complete=1 AND b.parameters_at IS NULL) AS parameter_gap_count"
|
||||
+ ",(SELECT COUNT(*) FROM rent_history_sample s WHERE s.network=c.network) AS pending_sample_count"
|
||||
+ ",(SELECT MAX(s.block_height) FROM rent_history_sample s WHERE s.network=c.network) AS latest_sample_height"
|
||||
+ " FROM rent_history_cursor c ORDER BY c.network");
|
||||
}
|
||||
|
||||
@@ -478,12 +636,17 @@ public class RentalHistoryService {
|
||||
private final JsonNode block;
|
||||
private final long[] totals;
|
||||
private final long balance;
|
||||
private final long sampledAt = System.currentTimeMillis();
|
||||
private final Object sampledAt;
|
||||
|
||||
private Snapshot(JsonNode block, long[] totals, long balance) {
|
||||
this(block, totals, balance, now());
|
||||
}
|
||||
|
||||
private Snapshot(JsonNode block, long[] totals, long balance, Object sampledAt) {
|
||||
this.block = block;
|
||||
this.totals = totals;
|
||||
this.balance = balance;
|
||||
this.sampledAt = sampledAt;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,8 @@ import java.util.Map;
|
||||
@Service
|
||||
@lombok.extern.slf4j.Slf4j
|
||||
public class RentalOrders {
|
||||
@org.springframework.beans.factory.annotation.Autowired(required = false)
|
||||
private org.springframework.context.ApplicationEventPublisher deliveryEvents;
|
||||
@org.springframework.beans.factory.annotation.Autowired
|
||||
private RentalOnchain onchain;
|
||||
private final RentalStore store;
|
||||
@@ -183,6 +185,7 @@ public class RentalOrders {
|
||||
order.put("id", id);
|
||||
funds.hold(order);
|
||||
store.event("ORDER", id, "CREATE", user, "创建订单并冻结内部USDT");
|
||||
RentalDeliveryEvents.afterCommit(deliveryEvents, true, id);
|
||||
return store.get("order", id, false);
|
||||
}
|
||||
|
||||
@@ -237,6 +240,7 @@ public class RentalOrders {
|
||||
log.info("地址上链分账已锁定 orderId={} platformPercent={} platformFeeUsdt={} supplierNetUsdt={}",
|
||||
orderId, price.get("supplier_fee_percent"), price.get("supplier_fee_amount"), price.get("supplier_net_amount"));
|
||||
store.event("ORDER", orderId, "CREATE", user, "地址上链:冻结1TRX折价及固定服务费USDT");
|
||||
RentalDeliveryEvents.afterCommit(deliveryEvents, true, orderId);
|
||||
log.info("地址上链订单已冻结 orderId={} userId={} network={} transferSun={} principalUsdt={} serviceFeeUsdt={} totalUsdt={}",
|
||||
orderId, user, network, RentalOnchain.TRANSFER_SUN, price.get("principal_usdt"),
|
||||
price.get("service_fee_usdt"), total);
|
||||
|
||||
@@ -75,6 +75,15 @@ public class RentalQueries {
|
||||
// 资金账户列表补充所属用户名;左连接保留关联用户缺失的账户,归属过滤仍使用账户的user_id。
|
||||
String select = "r.*";
|
||||
if ("order".equals(type)) {
|
||||
// 只取归属校验后的订单关联诊断,不向页面暴露整份交易证据或节点配置。
|
||||
select += ", (SELECT e.reason FROM rent_event e WHERE e.object_type='ORDER'"
|
||||
+ " AND e.object_id=r.id AND e.action='DELIVERY_REVIEW' ORDER BY e.id DESC LIMIT 1) AS fulfillment_reason"
|
||||
+ ", (SELECT x.evidence FROM rent_transaction x JOIN rent_task t ON t.id=x.task_id"
|
||||
+ " WHERE t.order_id=r.id AND t.task_type='DELEGATE' AND x.status='CONFIRMED'"
|
||||
+ " ORDER BY x.id LIMIT 1) AS review_evidence"
|
||||
+ ", (SELECT x.confirmed_at FROM rent_transaction x JOIN rent_task t ON t.id=x.task_id"
|
||||
+ " WHERE t.order_id=r.id AND t.task_type='DELEGATE' AND x.status='CONFIRMED'"
|
||||
+ " ORDER BY x.id LIMIT 1) AS review_checked_at";
|
||||
select += ", (SELECT x.tx_id FROM rent_transaction x JOIN rent_task t ON t.id=x.task_id"
|
||||
+ " WHERE t.order_id=r.id AND t.task_type='TRANSFER_TRX' AND x.status='CONFIRMED'"
|
||||
+ " ORDER BY x.id LIMIT 1) AS transaction_id";
|
||||
@@ -93,6 +102,9 @@ public class RentalQueries {
|
||||
+ ") ORDER BY r.id DESC LIMIT 50 OFFSET ?",
|
||||
args.toArray());
|
||||
for (Map<String, Object> row : rows) {
|
||||
if ("order".equals(type)) {
|
||||
explainFulfillment(row);
|
||||
}
|
||||
row.remove("api_secret");
|
||||
row.remove("payment_api_key");
|
||||
row.remove("payment_public_key");
|
||||
@@ -117,4 +129,40 @@ public class RentalQueries {
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
/** 老订单尚无诊断事件时,仅用当时已归档的证据回溯;不能用当前时间判断历史租期。 */
|
||||
private void explainFulfillment(Map<String, Object> row) {
|
||||
Object evidence = row.remove("review_evidence");
|
||||
Object checked = row.remove("review_checked_at");
|
||||
String code = text(row, "error_code");
|
||||
if ("DELEGATION_CHANGED".equals(code)) {
|
||||
row.put("fulfillment_reason", "租期内委托关系与原确认本金不一致,可能被外部撤销或追加,需人工核对");
|
||||
return;
|
||||
}
|
||||
if (!"DELIVERY_EVIDENCE_REVIEW".equals(code)) {
|
||||
row.put("fulfillment_reason", "");
|
||||
return;
|
||||
}
|
||||
if (!text(row, "fulfillment_reason").isEmpty()) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
if (evidence != null) {
|
||||
com.fasterxml.jackson.databind.JsonNode proof = new com.fasterxml.jackson.databind.ObjectMapper()
|
||||
.readTree(evidence.toString());
|
||||
com.fasterxml.jackson.databind.JsonNode quantity = proof.path("verified_resource_quantity");
|
||||
Long verified = quantity.isIntegralNumber() && quantity.canConvertToLong() ? quantity.longValue() : null;
|
||||
String reason = RentalDeliveryDiagnostics.explain(proof.path("delivery_proven").asBoolean(false),
|
||||
verified, number(row, "target_resource_quantity"),
|
||||
row.get("service_expires_at") == null ? null : time(row.get("service_expires_at")),
|
||||
checked == null ? null : time(checked));
|
||||
row.put("fulfillment_reason", reason.isEmpty()
|
||||
? "历史核验未通过,现有归档未记录明确失败项,请核对原任务及订单事件" : reason);
|
||||
return;
|
||||
}
|
||||
} catch (Exception ignored) {
|
||||
// 不把数据库证据JSON或解析异常原文带到HTTP响应中。
|
||||
}
|
||||
row.put("fulfillment_reason", "历史履约核验未通过,未保存完整诊断,请核对原交易证据、资源数量及核验时间");
|
||||
}
|
||||
}
|
||||
@@ -291,90 +291,104 @@ public class RentalSocket extends TextWebSocketHandler {
|
||||
|
||||
/** 由有界后台调度调用,同一逻辑任务始终使用相同delivery_message_id和冻结intent。 */
|
||||
public void tick() {
|
||||
tick(0);
|
||||
}
|
||||
|
||||
public void push(long nodeId) {
|
||||
tick(nodeId);
|
||||
}
|
||||
|
||||
private void tick(long nodeId) {
|
||||
for (Connection c : connections.values()) {
|
||||
try {
|
||||
if (c.node == 0) {
|
||||
if (System.currentTimeMillis() - c.opened > 5000) {
|
||||
c.socket.close(CloseStatus.POLICY_VIOLATION);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (System.currentTimeMillis() - c.pong > 45000) {
|
||||
c.socket.close(CloseStatus.SESSION_NOT_RELIABLE);
|
||||
continue;
|
||||
}
|
||||
Map<String, Object> node = store.get("node", c.node, false);
|
||||
if (number(node, "session_epoch") != c.epoch
|
||||
|| "REVOKED".equals(text(node, "status"))) {
|
||||
c.socket.close(CloseStatus.POLICY_VIOLATION);
|
||||
continue;
|
||||
}
|
||||
// 快速扫描订单不等于快速发心跳;距离最近PONG至少15秒才主动探活。
|
||||
if (c.ping == null && System.currentTimeMillis() - c.pong >= 15000) {
|
||||
send(c, "PING", map());
|
||||
}
|
||||
if (!c.ready) {
|
||||
continue;
|
||||
}
|
||||
for (Map<String, Object> task :
|
||||
store.rows(
|
||||
"SELECT * FROM rent_task WHERE node_id=? AND status IN"
|
||||
+ " ('PENDING','ACCEPTED','UNKNOWN','BROADCASTED') AND"
|
||||
+ " (last_sent_at IS NULL OR last_sent_at<?) ORDER BY id LIMIT"
|
||||
+ " 10",
|
||||
c.node,
|
||||
after(-15))) {
|
||||
Map<String, Object> credential =
|
||||
store.get("credential", number(task, "credential_id"), false);
|
||||
if ("REVOKED".equals(text(credential, "status"))) {
|
||||
continue;
|
||||
}
|
||||
// PAUSED仍核对历史原任务,但不推送尚未接受的首次任务去执行。
|
||||
if (!"ACTIVE".equals(text(node, "status"))
|
||||
&& "PENDING".equals(text(task, "status"))) {
|
||||
continue;
|
||||
}
|
||||
send(
|
||||
c,
|
||||
"TASK_PUSH",
|
||||
map(
|
||||
"task_no",
|
||||
text(task, "task_no"),
|
||||
"delivery_message_id",
|
||||
text(task, "delivery_message_id"),
|
||||
"api_key",
|
||||
text(credential, "api_key"),
|
||||
"intent",
|
||||
json.writeValueAsString(
|
||||
new TreeMap<>(
|
||||
json.readValue(
|
||||
text(task, "intent"), Map.class))),
|
||||
"signature",
|
||||
text(task, "signature"),
|
||||
"timestamp",
|
||||
time(task.get("signed_at")).toEpochMilli(),
|
||||
"nonce",
|
||||
text(task, "nonce")));
|
||||
LOG.info("租赁任务已推送 taskId={} taskNo={} orderId={} nodeId={} deliveryCount={} taskAgeMs={}",
|
||||
task.get("id"), text(task, "task_no"), task.get("order_id"),
|
||||
c.node, number(task, "delivery_count") + 1,
|
||||
System.currentTimeMillis() - time(task.get("created_at")).toEpochMilli());
|
||||
store.execute(
|
||||
"UPDATE rent_task SET"
|
||||
+ " delivery_count=delivery_count+1,last_sent_at=?,delivery_session_epoch=?,version=version+1,updated_at=?"
|
||||
+ " WHERE id=?",
|
||||
now(),
|
||||
c.epoch,
|
||||
now(),
|
||||
task.get("id"));
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
LOG.warn("租赁任务推送或连接检查失败 nodeId={} diagnostic={}",
|
||||
c.node, RentalDiagnostics.describe(ex));
|
||||
if (nodeId != 0 && c.node != nodeId) {
|
||||
continue;
|
||||
}
|
||||
// 即时推送与补偿扫描串行处理同一连接的选择、发送及投递计数。
|
||||
synchronized (c) {
|
||||
try {
|
||||
c.socket.close(CloseStatus.SERVER_ERROR);
|
||||
} catch (Exception ignored) {
|
||||
/* 关闭后由epoch保护离线更新。 */
|
||||
if (c.node == 0) {
|
||||
if (System.currentTimeMillis() - c.opened > 5000) {
|
||||
c.socket.close(CloseStatus.POLICY_VIOLATION);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (System.currentTimeMillis() - c.pong > 45000) {
|
||||
c.socket.close(CloseStatus.SESSION_NOT_RELIABLE);
|
||||
continue;
|
||||
}
|
||||
Map<String, Object> node = store.get("node", c.node, false);
|
||||
if (number(node, "session_epoch") != c.epoch
|
||||
|| "REVOKED".equals(text(node, "status"))) {
|
||||
c.socket.close(CloseStatus.POLICY_VIOLATION);
|
||||
continue;
|
||||
}
|
||||
// 快速扫描订单不等于快速发心跳;距离最近PONG至少15秒才主动探活。
|
||||
if (c.ping == null && System.currentTimeMillis() - c.pong >= 15000) {
|
||||
send(c, "PING", map());
|
||||
}
|
||||
if (!c.ready) {
|
||||
continue;
|
||||
}
|
||||
for (Map<String, Object> task :
|
||||
store.rows(
|
||||
"SELECT * FROM rent_task WHERE node_id=? AND status IN"
|
||||
+ " ('PENDING','ACCEPTED','UNKNOWN','BROADCASTED') AND"
|
||||
+ " (last_sent_at IS NULL OR last_sent_at<?) ORDER BY id LIMIT"
|
||||
+ " 10",
|
||||
c.node,
|
||||
after(-15))) {
|
||||
Map<String, Object> credential =
|
||||
store.get("credential", number(task, "credential_id"), false);
|
||||
if ("REVOKED".equals(text(credential, "status"))) {
|
||||
continue;
|
||||
}
|
||||
// PAUSED仍核对历史原任务,但不推送尚未接受的首次任务去执行。
|
||||
if (!"ACTIVE".equals(text(node, "status"))
|
||||
&& "PENDING".equals(text(task, "status"))) {
|
||||
continue;
|
||||
}
|
||||
send(
|
||||
c,
|
||||
"TASK_PUSH",
|
||||
map(
|
||||
"task_no",
|
||||
text(task, "task_no"),
|
||||
"delivery_message_id",
|
||||
text(task, "delivery_message_id"),
|
||||
"api_key",
|
||||
text(credential, "api_key"),
|
||||
"intent",
|
||||
json.writeValueAsString(
|
||||
new TreeMap<>(
|
||||
json.readValue(
|
||||
text(task, "intent"), Map.class))),
|
||||
"signature",
|
||||
text(task, "signature"),
|
||||
"timestamp",
|
||||
time(task.get("signed_at")).toEpochMilli(),
|
||||
"nonce",
|
||||
text(task, "nonce")));
|
||||
LOG.info("租赁任务已推送 taskId={} taskNo={} orderId={} nodeId={} deliveryCount={} taskAgeMs={}",
|
||||
task.get("id"), text(task, "task_no"), task.get("order_id"),
|
||||
c.node, number(task, "delivery_count") + 1,
|
||||
System.currentTimeMillis() - time(task.get("created_at")).toEpochMilli());
|
||||
store.execute(
|
||||
"UPDATE rent_task SET"
|
||||
+ " delivery_count=delivery_count+1,last_sent_at=?,delivery_session_epoch=?,version=version+1,updated_at=?"
|
||||
+ " WHERE id=?",
|
||||
now(),
|
||||
c.epoch,
|
||||
now(),
|
||||
task.get("id"));
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
LOG.warn("租赁任务推送或连接检查失败 nodeId={} diagnostic={}",
|
||||
c.node, RentalDiagnostics.describe(ex));
|
||||
try {
|
||||
c.socket.close(CloseStatus.SERVER_ERROR);
|
||||
} catch (Exception ignored) {
|
||||
/* 关闭后由epoch保护离线更新。 */
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,6 +13,8 @@ import java.util.function.Supplier;
|
||||
@Service
|
||||
@lombok.extern.slf4j.Slf4j
|
||||
public class RentalTasks {
|
||||
@org.springframework.beans.factory.annotation.Autowired(required = false)
|
||||
private org.springframework.context.ApplicationEventPublisher deliveryEvents;
|
||||
private final RentalStore store;
|
||||
private final RentalChain chain;
|
||||
private final RentalIdentity identity;
|
||||
@@ -423,6 +425,7 @@ public class RentalTasks {
|
||||
java.time.LocalDateTime.ofInstant(
|
||||
Instant.ofEpochMilli(signed), java.time.ZoneOffset.UTC),
|
||||
taskNo);
|
||||
RentalDeliveryEvents.afterCommit(deliveryEvents, false, nodeId);
|
||||
}
|
||||
|
||||
public void reclaim(long orderId) {
|
||||
@@ -634,6 +637,7 @@ public class RentalTasks {
|
||||
Map<String, Object> fields = new LinkedHashMap<>(proof);
|
||||
fields.remove("delivery_proven");
|
||||
fields.remove("history_proof");
|
||||
fields.remove("delivery_evidence_gap");
|
||||
fields.put("evidence", orders.encode(proof));
|
||||
fields.put("confirmed_at", now());
|
||||
store.update("transaction", number(record, "id"), fields);
|
||||
@@ -682,11 +686,18 @@ public class RentalTasks {
|
||||
if (delegate) {
|
||||
Instant start = time(proof.get("block_time")),
|
||||
expires = start.plusSeconds(number(order, "duration_seconds"));
|
||||
boolean delivered =
|
||||
Boolean.TRUE.equals(proof.get("delivery_proven"))
|
||||
&& number(proof, "verified_resource_quantity")
|
||||
>= number(order, "target_resource_quantity")
|
||||
&& expires.isAfter(Instant.now());
|
||||
Instant checkedAt = Instant.now();
|
||||
// 在同一次判断中固定核验时间;记录所有未满足项,避免日志与状态跨租期边界不一致。
|
||||
String reviewReason = RentalDeliveryDiagnostics.explain(
|
||||
Boolean.TRUE.equals(proof.get("delivery_proven")),
|
||||
proof.get("verified_resource_quantity") == null ? null
|
||||
: number(proof, "verified_resource_quantity"),
|
||||
number(order, "target_resource_quantity"), expires, checkedAt);
|
||||
String gap = RentalDeliveryDiagnostics.evidenceGap(text(proof, "delivery_evidence_gap"));
|
||||
if (!gap.isEmpty() && !Boolean.TRUE.equals(proof.get("delivery_proven"))) {
|
||||
reviewReason += ";" + gap;
|
||||
}
|
||||
boolean delivered = reviewReason.isEmpty();
|
||||
if (delivered) {
|
||||
funds.charge(order);
|
||||
}
|
||||
@@ -710,6 +721,14 @@ public class RentalTasks {
|
||||
delivered ? null : "DELIVERY_EVIDENCE_REVIEW"));
|
||||
if (delivered) {
|
||||
orders.webhook(order, "SUCCESS", "ORDER:" + orderId + ":SUCCESS");
|
||||
} else {
|
||||
// 与人工核对状态同事务保存,查询端无需推测或重新查询链上即可展示当时的原因。
|
||||
store.event("ORDER", orderId, "DELIVERY_REVIEW", 0, reviewReason);
|
||||
log.warn("租赁履约未通过 orderId={} taskId={} txId={} historyProven={}"
|
||||
+ " verifiedQuantity={} targetQuantity={} reason={}",
|
||||
orderId, taskId, record.get("tx_id"), proof.get("delivery_proven"),
|
||||
proof.get("verified_resource_quantity"), order.get("target_resource_quantity"),
|
||||
reviewReason);
|
||||
}
|
||||
} else {
|
||||
store.update(
|
||||
|
||||
@@ -26,6 +26,8 @@ public class RentalWorkers {
|
||||
private long walletCursor;
|
||||
private long monitoringCursor;
|
||||
private long dispatchCursor;
|
||||
@org.springframework.beans.factory.annotation.Autowired(required = false)
|
||||
private RentalDeliveryDispatcher deliveryDispatcher;
|
||||
|
||||
@org.springframework.beans.factory.annotation.Value("${rental.delivery.dispatch-interval-ms:3000}")
|
||||
private long dispatchIntervalMs = 3000;
|
||||
@@ -103,7 +105,11 @@ public class RentalWorkers {
|
||||
for (Map<String, Object> row : waiting) {
|
||||
dispatchCursor = number(row, "id");
|
||||
try {
|
||||
tasks.dispatch(dispatchCursor);
|
||||
if (deliveryDispatcher == null) {
|
||||
tasks.dispatch(dispatchCursor);
|
||||
} else {
|
||||
deliveryDispatcher.dispatch(dispatchCursor);
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
LOG.warn("租赁订单调度待重试 orderId={} diagnostic={}", dispatchCursor, RentalDiagnostics.describe(ex));
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user