新增融合输入接入并调整 UDP 网关转发

This commit is contained in:
2026-12-01 08:51:28 +08:00
parent bf84214534
commit 088fc96888
27 changed files with 1763 additions and 58 deletions
@@ -21,6 +21,7 @@ public class Settings {
public final String role, cluster, token, id, bootId, name, coordinator, advertisedHost, bindHost;
public final Path directory;
public final int capacity, gatewayPort, targetPort;
public final String forwardTargetHost;
// HTTP 就绪事件发布实际端口,随机端口部署不能继续上报配置中的 0。
public volatile int port;
private volatile boolean serverReady;
@@ -68,6 +69,7 @@ public class Settings {
// HTTP 管理、网关 UDP 接入和 PXHJ 接收端口各自配置,不能混为同一入口。
port = env.getProperty("server.port", Integer.class, 18100);
gatewayPort = env.getProperty("fusion.gateway-port", Integer.class, 19002);
forwardTargetHost = env.getProperty("fusion.forward-target-host", "").trim();
targetPort = env.getProperty("fusion.forward-target-port", Integer.class, 19001);
// 授权有效期交给业务服务用单调时钟计时;这里仅校验部署值范围。
@@ -82,10 +82,13 @@ public class ServiceSecurity extends OncePerRequestFilter {
return;
}
// 有界读取保护内存;签名绑定方法、路径、查询参数和实际收到的全部正文。
byte[] body = req.getInputStream().readNBytes(2 * 1024 * 1024 + 1);
// Only the authenticated image relay accepts a 2 MiB JPEG encoded inside HTTP JSON.
int limit = java.util.Set.of("/control/input", "/control/input-image", "/node/input").contains(path)
? 3 * 1024 * 1024 : 2 * 1024 * 1024;
byte[] body = req.getInputStream().readNBytes(limit + 1);
String requestPath = path + (req.getQueryString() == null ? "" : "?" + req.getQueryString());
String expected = Signatures.request(settings.token, req.getMethod(), requestPath, time, nonce, body);
if (body.length > 2 * 1024 * 1024 || !Signatures.equal(expected, supplied)
if (body.length > limit || !Signatures.equal(expected, supplied)
|| nonces.putIfAbsent(nonce, timestamp) != null) {
reject(res, "Invalid service signature");
return;
@@ -35,6 +35,40 @@ public class CoordinatorService {
private final ImageSourceRegistry imageSources = new ImageSourceRegistry();
// 保存失败后停止继续派发,避免内存中的新授权与磁盘中的旧状态发生分歧。
private boolean storageHealthy = true;
private final Map<String,String> inputOwners = new HashMap<>();
private final Map<String,Long> inputTouched = new HashMap<>();
/** Keep all inputs of one equipment on one live execution node, including data-only equipment. */
public synchronized ObjectNode inputTarget(String trialId, String equipmentId) {
String key = equipmentId;
List<ObjectNode> eligible = rows(state,"nodes").stream().filter(n -> live(n)
&& n.path("enabled").asBoolean() && n.path("capacity").asInt() > 0
&& n.path("inputForwarding").asBoolean()).toList();
inputOwners.entrySet().removeIf(e -> eligible.stream().noneMatch(n -> n.path("nodeId").asText().equals(e.getValue())));
inputOwners.keySet().removeIf(owner -> now()-inputTouched.getOrDefault(owner,0L)>60_000);
inputTouched.keySet().retainAll(inputOwners.keySet());
// Follow an existing equipment task when possible; source-connection IDs are never equipment IDs.
for (ObjectNode task : rows(state,"tasks")) {
if (!trialId.equals(task.path("trialId").asText()) || !equipmentId.equals(task.path("equipmentId").asText())) continue;
ObjectNode active = assignment(task,"active");
if (active != null && valid(active) && eligible.stream().anyMatch(n -> n.path("nodeId").asText().equals(active.path("nodeId").asText()))) {
inputOwners.put(key,active.path("nodeId").asText()); break;
}
}
if (!inputOwners.containsKey(key)) {
if (inputOwners.size() >= 2048) throw new IllegalStateException("Too many input equipment routes");
ObjectNode target = eligible.stream().filter(n -> inputOwners.values().stream()
.filter(n.path("nodeId").asText()::equals).count() < n.path("capacity").asInt())
.min(Comparator.comparingDouble((ObjectNode n) -> (double)inputOwners.values().stream()
.filter(n.path("nodeId").asText()::equals).count()/n.path("capacity").asInt())
.thenComparing(n -> n.path("nodeId").asText()))
.orElseThrow(() -> new IllegalStateException("No input execution node has capacity"));
inputOwners.put(key,target.path("nodeId").asText());
}
ObjectNode target = node(inputOwners.get(key));
inputTouched.put(key,now());
return object().put("nodeId",target.path("nodeId").asText()).put("baseUrl",target.path("baseUrl").asText());
}
@org.springframework.beans.factory.annotation.Autowired
public CoordinatorService(Settings settings, ObjectMapper mapper) throws Exception {
@@ -113,6 +147,7 @@ public class CoordinatorService {
String imageHost=input.path("imageHost").asText("");
require(imagePort==0||(imagePort>0&&imagePort<=65535&&ImageSourceRegistry.ipv4(imageHost)),"Invalid node image input");
n.put("imageInputPort",imagePort).put("imageHost",imageHost);
n.put("inputForwarding",input.path("inputForwarding").asBoolean(false));
map("nodes").set(id,n);leaseRefresh.put(id,leaseClock.getAsLong());schedule();persist();
return object().put("nodeId",id).put("sessionId",n.path("sessionId").asText()).put("epoch",state.path("epoch").asLong()).put("leaseMs",leaseMs);
}
@@ -183,6 +218,9 @@ public class CoordinatorService {
String revision=input.path("configurationVersion").asText("0");
var c=map("contexts").has(trialId)?(ObjectNode)map("contexts").get(trialId):object();
boolean enabled=input.path("enabled").asBoolean(true);
if(!enabled||phase.equals("SAVED")){
// Equipment can belong to another prepared trial; idle input routes expire independently.
}
c.put("trialId",trialId).put("roundId",roundId).put("name",name).put("roundStatus",phase).put("configurationVersion",revision)
.put("enabled",enabled).put("confirmed",true).put("confirmedAt",now());
c.set("channels",input.path("channels").deepCopy());c.set("bindings",input.path("bindings").deepCopy());map("contexts").set(trialId,c);
@@ -18,6 +18,7 @@ import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.SocketTimeoutException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
@@ -47,9 +48,8 @@ public class GatewayService {
// 字节限额与报文数限额配合,大报文不能绕过队列长度限制。
private static final long MAX_BUFFERED_BYTES = 16L * 1024 * 1024;
// 收包时保留来源及匹配的路由,发送线程无需重复猜测采集器身份。
// 字节数组专属这一报文,与接收循环复用的缓冲区不共享。
private record Packet(byte[] bytes, InetSocketAddress source, Relay relay) {}
private record Routes(List<Relay> registered, InetSocketAddress target) {}
private record Packet(byte[] bytes, InetSocketAddress source, InetSocketAddress target, Relay relay) {}
private final Settings settings;
private final CoordinatorLocator locator;
@@ -57,16 +57,18 @@ public class GatewayService {
// 路由持久化经 DAO 完成;业务服务不包含表结构或 SQL 语句。
private final StateStore store;
private final DatagramSocket ingress;
private final InetSocketAddress configuredTarget;
private final UdpForwardSessions sessions;
// 上行接收与发送解耦,避免目标发送迟缓阻塞所有采集器的接收。
private final ArrayBlockingQueue<Packet> queue = new ArrayBlockingQueue<>(2048);
// 计数描述本次进程运行,重启恢复的是路由,而不是历史报文统计。
// 原子计数可同时由上行线程和各采集器回传线程更新。
// 未登记、队列丢弃和发送错误分别计数,PXHJ 可区分数据缺失原因。
// 缺少转发目标、队列丢弃和发送错误分别计数。
private final AtomicLong received = new AtomicLong(), forwarded = new AtomicLong();
private final AtomicLong unknown = new AtomicLong(), overflow = new AtomicLong();
private final AtomicLong noTarget = new AtomicLong(), overflow = new AtomicLong();
private final AtomicLong errors = new AtomicLong(), buffered = new AtomicLong();
// 发布只读列表快照,收包线程遍历期间不受路由增删影响。
private volatile List<Relay> relays = List.of();
private volatile Routes active;
private volatile boolean closed;
private volatile long routeVersion = -1;
private volatile JsonNode appliedRoutes = array();
@@ -89,11 +91,29 @@ public class GatewayService {
ingress = new DatagramSocket(null);
// 增大内核收包缓冲区以应对短时突发,实际可用大小仍由操作系统决定。
// 内核缓冲区和业务队列是两层容量,业务队列满时会显式累计丢弃数。
ingress.setReceiveBufferSize(4 * 1024 * 1024);
ingress.bind(new InetSocketAddress(settings.gatewayPort));
ObjectNode saved = store.load();
if (saved.path("routes").isArray()) {
apply(saved.path("routes"), saved.path("routeVersion").asLong(), false);
try {
ingress.setReceiveBufferSize(4 * 1024 * 1024);
ingress.bind(new InetSocketAddress(settings.gatewayPort));
sessions = new UdpForwardSessions(ingress, errors);
} catch (Exception failure) {
ingress.close();
store.close();
throw failure;
}
try {
configuredTarget = settings.forwardTargetHost.isEmpty() ? null :
platformAddress(settings.forwardTargetHost, settings.targetPort);
active = new Routes(List.of(), configuredTarget);
sessions.setTarget(configuredTarget);
ObjectNode saved = store.load();
if (saved.path("routes").isArray()) {
apply(saved.path("routes"), saved.path("routeVersion").asLong(), false);
}
} catch (Exception failure) {
ingress.close();
sessions.close();
store.close();
throw failure;
}
daemon("xtrh-udp-receive", this::receive);
daemon("xtrh-udp-forward", this::forward);
@@ -121,7 +141,7 @@ public class GatewayService {
}
/**
* 仅接收唯一匹配的登记来源;未登记和歧义来源统一丢弃并计数。
* 接收任意来源的报文,将每个报文发往同一个平台地址一次。
* 接收缓冲区循环复用,入队前复制有效字节,防止下一报文覆盖旧内容。
* 队列同时限制报文数和累计字节数,避免高频或大报文耗尽内存。
*/
@@ -133,15 +153,16 @@ public class GatewayService {
ingress.receive(packet);
received.incrementAndGet();
InetSocketAddress source = (InetSocketAddress) packet.getSocketAddress();
Relay match = matchSource(source);
if (match == null) {
unknown.incrementAndGet();
Routes routes = active;
if (routes.target == null) {
noTarget.incrementAndGet();
continue;
}
Relay match = registeredRelay(routes.registered, source);
// 不改原始密文、报文长度和采样时间,PXHJ 继续按既有协议解析。
byte[] bytes = Arrays.copyOf(buffer, packet.getLength());
long reserved = buffered.addAndGet(bytes.length);
if (reserved > MAX_BUFFERED_BYTES || !queue.offer(new Packet(bytes, source, match))) {
if (reserved > MAX_BUFFERED_BYTES || !queue.offer(new Packet(bytes, source, routes.target, match))) {
buffered.addAndGet(-bytes.length);
overflow.incrementAndGet();
}
@@ -153,10 +174,8 @@ public class GatewayService {
}
}
// 同一来源若匹配多条路由就拒绝转发,防止把数据归入错误采集器。
private Relay matchSource(InetSocketAddress source) {
// 匹配依据来源 IP 与登记端口,内容中的模块编号仍交给 PXHJ 校验。
// 动态源端口由各 Relay 的 sourcePort=0 明确允许,不放宽来源 IP。
// 登记信息仅用于选择原有固定出口。其余来源使用独立会话。
private Relay registeredRelay(List<Relay> relays, InetSocketAddress source) {
Relay match = null;
for (Relay relay : relays) {
if (relay.matches(source)) {
@@ -184,7 +203,11 @@ public class GatewayService {
continue;
}
try {
packet.relay.send(packet.bytes, packet.source);
if (packet.relay == null) {
sessions.send(packet.bytes, packet.source, packet.target);
} else {
packet.relay.send(packet.bytes, packet.source, packet.target);
}
forwarded.incrementAndGet();
} catch (Exception failure) {
errors.incrementAndGet();
@@ -198,14 +221,29 @@ public class GatewayService {
}
}
private InetSocketAddress platformAddress(String host, int port) throws Exception {
require(port > 0 && port <= 65535, "Invalid platform UDP port");
InetAddress address = InetAddress.getByName(host);
if (port == ingress.getLocalPort()) {
require(!address.isAnyLocalAddress() && !address.isLoopbackAddress()
&& NetworkInterface.getByInetAddress(address) == null, "Platform UDP target is the gateway input");
}
return new InetSocketAddress(address, port);
}
/**
* 路由变更先校验地址并准备新 socket,再发布新的列表快照。
* 相同采集器及相同转发端口复用 socket,保留回传线程与端口身份。
* 准备失败时关闭本次新开的端口,不关闭仍在服务的旧路由。
*/
private synchronized void apply(JsonNode routes, long version, boolean save) throws Exception {
InetSocketAddress target = configuredTarget;
if (target == null && !routes.isEmpty()) {
JsonNode first = routes.get(0);
target = platformAddress(required(first, "targetHost"), first.path("targetPort").asInt());
}
Map<String, Relay> existing = new HashMap<>();
for (Relay relay : relays) {
for (Relay relay : active.registered) {
existing.put(relay.id, relay);
}
List<Relay> next = new ArrayList<>(), opened = new ArrayList<>();
@@ -218,13 +256,12 @@ public class GatewayService {
String id = required(route, "endpointId");
ObjectNode config = (ObjectNode) route.deepCopy();
InetAddress.getByName(required(route, "sourceHost"));
InetAddress.getByName(required(route, "targetHost"));
Relay old = existing.get(id);
if (old != null && old.route.path("relayPort").asInt() == route.path("relayPort").asInt()) {
next.add(old);
updates.put(old, config);
} else {
Relay fresh = new Relay(config);
Relay fresh = new Relay(config, target);
opened.add(fresh);
next.add(fresh);
}
@@ -236,11 +273,12 @@ public class GatewayService {
store.save(snapshot);
}
for (Map.Entry<Relay, ObjectNode> entry : updates.entrySet()) {
entry.getKey().update(entry.getValue());
entry.getKey().update(entry.getValue(), target);
}
List<Relay> previous = relays;
List<Relay> previous = active.registered;
// 旧列表不再修改;新列表发布后才关闭已撤销的旧 socket。
relays = List.copyOf(next);
sessions.setTarget(target);
active = new Routes(List.copyOf(next), target);
routeVersion = version;
appliedRoutes = routes.deepCopy();
routeState = "APPLIED";
@@ -292,13 +330,18 @@ public class GatewayService {
// 控制层读取统计快照,不接触 socket、队列或可变路由对象。
public ObjectNode status() {
Routes routes = active;
ObjectNode result = object().put("connection", connection).put("routeState", routeState)
.put("routeVersion", routeVersion).put("inputPort", ingress.getLocalPort())
.put("received", received.get()).put("forwarded", forwarded.get())
.put("unknownSource", unknown.get()).put("queueDropped", overflow.get())
.put("unknownSource", noTarget.get()).put("queueDropped", overflow.get())
.put("errors", errors.get()).put("bufferedBytes", buffered.get());
if (routes.target != null) {
result.put("forwardTargetHost", routes.target.getAddress().getHostAddress())
.put("forwardTargetPort", routes.target.getPort());
}
ArrayNode entries = result.putArray("routeStatus");
for (Relay relay : relays) {
for (Relay relay : routes.registered) {
entries.add(relay.status());
}
return result;
@@ -306,10 +349,11 @@ public class GatewayService {
// 先关闭 socket 唤醒阻塞接收,再关闭持久化连接。
@PreDestroy
public void close() throws Exception {
public synchronized void close() throws Exception {
closed = true;
ingress.close();
for (Relay relay : relays) {
sessions.close();
for (Relay relay : active.registered) {
relay.close();
}
store.close();
@@ -331,14 +375,14 @@ public class GatewayService {
private volatile InetSocketAddress lastNegotiationSource;
private final AtomicLong sent = new AtomicLong(), replies = new AtomicLong();
Relay(ObjectNode config) throws Exception {
Relay(ObjectNode config, InetSocketAddress target) throws Exception {
id = config.path("endpointId").asText();
socket = new DatagramSocket(null);
try {
// 专属转发端口是 PXHJ 识别原采集器的映射,不随视频任务迁移。
socket.bind(new InetSocketAddress(config.path("relayPort").asInt()));
socket.setSoTimeout(1000);
update(config);
update(config, target);
daemon("xtrh-relay-" + id, this::reply);
} catch (Exception failure) {
socket.close();
@@ -351,16 +395,18 @@ public class GatewayService {
* 来源配置变化时清空最近设备地址,避免回执发到旧采集器。
* 更新和发送共用对象锁,避免发送期间切换目标 socket 连接。
*/
synchronized void update(ObjectNode config) throws Exception {
synchronized void update(ObjectNode config, InetSocketAddress target) throws Exception {
sourceAddress = InetAddress.getByName(config.path("sourceHost").asText());
if (route == null || !route.path("sourceHost").equals(config.path("sourceHost"))
|| !route.path("sourcePort").equals(config.path("sourcePort"))) {
|| !route.path("sourcePort").equals(config.path("sourcePort"))
|| !target.equals(socket.getRemoteSocketAddress())) {
lastSource = null;
lastNegotiationSource = null;
}
socket.disconnect();
socket.connect(new InetSocketAddress(config.path("targetHost").asText(),
config.path("targetPort").asInt()));
if (!target.equals(socket.getRemoteSocketAddress())) {
socket.disconnect();
socket.connect(target);
}
route = config;
}
@@ -372,7 +418,8 @@ public class GatewayService {
}
// 记住最近真实来源,动态源端口的配置及回执才能准确返回。
synchronized void send(byte[] bytes, InetSocketAddress source) throws Exception {
synchronized void send(byte[] bytes, InetSocketAddress source, InetSocketAddress target) throws Exception {
require(target.equals(socket.getRemoteSocketAddress()), "Platform UDP target changed");
// 类型字节只用于选择回程 socket,不能据此新增路由或认定报文可信。
// 协商请求不能覆盖既有配置回执的设备端口,普通上行也不能覆盖协商端口。
if (frameType(bytes, bytes.length, 0x14)) {
@@ -0,0 +1,158 @@
package com.xtrh.gateway.service;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedSelectorException;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
/** 通过独立临时出口区分实际发送方,平台可按报文的来源端口回复。 */
final class UdpForwardSessions implements AutoCloseable {
private static final int MAX_SESSIONS = 2048;
private static final long IDLE_NANOS = TimeUnit.MINUTES.toNanos(2);
private static final class Session {
final DatagramChannel channel;
long lastActive;
Session(DatagramChannel channel) {
this.channel = channel;
}
}
private final DatagramSocket ingress;
private final AtomicLong errors;
private final Selector selector;
private final LinkedHashMap<InetSocketAddress, Session> sessions = new LinkedHashMap<>(16, 0.75f, true);
private InetSocketAddress target;
UdpForwardSessions(DatagramSocket ingress, AtomicLong errors) throws IOException {
this.ingress = ingress;
this.errors = errors;
selector = Selector.open();
Thread thread = new Thread(this::receiveReplies, "xtrh-udp-session-replies");
thread.setDaemon(true);
thread.start();
}
synchronized void setTarget(InetSocketAddress target) {
if (!Objects.equals(this.target, target)) {
clearSessions();
this.target = target;
}
}
synchronized void send(byte[] bytes, InetSocketAddress source, InetSocketAddress expectedTarget) throws IOException {
if (!selector.isOpen() || target == null || !target.equals(expectedTarget)) {
throw new IOException("UDP forwarding target changed");
}
Session session = sessions.get(source);
if (session == null) {
if (sessions.size() == MAX_SESSIONS) {
Iterator<Session> oldest = sessions.values().iterator();
closeChannel(oldest.next().channel);
oldest.remove();
}
DatagramChannel channel = DatagramChannel.open();
try {
channel.bind(null);
channel.configureBlocking(false);
selector.wakeup();
channel.register(selector, SelectionKey.OP_READ, source);
} catch (IOException | RuntimeException failure) {
closeChannel(channel);
throw failure;
}
session = new Session(channel);
sessions.put(source, session);
}
session.lastActive = System.nanoTime();
// 使用带目的地址的 send,也能把零字节报文作为一个独立的数据报发出。
if (session.channel.send(ByteBuffer.wrap(bytes), target) != bytes.length) {
throw new IOException("UDP forwarding socket could not send the datagram");
}
}
private void receiveReplies() {
ByteBuffer buffer = ByteBuffer.allocate(65535);
while (selector.isOpen()) {
try {
selector.select(1000);
processReplies(buffer);
} catch (ClosedSelectorException closed) {
return;
} catch (IOException failure) {
if (selector.isOpen()) {
errors.incrementAndGet();
}
}
}
}
private synchronized void processReplies(ByteBuffer buffer) {
Iterator<SelectionKey> ready = selector.selectedKeys().iterator();
while (ready.hasNext()) {
SelectionKey key = ready.next();
ready.remove();
if (!key.isValid()) {
continue;
}
DatagramChannel channel = (DatagramChannel) key.channel();
InetSocketAddress source = (InetSocketAddress) key.attachment();
try {
buffer.clear();
if (target != null && target.equals(channel.receive(buffer))) {
Session session = sessions.get(source);
session.lastActive = System.nanoTime();
ingress.send(new DatagramPacket(buffer.array(), buffer.position(), source));
}
} catch (IOException failure) {
errors.incrementAndGet();
}
}
long now = System.nanoTime();
Iterator<Session> oldest = sessions.values().iterator();
while (oldest.hasNext()) {
Session session = oldest.next();
if (now - session.lastActive < IDLE_NANOS) {
break;
}
closeChannel(session.channel);
oldest.remove();
}
}
private void closeChannel(DatagramChannel channel) {
try {
channel.close();
} catch (IOException failure) {
errors.incrementAndGet();
}
}
private void clearSessions() {
for (Session session : sessions.values()) {
closeChannel(session.channel);
}
sessions.clear();
}
@Override
public synchronized void close() {
clearSessions();
try {
selector.close();
} catch (IOException failure) {
errors.incrementAndGet();
}
}
}
@@ -0,0 +1,17 @@
package com.xtrh.input.controller;
import com.fasterxml.jackson.databind.JsonNode;
import com.xtrh.input.service.FusionInputRouter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.web.bind.annotation.*;
/** All paths are protected by the existing service HMAC filter. */
@RestController
@ConditionalOnProperty(name = "fusion.role", havingValue = "coordinator", matchIfMissing = true)
public class FusionInputController {
private final FusionInputRouter router;
public FusionInputController(FusionInputRouter router) { this.router = router; }
@PostMapping("/control/input") public Object input(@RequestBody JsonNode input) throws Exception { return router.route(input); }
@PostMapping("/control/input-bindings") public Object bindings(@RequestBody JsonNode input) { return router.bindings(input); }
@PostMapping("/control/input-image") public Object image(@RequestBody JsonNode input) throws Exception { return router.originalImage(input); }
}
@@ -0,0 +1,24 @@
package com.xtrh.input.controller;
import com.fasterxml.jackson.databind.JsonNode;
import com.xtrh.input.service.LocalFusionInput;
import com.xtrh.node.config.WorkerCapabilityCondition;
import org.springframework.context.annotation.Conditional;
import org.springframework.web.bind.annotation.*;
@RestController
@Conditional(WorkerCapabilityCondition.class)
public class NodeInputController {
private final LocalFusionInput input;
private final com.xtrh.input.service.OriginalInputRelay images;
public NodeInputController(LocalFusionInput input, com.xtrh.input.service.OriginalInputRelay images) { this.input = input; this.images = images; }
@PostMapping("/node/input") public Object accept(@RequestBody JsonNode body) { return input.accept(body); }
@PutMapping("/node/input/target")
public Object changeTarget(@RequestBody JsonNode body) throws java.io.IOException {
var port = body.path("port");
if (!body.path("host").isTextual() || !port.isIntegralNumber() || !port.canConvertToInt())
throw new IllegalArgumentException("Invalid gRPC host or port");
return input.changeTarget(body.path("host").asText(), port.intValue());
}
@GetMapping("/node/input/status") public Object status() { var state=input.status();state.set("originalImages",images.status());return state; }
}
@@ -0,0 +1,44 @@
package com.xtrh.input.protocol;
import com.google.protobuf.ByteString;
import com.google.protobuf.DescriptorProtos;
import com.google.protobuf.Descriptors;
import com.google.protobuf.DynamicMessage;
import com.google.protobuf.Empty;
import io.grpc.MethodDescriptor;
import io.grpc.protobuf.ProtoUtils;
/** Standard protobuf wire contract, also published as fusion_input.proto for other languages. */
public final class FusionInputProtocol {
public static final String SERVICE = "xtrh.fusion.v1.FusionInputService";
public static final Descriptors.Descriptor DESCRIPTOR;
public static final MethodDescriptor<DynamicMessage, Empty> PUSH;
static {
try {
var message = DescriptorProtos.DescriptorProto.newBuilder().setName("FusionInput")
.addField(field("json", 1, DescriptorProtos.FieldDescriptorProto.Type.TYPE_STRING))
.addField(field("image", 2, DescriptorProtos.FieldDescriptorProto.Type.TYPE_BYTES));
var file = DescriptorProtos.FileDescriptorProto.newBuilder().setName("fusion_input.proto")
.setPackage("xtrh.fusion.v1").setSyntax("proto3").addMessageType(message).build();
DESCRIPTOR = Descriptors.FileDescriptor.buildFrom(file, new Descriptors.FileDescriptor[0])
.findMessageTypeByName("FusionInput");
PUSH = MethodDescriptor.<DynamicMessage, Empty>newBuilder()
.setType(MethodDescriptor.MethodType.CLIENT_STREAMING)
.setFullMethodName(MethodDescriptor.generateFullMethodName(SERVICE, "Push"))
.setRequestMarshaller(ProtoUtils.marshaller(DynamicMessage.getDefaultInstance(DESCRIPTOR)))
.setResponseMarshaller(ProtoUtils.marshaller(Empty.getDefaultInstance())).build();
} catch (Descriptors.DescriptorValidationException error) {
throw new ExceptionInInitializerError(error);
}
}
private FusionInputProtocol() {}
private static DescriptorProtos.FieldDescriptorProto field(String name, int number,
DescriptorProtos.FieldDescriptorProto.Type type) {
return DescriptorProtos.FieldDescriptorProto.newBuilder().setName(name).setNumber(number)
.setType(type).setLabel(DescriptorProtos.FieldDescriptorProto.Label.LABEL_OPTIONAL).build();
}
public static DynamicMessage message(String json, byte[] image) {
return DynamicMessage.newBuilder(DESCRIPTOR).setField(DESCRIPTOR.findFieldByNumber(1), json)
.setField(DESCRIPTOR.findFieldByNumber(2), ByteString.copyFrom(image)).build();
}
}
@@ -0,0 +1,49 @@
package com.xtrh.input.protocol;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.nio.charset.StandardCharsets;
import static com.xtrh.common.util.Jsons.object;
/** Reads the existing collector HD-UPLOAD JPEG comment; never re-encodes the JPEG. */
public final class ImageUploadMetadata {
private static final ObjectMapper JSON = new ObjectMapper();
private ImageUploadMetadata() {}
public static ObjectNode validate(JsonNode upload) {
if (!upload.isObject() || !"FIXED_30".equals(upload.path("mode").asText())
|| !upload.path("time").isIntegralNumber() || !upload.path("time").canConvertToLong()
|| upload.path("time").asLong() <= 0 || upload.path("time").asLong() > 9007199254740991L
|| !upload.path("reused").isBoolean()) throw new IllegalArgumentException("Invalid upload metadata");
ObjectNode result = object().put("mode","FIXED_30").put("time",upload.path("time").asLong())
.put("reused",upload.path("reused").asBoolean());
if (upload.has("frameId")) {
if (!upload.path("frameId").isTextual() || !upload.path("frameId").asText().matches("[0-9a-f]{16}"))
throw new IllegalArgumentException("Invalid upload frame ID");
result.put("frameId",upload.path("frameId").asText());
}
if (upload.has("sourceTime")) {
if (!upload.path("sourceTime").isIntegralNumber() || !upload.path("sourceTime").canConvertToLong()
|| upload.path("sourceTime").asLong() <= 0) throw new IllegalArgumentException("Invalid image source time");
result.put("sourceTime",upload.path("sourceTime").asLong());
}
return result;
}
public static ObjectNode read(byte[] jpeg) {
if (jpeg.length < 4 || (jpeg[0]&255)!=255 || (jpeg[1]&255)!=216) return null;
int at=2;
while (at+4<=jpeg.length && (jpeg[at]&255)==255) {
int marker=jpeg[at+1]&255;
if (marker==218 || marker==217) break;
int length=((jpeg[at+2]&255)<<8)|(jpeg[at+3]&255);
if (length<2 || at+2+length>jpeg.length) break;
if (marker==254 && length<=2048) {
String comment=new String(jpeg,at+4,length-2,StandardCharsets.UTF_8);
if (comment.startsWith("HD-UPLOAD: ")) try { return validate(JSON.readTree(comment.substring(11))); }
catch (Exception invalid) { return null; }
}
at+=2+length;
}
return null;
}
}
@@ -0,0 +1,81 @@
package com.xtrh.input.service;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.xtrh.common.config.Settings;
import com.xtrh.communication.client.PeerClient;
import com.xtrh.control.service.CoordinatorService;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.xtrh.common.util.Jsons.object;
/** Routes an equipment's inputs to an execution node; the final gRPC hop is always node-local. */
@Service
@ConditionalOnProperty(name = "fusion.role", havingValue = "coordinator", matchIfMissing = true)
public class FusionInputRouter {
private final CoordinatorService coordinator;
private final PeerClient peer;
private final LocalFusionInput local;
private final Settings settings;
private Map<String, ObjectNode> imageBindings = Map.of();
private long bindingObservedAt, bindingSyncedAt;
public FusionInputRouter(CoordinatorService coordinator, PeerClient peer, LocalFusionInput local, Settings settings) {
this.coordinator = coordinator; this.peer = peer; this.local = local; this.settings = settings;
}
public ObjectNode route(JsonNode input) throws Exception {
LocalFusionInput.validate(input);
ObjectNode target = coordinator.inputTarget(input.path("trialId").asText(""), input.path("equipmentId").asText());
if (target.path("nodeId").asText().equals(settings.id)) return local.accept(input);
JsonNode result = peer.request(target.path("baseUrl").asText(), "/node/input", "POST", input);
if (!result.path("accepted").asBoolean()) throw new IllegalStateException("Input node did not accept input");
return (ObjectNode)result;
}
/** Replace, including an empty list, so removed or ended bindings cannot linger. */
public synchronized ObjectNode bindings(JsonNode input) {
long now = System.currentTimeMillis(), observed = input.path("observedAt").asLong();
if (observed <= 0 || observed < bindingObservedAt || Math.abs(now - observed) > 60_000
|| !input.path("bindings").isArray() || input.path("bindings").size() > 512)
throw new IllegalArgumentException("Invalid input bindings");
Map<String, ObjectNode> next = new HashMap<>();
for (JsonNode row : input.path("bindings")) {
for (String key : List.of("sourceEndpointId", "equipmentId"))
if (!row.path(key).isTextual() || row.path(key).asText().isBlank() || row.path(key).asText().length() > 200)
throw new IllegalArgumentException("Invalid input binding identity");
LocalFusionInput.copyTrialContext(object(),row);
LocalFusionInput.copySimulationContext(object(),row);
if (!row.path("validFrom").isIntegralNumber() || row.path("validFrom").asLong() <= 0
|| next.put(row.path("sourceEndpointId").asText(), row.deepCopy()) != null)
throw new IllegalArgumentException("Ambiguous input image binding");
}
imageBindings = Map.copyOf(next); bindingObservedAt = observed; bindingSyncedAt = now;
return object().put("accepted", true).put("bindings", next.size());
}
/** Original-image nodes know authenticated endpoints, not equipment IDs; resolve only signed bindings. */
public ObjectNode originalImage(JsonNode input) throws Exception {
ObjectNode binding;
synchronized (this) {
binding = imageBindings.get(input.path("sourceEndpointId").asText());
if (binding == null || System.currentTimeMillis() - bindingSyncedAt > 15_000
|| input.path("sourceTime").asLong() < binding.path("validFrom").asLong())
return object().put("accepted", false).put("reason", "UNBOUND_OR_STALE_IMAGE");
binding = binding.deepCopy();
}
ObjectNode event = ((ObjectNode)input).deepCopy();
for (String key : List.of("equipmentId", "equipmentCode", "moduleNo", "moduleType", "collectionWay"))
event.put(key, binding.path(key).asText());
LocalFusionInput.copyTrialContext(event,binding);
LocalFusionInput.copySimulationContext(event,binding);
event.put("kind", "IMAGE");
event.put("messageId", "image/" + event.path("equipmentId").asText() + "/" + event.path("sourceEndpointId").asText()
+ "/" + event.path("sourceTime").asText() + "/" + event.path("frameId").asText());
return route(event);
}
}
@@ -0,0 +1,44 @@
package com.xtrh.input.service;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
record GrpcTarget(String host, int port) {
private static final ObjectMapper JSON = new ObjectMapper();
GrpcTarget {
host = host == null ? "" : host.strip();
if (host.startsWith("[") && host.endsWith("]")) host = host.substring(1, host.length() - 1);
try {
var uri = new URI("http", null, host, port, null, null, null).parseServerAuthority();
if (uri.getHost() == null || host.isBlank() || host.contains("/") || host.contains("@") || host.contains("%")
|| port < 1 || port > 65535) throw new IllegalArgumentException("Invalid gRPC target");
} catch (URISyntaxException invalid) {
throw new IllegalArgumentException("Invalid gRPC host", invalid);
}
}
static GrpcTarget load(Path path, GrpcTarget fallback) {
if (Files.notExists(path)) return fallback;
try {
return JSON.readValue(Files.readAllBytes(path), GrpcTarget.class);
} catch (IOException failure) {
throw new IllegalStateException("Cannot read saved gRPC target", failure);
}
}
void save(Path path) throws IOException {
Path temporary = Files.createTempFile(path.getParent(), "grpc-target-", ".tmp");
try {
Files.write(temporary, JSON.writeValueAsBytes(this));
Files.move(temporary, path, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
} finally {
Files.deleteIfExists(temporary);
}
}
}
@@ -0,0 +1,312 @@
package com.xtrh.input.service;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.protobuf.DynamicMessage;
import com.google.protobuf.Empty;
import com.xtrh.common.config.Settings;
import com.xtrh.input.protocol.FusionInputProtocol;
import io.grpc.CallOptions;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.Status;
import io.grpc.stub.ClientCalls;
import io.grpc.stub.StreamObserver;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HexFormat;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import static com.xtrh.common.util.Jsons.object;
/** Bounded asynchronous delivery to the configured gRPC receiver. */
@Service
public class LocalFusionInput implements AutoCloseable {
private record Pending(String id, String digest, DynamicMessage message, int bytes) {}
private final boolean enabled;
private final java.nio.file.Path targetFile;
private GrpcTarget target;
private final int capacity, timeoutMs;
private final long maxBytes;
private final RecentModuleInput recentData;
private final ArrayDeque<Pending> queue = new ArrayDeque<>();
private final LinkedHashMap<String, String> acceptedIds = new LinkedHashMap<>();
private ManagedChannel channel;
private Thread sender;
private volatile boolean closed;
private long buffered, accepted, completed, retries, rejected, imagesWithData, imagesWithoutData;
private String error = "";
public LocalFusionInput(Settings settings, Environment env) {
enabled = settings.supportsWorker && env.getProperty("fusion.input-grpc.enabled", Boolean.class, false);
targetFile = settings.directory.resolve("input-grpc-target.json");
target = GrpcTarget.load(targetFile, new GrpcTarget(env.getProperty("fusion.input-grpc.host", "127.0.0.1"),
env.getProperty("fusion.input-grpc.port", Integer.class, 50051)));
capacity = env.getProperty("fusion.input-grpc.queue-capacity", Integer.class, 2048);
maxBytes = env.getProperty("fusion.input-grpc.max-buffer-bytes", Long.class, 64L * 1024 * 1024);
timeoutMs = env.getProperty("fusion.input-grpc.timeout-ms", Integer.class, 3000);
recentData = new RecentModuleInput(env.getProperty("fusion.input-grpc.image-data-max-age-ms", Long.class, 15_000L));
if (capacity < 1 || capacity > 65536 || maxBytes < 4 * 1024 * 1024
|| maxBytes > 1024L * 1024 * 1024 || timeoutMs < 100 || timeoutMs > 60000)
throw new IllegalArgumentException("Invalid fusion input configuration");
}
public boolean enabled() { return enabled; }
private static ManagedChannel openChannel(GrpcTarget target) {
return ManagedChannelBuilder.forAddress(target.host(), target.port()).usePlaintext().build();
}
public synchronized ObjectNode changeTarget(String host, int port) throws java.io.IOException {
if (closed) throw new IllegalStateException("Fusion input is shutting down");
GrpcTarget next = new GrpcTarget(host, port);
if (next.equals(target)) {
if (java.nio.file.Files.notExists(targetFile)) next.save(targetFile);
return status();
}
ManagedChannel replacement = channel == null ? null : openChannel(next);
try {
next.save(targetFile);
} catch (java.io.IOException | RuntimeException failure) {
if (replacement != null) replacement.shutdownNow();
throw failure;
}
ManagedChannel previous = channel;
target = next;
channel = replacement;
if (previous != null) previous.shutdown();
return status();
}
@PostConstruct public synchronized void start() {
if (!enabled || sender != null) return;
// Loopback remains the default; a LAN host supports an external receiver.
channel = openChannel(target);
sender = new Thread(this::sendLoop, "xtrh-local-fusion-input");
sender.setDaemon(true);
sender.start();
}
/** Called only behind the existing service-signature filter. Base64 is inter-node HTTP transport only. */
public synchronized ObjectNode accept(JsonNode input) {
if (!enabled || closed) throw new IllegalStateException("Local fusion input is disabled");
ObjectNode metadata = validate(input);
byte[] image = new byte[0];
if (metadata.path("kind").asText().equals("IMAGE")) {
JsonNode encoded = input.path("imageBase64");
if (!encoded.isTextual() || encoded.textValue().length() > 2_800_000)
throw new IllegalArgumentException("Invalid image bytes");
try { image = Base64.getDecoder().decode(encoded.textValue()); }
catch (IllegalArgumentException bad) { throw new IllegalArgumentException("Invalid image bytes"); }
if (image.length < 4 || image.length > 2 * 1024 * 1024 || (image[0] & 255) != 255
|| (image[1] & 255) != 216 || (image[image.length - 2] & 255) != 255
|| (image[image.length - 1] & 255) != 217) throw new IllegalArgumentException("Invalid JPEG");
metadata.put("imageBytes", image.length).put("imageContentType", "image/jpeg");
} else if (input.has("imageBase64")) throw new IllegalArgumentException("Unexpected image bytes");
String json = metadata.toString(), id = metadata.path("messageId").asText();
byte[] jsonBytes = json.getBytes(StandardCharsets.UTF_8);
if (jsonBytes.length > 256 * 1024) throw new IllegalArgumentException("Input metadata too large");
ObjectNode stable = metadata.deepCopy(); stable.remove("receivedTime");
String digest = digest(stable.toString().getBytes(StandardCharsets.UTF_8), image);
String previous = acceptedIds.get(id);
if (previous != null) {
if (!previous.equals(digest)) throw new IllegalArgumentException("Input identity reused with different content");
return object().put("accepted", true).put("duplicate", true);
}
// Hash the accepted input before enrichment so retries cannot pick up newer module data.
boolean imageWithData = image.length > 0 && recentData.attach(metadata);
json = metadata.toString();
jsonBytes = json.getBytes(StandardCharsets.UTF_8);
if (jsonBytes.length > 256 * 1024) {
// Optional measured fields must not stop a valid image when metadata reaches the size limit.
metadata.remove(List.of("data", "dataSourceTime", "dataReceivedTime", "dataMessageId", "dataAssociation", "dataAssociationTimeBasis"));
imageWithData = false;
recentData.metadataTooLarge();
json = metadata.toString();
jsonBytes = json.getBytes(StandardCharsets.UTF_8);
}
int bytes = jsonBytes.length + image.length;
if (queue.size() >= capacity || buffered + bytes > maxBytes) {
rejected++;
throw new IllegalStateException("Local fusion input queue is full");
}
// Protobuf owns immutable image bytes. Neither the preview cache nor the caller can mutate them.
queue.add(new Pending(id, digest, FusionInputProtocol.message(json, image), bytes));
acceptedIds.put(id, digest);
buffered += bytes;
accepted++;
if (image.length == 0) recentData.remember(metadata);
else if (imageWithData) imagesWithData++;
else imagesWithoutData++;
trimIds();
notifyAll();
return object().put("accepted", true).put("duplicate", false);
}
public static ObjectNode validate(JsonNode input) {
if (input == null || !input.isObject()) throw new IllegalArgumentException("Invalid fusion input");
ObjectNode result = object().put("schemaVersion", 1);
for (String key : List.of("messageId", "equipmentId", "sourceEndpointId", "kind"))
result.put(key, text(input, key, true));
copyTrialContext(result,input);
copySimulationContext(result,input);
String kind = result.path("kind").asText();
if (!Set.of("DATA", "IMAGE").contains(kind)) throw new IllegalArgumentException("Invalid input kind");
for (String key : List.of("equipmentCode", "moduleNo", "moduleType", "collectionWay", "packetId"))
result.put(key, text(input, key, false));
String alignment = text(input, "frameId", kind.equals("IMAGE"));
if (!alignment.isEmpty() && !alignment.matches("[0-9a-f]{16}")) throw new IllegalArgumentException("Invalid frame ID");
if (alignment.isEmpty()) result.putNull("frameId"); else result.put("frameId", alignment);
result.put("pairingAvailable", !alignment.isEmpty());
if (input.hasNonNull("upload")) {
ObjectNode upload = com.xtrh.input.protocol.ImageUploadMetadata.validate(input.path("upload"));
if (upload.has("frameId") && !alignment.equals(upload.path("frameId").asText()))
throw new IllegalArgumentException("Conflicting frame IDs");
result.set("upload",upload);
}
for (String key : List.of("sourceTime", "receivedTime")) {
JsonNode value = input.path(key);
if (!value.isIntegralNumber() || !value.canConvertToLong() || value.longValue() <= 0)
throw new IllegalArgumentException("Invalid input time");
result.put(key, value.longValue());
}
if (kind.equals("DATA")) {
if (!input.path("data").isObject()) throw new IllegalArgumentException("Missing measured data");
result.set("data", input.path("data").deepCopy());
}
return result;
}
static void copySimulationContext(ObjectNode result, JsonNode input) {
result.put("participantCode", text(input, "participantCode", true));
var fields = List.of("simulationObjectId", "scenarioEquipmentId", "scenarioCacheId", "scenarioId");
boolean simulation = fields.stream().anyMatch(key -> !text(input, key, false).isEmpty());
// Real vehicles need no simulator object. If supplied, the simulator context must be complete.
// Remove untrusted image-provided context when the authoritative binding has none.
result.remove(fields);
if (simulation) for (String key : fields) result.put(key, text(input, key, true));
}
static void copyTrialContext(ObjectNode result, JsonNode input) {
String trial=text(input,"trialId",false);
var trials=new java.util.TreeSet<String>();
if(input.has("trialIds")){
if(!input.path("trialIds").isArray()||input.path("trialIds").size()>64)
throw new IllegalArgumentException("Invalid trial context");
for(JsonNode id:input.path("trialIds")){
if(!id.isTextual()||id.asText().isBlank()||id.asText().length()>240||id.asText().indexOf('\0')>=0)
throw new IllegalArgumentException("Invalid trial context");
trials.add(id.asText());
}
}
if(!trial.isEmpty()){
if(!trials.isEmpty()&&(trials.size()!=1||!trials.contains(trial)))
throw new IllegalArgumentException("Conflicting trial context");
trials.add(trial);
}
if(trials.isEmpty())throw new IllegalArgumentException("Missing trial context");
if(trials.size()==1)result.put("trialId",trials.first());else result.putNull("trialId");
var list=result.putArray("trialIds");trials.forEach(list::add);
}
private static String text(JsonNode input, String key, boolean required) {
JsonNode field = input.get(key);
if (field != null && !field.isNull() && !field.isTextual()) throw new IllegalArgumentException("Invalid " + key);
String value = field == null || field.isNull() ? "" : field.textValue();
if (value.length() > 240 || value.indexOf('\0') >= 0 || required && value.isBlank())
throw new IllegalArgumentException("Invalid " + key);
return value;
}
private void sendLoop() {
while (!closed) {
List<Pending> batch = new ArrayList<>();
ManagedChannel destination;
synchronized (this) {
while (queue.isEmpty() && !closed) try { wait(); }
catch (InterruptedException stopped) { Thread.currentThread().interrupt(); return; }
destination = channel;
int bytes = 0;
for (Pending next : queue) {
if (!batch.isEmpty() && (batch.size() >= 32 || bytes + next.bytes > 4 * 1024 * 1024)) break;
batch.add(next); bytes += next.bytes;
}
}
if (closed) return;
try {
transmit(destination, batch);
synchronized (this) {
if (closed) return;
for (Pending entry : batch) {
if (queue.peek() != entry) throw new IllegalStateException("Input queue order changed");
queue.remove(); buffered -= entry.bytes; completed++;
}
error = ""; trimIds();
}
} catch (Exception failure) {
synchronized (this) { retries++; error = "LOCAL_GRPC_" + Status.fromThrowable(failure).getCode().name(); }
try { Thread.sleep(250); } catch (InterruptedException stopped) { Thread.currentThread().interrupt(); return; }
}
}
}
private void transmit(ManagedChannel destination, List<Pending> batch) throws Exception {
var done = new CountDownLatch(1);
var failure = new AtomicReference<Throwable>();
var receipts = new java.util.concurrent.atomic.AtomicInteger();
var call = destination.newCall(FusionInputProtocol.PUSH, CallOptions.DEFAULT.withDeadlineAfter(timeoutMs, TimeUnit.MILLISECONDS));
StreamObserver<DynamicMessage> stream = ClientCalls.asyncClientStreamingCall(call, new StreamObserver<Empty>() {
public void onNext(Empty receipt) { receipts.incrementAndGet(); }
public void onError(Throwable error) { failure.set(error); done.countDown(); }
public void onCompleted() { done.countDown(); }
});
try {
for (Pending entry : batch) stream.onNext(entry.message);
stream.onCompleted();
if (!done.await(timeoutMs + 250L, TimeUnit.MILLISECONDS)) throw Status.DEADLINE_EXCEEDED.asRuntimeException();
if (failure.get() != null) throw Status.fromThrowable(failure.get()).asRuntimeException();
if (receipts.get() != 1) throw Status.INTERNAL.withDescription("Missing input receipt").asRuntimeException();
} finally { call.cancel("Input batch finished", null); }
}
private void trimIds() {
if (acceptedIds.size() <= capacity + 4096) return;
var pending = new java.util.HashSet<String>();
queue.forEach(item -> pending.add(item.id));
var iterator = acceptedIds.keySet().iterator();
while (acceptedIds.size() > capacity + 4096 && iterator.hasNext())
if (!pending.contains(iterator.next())) iterator.remove();
}
private static String digest(byte[] json, byte[] image) {
try { var sha = MessageDigest.getInstance("SHA-256"); sha.update(json); return HexFormat.of().formatHex(sha.digest(image)); }
catch (Exception impossible) { throw new IllegalStateException(impossible); }
}
public synchronized ObjectNode status() {
return object().put("enabled", enabled).put("host", target.host()).put("port", target.port()).put("queued", queue.size())
.put("bufferedBytes", buffered).put("accepted", accepted).put("rpcCompleted", completed)
.put("retries", retries).put("rejected", rejected).put("error", error)
.put("imagesWithData", imagesWithData).put("imagesWithoutData", imagesWithoutData)
.put("imageDataMaxAgeMs", recentData.maxAgeMs()).put("imageDataTimeBasis", "NODE_RECEIPT")
.set("imageDataMissReasons", recentData.missCounts());
}
@Override @PreDestroy public synchronized void close() {
closed = true;
notifyAll();
if (sender != null) sender.interrupt();
if (channel != null) channel.shutdownNow();
queue.clear(); acceptedIds.clear(); recentData.clear(); buffered = 0;
}
}
@@ -0,0 +1,75 @@
package com.xtrh.input.service;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.xtrh.communication.client.PeerClient;
import com.xtrh.discovery.service.CoordinatorLocator;
import com.xtrh.node.config.WorkerCapabilityCondition;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import org.springframework.context.annotation.Conditional;
import org.springframework.stereotype.Service;
import java.util.ArrayDeque;
import java.util.Base64;
import static com.xtrh.common.util.Jsons.object;
/** Bridges each authenticated complete JPEG, independently of the three-frame preview cache. */
@Service
@Conditional(WorkerCapabilityCondition.class)
public class OriginalInputRelay implements AutoCloseable {
private record Frame(String endpoint, String id, long source, long received, byte[] jpeg, ObjectNode upload) {}
private final PeerClient peer;
private final CoordinatorLocator locator;
private final LocalFusionInput local;
private final ArrayDeque<Frame> frames = new ArrayDeque<>();
private long bytes, rejected, sent, unbound;
private volatile boolean closed;
private Thread sender;
public OriginalInputRelay(PeerClient peer, CoordinatorLocator locator, LocalFusionInput local) {
this.peer = peer; this.locator = locator; this.local = local;
}
public synchronized void received(String endpoint, long frame, long source, long received, byte[] jpeg) {
if (!local.enabled() || closed) return;
if (frames.size() >= 512 || bytes + jpeg.length > 64L * 1024 * 1024) { rejected++; return; }
String frameId = String.format("%016x",frame);
ObjectNode upload = com.xtrh.input.protocol.ImageUploadMetadata.read(jpeg);
if (upload != null && upload.has("frameId") && !frameId.equals(upload.path("frameId").asText())) { rejected++; return; }
frames.add(new Frame(endpoint, frameId, source, received, jpeg.clone(), upload));
bytes += jpeg.length; notifyAll();
}
@PostConstruct public synchronized void start() {
if (!local.enabled() || sender != null) return;
sender = new Thread(this::run, "xtrh-original-input-relay"); sender.setDaemon(true); sender.start();
}
private void run() {
while (!closed) {
Frame frame;
synchronized (this) {
while (frames.isEmpty() && !closed) try { wait(); }
catch (InterruptedException stopped) { Thread.currentThread().interrupt(); return; }
if (closed) return;
frame = frames.peek();
}
try {
ObjectNode message = object().put("sourceEndpointId", frame.endpoint).put("frameId", frame.id)
.put("sourceTime", frame.source).put("receivedTime", frame.received)
.put("imageBase64", Base64.getEncoder().encodeToString(frame.jpeg));
if (frame.upload != null) message.set("upload",frame.upload);
var result = peer.request(locator.locate(), "/control/input-image", "POST", message);
synchronized (this) {
if (closed) return;
frames.remove(); bytes -= frame.jpeg.length;
if (result.path("accepted").asBoolean()) sent++; else unbound++;
}
} catch (Exception failed) {
try { Thread.sleep(500); } catch (InterruptedException stopped) { Thread.currentThread().interrupt(); return; }
}
}
}
public synchronized ObjectNode status() {
return object().put("queued", frames.size()).put("bufferedBytes", bytes).put("sent", sent)
.put("rejected", rejected).put("unbound", unbound);
}
@Override @PreDestroy public synchronized void close() {
closed = true; notifyAll(); if (sender != null) sender.interrupt(); frames.clear(); bytes = 0;
}
}
@@ -0,0 +1,87 @@
package com.xtrh.input.service;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.function.LongSupplier;
import static com.xtrh.common.util.Jsons.object;
/** Latest received fields for an authoritative vehicle/trial/module; sender clocks do not define cache freshness. */
final class RecentModuleInput {
private record Entry(ObjectNode snapshot, long acceptedAt, int bytes) {}
private static final int MAX_MODULES = 512, MAX_BYTES = 4 * 1024 * 1024;
private final LinkedHashMap<String, Entry> entries = new LinkedHashMap<>();
private final LinkedHashMap<String, Long> misses = new LinkedHashMap<>();
private final long maxAgeMs;
private final LongSupplier clock;
private int buffered;
RecentModuleInput(long maxAgeMs) { this(maxAgeMs, System::nanoTime); }
RecentModuleInput(long maxAgeMs, LongSupplier clock) {
if (maxAgeMs < 100 || maxAgeMs > 300_000) throw new IllegalArgumentException("Invalid image data age limit");
this.maxAgeMs = maxAgeMs;
this.clock = clock;
for (String reason : List.of("NO_SAME_MODULE_DATA", "CACHE_EXPIRED", "METADATA_TOO_LARGE")) misses.put(reason, 0L);
}
void remember(ObjectNode input) {
expire();
String key = key(input);
ObjectNode snapshot = object();
for (String field : List.of("messageId", "sourceTime", "receivedTime", "data"))
snapshot.set(field, input.path(field).deepCopy());
int bytes = snapshot.toString().getBytes(StandardCharsets.UTF_8).length + key.length() * 2;
Entry previous = entries.remove(key);
if (previous != null) buffered -= previous.bytes;
entries.put(key, new Entry(snapshot, clock.getAsLong(), bytes));
buffered += bytes;
var iterator = entries.values().iterator();
while ((entries.size() > MAX_MODULES || buffered > MAX_BYTES) && iterator.hasNext()) {
buffered -= iterator.next().bytes; iterator.remove();
}
}
boolean attach(ObjectNode image) {
String key = key(image);
boolean existed = entries.containsKey(key);
expire();
Entry entry = entries.get(key);
if (entry == null) return miss(existed ? "CACHE_EXPIRED" : "NO_SAME_MODULE_DATA");
// Images and measurements may use different clocks or deliberately reuse source timestamps.
// Compose the most recently received fields, preserving both original times for the receiver.
ObjectNode sample = entry.snapshot;
image.set("data", sample.path("data").deepCopy());
image.put("dataSourceTime", sample.path("sourceTime").asLong());
image.put("dataReceivedTime", sample.path("receivedTime").asLong());
image.put("dataMessageId", sample.path("messageId").asText());
image.put("dataAssociation", "LATEST_SAME_MODULE");
image.put("dataAssociationTimeBasis", "NODE_RECEIPT");
return true;
}
private static String key(ObjectNode input) {
ObjectNode context = object();
for (String field : List.of("equipmentId", "trialIds", "participantCode", "sourceEndpointId", "moduleNo",
"moduleType", "collectionWay", "simulationObjectId", "scenarioEquipmentId", "scenarioCacheId", "scenarioId"))
context.set(field, input.path(field));
return context.toString();
}
private void expire() {
long now = clock.getAsLong();
var iterator = entries.values().iterator();
while (iterator.hasNext()) {
Entry entry = iterator.next();
if (now - entry.acceptedAt > TimeUnit.MILLISECONDS.toNanos(maxAgeMs)) {
buffered -= entry.bytes; iterator.remove();
}
}
}
private boolean miss(String reason) { misses.merge(reason, 1L, Long::sum); return false; }
void metadataTooLarge() { miss("METADATA_TOO_LARGE"); }
ObjectNode missCounts() { ObjectNode result = object(); misses.forEach(result::put); return result; }
long maxAgeMs() { return maxAgeMs; }
void clear() { entries.clear(); buffered = 0; }
}
@@ -49,6 +49,7 @@ import static com.xtrh.common.util.Jsons.object;
@Service
@Conditional(WorkerCapabilityCondition.class)
public class ImageIngressService implements AutoCloseable {
@Autowired(required = false) private com.xtrh.input.service.OriginalInputRelay fusionInput;
// 一个 FND 帧最多承载 1024 字节明文,其中 36 字节属于 JPG1 分片头。
// 重组最多 32 帧、64MiB;完整帧缓存另有 64MiB 预算,不随设备持续上传而增长。
// 图片解码串行执行,实际尺寸也受限制,压缩 JPEG 不能扩大到任意像素数。
@@ -404,6 +405,7 @@ public class ImageIngressService implements AutoCloseable {
require(Byte.toUnsignedInt(assembly.data[0]) == 255 && Byte.toUnsignedInt(assembly.data[1]) == 216
&& Byte.toUnsignedInt(assembly.data[size - 2]) == 255 && Byte.toUnsignedInt(assembly.data[size - 1]) == 217);
validateJpeg(assembly.data, width, height);
if (fusionInput != null) fusionInput.received(authenticated.endpoint, wireFrame, time, now, assembly.data);
// 同来源多任务共享只读帧对象;任务版本仍各有许可,撤销其中一路不影响其他有效任务。
Frame frame = new Frame(java.util.UUID.randomUUID().toString(), authenticated.endpoint, time, now,
@@ -72,6 +72,7 @@ public class WorkerService {
private final CoordinatorLocator locator;
private final PeerClient peer;
private final ImageIngressService images;
@Autowired(required = false) private com.xtrh.input.service.LocalFusionInput fusionInput;
// 心跳、画面生成和 HTTP 播放会同时访问任务,键包含任务号及分配版本。
private final ConcurrentMap<String, MediaTask> tasks = new ConcurrentHashMap<>();
private volatile String session = "", connection = "WAITING";
@@ -144,6 +145,7 @@ public class WorkerService {
.put("nodeRole", settings.role.equals("coordinator") ? "COORDINATOR" : "WORKER")
.put("name", settings.name).put("capacity", settings.capacity)
.put("baseUrl", NodeAddress.url(settings, coordinator));
registration.put("inputForwarding", fusionInput != null && fusionInput.enabled());
// 图片直达节点 UDP 端口;控制与浏览器媒体接口仍复用现有 HTTP 端口。
// 广播和注册中只有地址与能力,设备 SM4/HMAC 密钥只存在私有任务计划。
if (images != null && imagePort > 0) {
+18
View File
@@ -0,0 +1,18 @@
syntax = "proto3";
package xtrh.fusion.v1;
import "google/protobuf/empty.proto";
// json contains the authoritative trial/vehicle/module identities and parameter-code values.
// IMAGE json may include recent data for the exact same binding with dataSourceTime and
// dataAssociation=LATEST_SAME_MODULE; this does not require matching frameId values.
// image contains the original JPEG bytes for IMAGE messages; it is empty for DATA.
message FusionInput {
string json = 1;
bytes image = 2;
}
service FusionInputService {
// Each short stream contains one or more inputs. Empty is a transport receipt,
// not a calibration/fusion result. Retries may repeat messageId values.
rpc Push(stream FusionInput) returns (google.protobuf.Empty);
}