新增融合输入接入并调整 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
@@ -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; }
}