Добавить учёт публикации блоков и обновить загрузку UI

This commit is contained in:
AidarKC
2026-12-01 20:39:18 +03:00
parent 3fa1e681d9
commit a320c12bdd
30 changed files with 714 additions and 60 deletions
@@ -14,8 +14,8 @@ import java.util.concurrent.atomic.AtomicBoolean;
/**
* Publisher с двумя путями доставки:
* 1) Turbo — немедленная неблокирующая попытка для только что принятого блока;
* 2) плановый fixed-delay цикл — страховочная добивка только зависших pending-записей.
* Серверный Turbo publisher обслуживает candidate-блоки ротации ключей.
* Пользовательские CORE/CONTENT в режиме client_only загружает браузер.
*/
public final class ArweaveBlockPublisherScheduler {
private static final Logger log = LoggerFactory.getLogger(ArweaveBlockPublisherScheduler.class);
@@ -12,7 +12,7 @@ import java.util.List;
import java.util.function.Consumer;
import java.util.function.Predicate;
/** Publishes locally-created signed user DataItems through the configured transport. */
/** Серверный publisher candidate-блоков ротации; пользовательские пары ведёт браузер. */
public final class ArweaveBlockPublisherService {
private static final Logger log = LoggerFactory.getLogger(ArweaveBlockPublisherService.class);
@@ -46,16 +46,7 @@ public final class ArweaveBlockPublisherService {
result.dataItemId(), entry.getCandidateBlockchainName(), entry.getBlockNumber());
return true;
}
BlockEntry entry = blocksDAO.getPendingArweaveByDataItemId(id);
if (entry == null) return true;
byte[] raw = entry.getBlockBytes();
if (raw == null || raw.length == 0) return false;
TurboDataItemUploader.UploadResult result = ArchiveBlockPair.publish(raw, id, turboUploader::upload);
blocksDAO.markArweavePublished(List.of(id), System.currentTimeMillis());
log.debug("Turbo immediately published SHiNE DataItem {} chain={} block={}",
result.dataItemId(), entry.getBchName(), entry.getBlockNumber());
return true;
return false;
}
public int runCycle() throws Exception {
@@ -86,17 +77,7 @@ public final class ArweaveBlockPublisherService {
};
}
int remaining = Math.max(0, maxItems - attempted);
if (remaining == 0) return published;
List<BlockEntry> candidates = blocksDAO.listPendingArweave(remaining);
candidates = candidates.stream().filter(e -> eligible.test(e.getDataItemId())).toList();
if (candidates.isEmpty()) return published;
published += switch (cfg.publishMode()) {
case TURBO -> publishTurbo(candidates, onPublished);
case ARWEAVE -> throw new IllegalStateException("CORE/CONTENT requires Turbo");
case NONE -> 0;
};
// Пользовательские блоки в режиме client_only публикует браузер.
return published;
}
@@ -15,6 +15,7 @@ import utils.config.AppConfig;
import shine.db.dao.ArweaveBlockImportDAO;
import shine.db.dao.BlockchainStateDAO;
import shine.db.dao.BlocksDAO;
import shine.db.entities.BlockEntry;
import shine.db.dao.BlockchainForkSegmentsDAO;
import shine.db.dao.CanonicalChainResolver;
import shine.db.dao.ChannelReadStateDAO;
@@ -115,7 +116,26 @@ public final class ArweaveBlockSyncService {
log.warn("Ignoring malformed Arweave DataItem id {}: {}", dataItemId, e.getMessage());
continue;
}
if (blocksDAO.existsByDataItemId(id32) || importDAO.exists(id32)) {
if (blocksDAO.existsByDataItemId(id32)) {
// Локально принятый блок должен получить подтверждение Arweave без повторного применения.
try {
DownloadedEvent published = downloadEvent(dataItemId);
BlockEntry local = blocksDAO.getByDataItemId(id32);
if (local != null && Arrays.equals(local.getBlockBytes(), published.rawDataItem())) {
shine.db.dao.BlockPublicationsDAO.getInstance().arweaveConfirmed(
local.getLogin(), local.getForkNumber(), local.getBlockNumber(), System.currentTimeMillis());
} else {
log.warn("Arweave DataItem {} differs from locally accepted bytes", dataItemId);
}
} catch (Exception e) {
lowestRetryHeight = Math.min(lowestRetryHeight, height);
unresolvedDownloads.put(dataItemId, new PendingDownload(dataItemId, id32, height));
continue;
}
unresolvedDownloads.remove(dataItemId);
continue;
}
if (importDAO.exists(id32)) {
unresolvedDownloads.remove(dataItemId);
continue;
}
@@ -163,7 +183,19 @@ public final class ArweaveBlockSyncService {
if (attempted >= cfg.syncPageSize()) break;
attempted++;
if (blocksDAO.existsByDataItemId(pending.id32()) || importDAO.exists(pending.id32())) {
if (blocksDAO.existsByDataItemId(pending.id32())) {
try {
DownloadedEvent published = downloadEvent(pending.dataItemId());
BlockEntry local = blocksDAO.getByDataItemId(pending.id32());
if (local != null && Arrays.equals(local.getBlockBytes(), published.rawDataItem())) {
shine.db.dao.BlockPublicationsDAO.getInstance().arweaveConfirmed(
local.getLogin(), local.getForkNumber(), local.getBlockNumber(), System.currentTimeMillis());
unresolvedDownloads.remove(pending.dataItemId());
}
} catch (Exception e) { log.debug("Arweave pair {} still unavailable: {}", pending.dataItemId(), e.getMessage()); }
continue;
}
if (importDAO.exists(pending.id32())) {
unresolvedDownloads.remove(pending.dataItemId());
continue;
}
@@ -280,6 +312,14 @@ public final class ArweaveBlockSyncService {
continue;
}
String reason = result.reasonCode();
if ("bad_block_number".equals(reason)) {
BlockEntry existing = blocksDAO.getByNumber(physicalUser.getBlockchainName(), parsedBlock.blockNumber);
if (existing != null && !Arrays.equals(existing.getBlockBytes(), q.rawDataItem())) {
importDAO.reject(q.dataItemId(), "conflict_same_number_different_core", System.currentTimeMillis());
progress = true;
continue;
}
}
if ("bad_block_number".equals(reason) || "bad_prev_hash".equals(reason)
|| "prev_line_block_not_found".equals(reason) || "channel_not_found".equals(reason)
|| "chain_resync_in_progress".equals(reason)) {
@@ -0,0 +1,70 @@
package server.archive;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import shine.db.dao.BlockPublicationsDAO;
import shine.db.dao.BlocksDAO;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/** Проверяет Turbo без загрузки или переподписи пользовательских блоков. */
public final class BlockPublicationVerifierScheduler {
private static final Logger log = LoggerFactory.getLogger(BlockPublicationVerifierScheduler.class);
private static final ObjectMapper json = new ObjectMapper();
private static final HttpClient http = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();
private static ScheduledExecutorService executor;
private BlockPublicationVerifierScheduler() {}
public static synchronized void startOrLog() {
if (executor != null) return;
String base = ArweaveBlocksConfig.load().syncTurboApiBase().replaceAll("/+$", "");
executor = Executors.newSingleThreadScheduledExecutor(r -> {
Thread t = new Thread(r, "shine-block-publication-verifier"); t.setDaemon(true); return t;
});
executor.scheduleWithFixedDelay(() -> {
try { verify(base); }
catch (Exception e) { log.warn("Cannot verify pending Turbo publications", e); }
}, 10, 30, TimeUnit.SECONDS);
}
private static void verify(String base) throws Exception {
BlockPublicationsDAO dao = BlockPublicationsDAO.getInstance();
long now = System.currentTimeMillis();
List<BlockPublicationsDAO.Row> rows = dao.due(100, now);
for (BlockPublicationsDAO.Row row : rows) {
try {
boolean content = row.contentConfirmed() || available(base, row.contentId());
boolean core = row.coreConfirmed() || available(base, row.coreId());
if (content || core) dao.verified(row, content, core, now);
else dao.attempted(row, "Turbo ещё не видит подписанную пару", now);
if (content && core) BlocksDAO.getInstance().markArweavePublished(
List.of(java.util.Base64.getUrlDecoder().decode(row.coreId())), now);
} catch (Exception e) { dao.attempted(row, e.getMessage(), now); }
}
}
private static boolean available(String base, String id) throws Exception {
HttpRequest req = HttpRequest.newBuilder(URI.create(base + "/tx/" + id + "/status"))
.timeout(Duration.ofSeconds(15)).GET().build();
HttpResponse<String> res = http.send(req, HttpResponse.BodyHandlers.ofString());
if (res.statusCode() == 404) return false;
if (res.statusCode() != 200) throw new IllegalStateException("Turbo status HTTP " + res.statusCode());
JsonNode node = json.readTree(res.body());
String status = node.path("status").asText("");
return status.equals("PENDING") || status.equals("CONFIRMED") || status.equals("BUNDLED") || status.equals("FINALIZED");
}
public static synchronized void close() {
if (executor != null) executor.shutdownNow();
executor = null;
}
}