新增融合输入接入并调整 UDP 网关转发
This commit is contained in:
@@ -31,7 +31,8 @@ class GatewayTest {
|
||||
CoordinatorLocator locator = mock(CoordinatorLocator.class);
|
||||
PeerClient peer = mock(PeerClient.class);
|
||||
when(locator.locate()).thenReturn("http://127.0.0.1:18100");
|
||||
try (DatagramSocket collector = loopbackSocket(); DatagramSocket pxhj = loopbackSocket()) {
|
||||
try (DatagramSocket collector = loopbackSocket(); DatagramSocket unknown = loopbackSocket();
|
||||
DatagramSocket pxhj = loopbackSocket()) {
|
||||
when(peer.request(anyString(), anyString(), anyString(), any()))
|
||||
.thenReturn(routes(collector.getLocalPort(), freePort(), pxhj.getLocalPort()));
|
||||
GatewayService gateway = new GatewayService(settings, locator, peer, new ObjectMapper());
|
||||
@@ -41,6 +42,8 @@ class GatewayTest {
|
||||
byte[] bytes = opaqueBytes(64);
|
||||
collector.send(new DatagramPacket(bytes, bytes.length, InetAddress.getLoopbackAddress(), ingressPort));
|
||||
assertArrayEquals(bytes, payload(receive(pxhj)));
|
||||
unknown.send(new DatagramPacket(bytes, bytes.length, InetAddress.getLoopbackAddress(), ingressPort));
|
||||
assertArrayEquals(bytes, payload(receive(pxhj)));
|
||||
|
||||
// 总控数据库重新初始化后可能复用旧版本号;明确确认的路由内容仍然必须生效。
|
||||
ObjectNode confirmedClear = object().put("routeVersion", 1).put("routesConfirmed", true);
|
||||
@@ -50,9 +53,10 @@ class GatewayTest {
|
||||
assertEquals(1, gateway.status().path("routeVersion").asLong());
|
||||
assertEquals(0, gateway.status().path("routeStatus").size());
|
||||
collector.send(new DatagramPacket(bytes, bytes.length, InetAddress.getLoopbackAddress(), ingressPort));
|
||||
unknown.send(new DatagramPacket(bytes, bytes.length, InetAddress.getLoopbackAddress(), ingressPort));
|
||||
pxhj.setSoTimeout(250);
|
||||
assertThrows(SocketTimeoutException.class, () -> receive(pxhj));
|
||||
assertEquals(1, gateway.status().path("unknownSource").asLong());
|
||||
assertEquals(2, gateway.status().path("unknownSource").asLong());
|
||||
} finally { gateway.close(); }
|
||||
}
|
||||
}
|
||||
@@ -98,21 +102,21 @@ class GatewayTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test void unknownSourcesAreDroppedAndLastConfirmedRoutesSurviveRestart() throws Exception {
|
||||
@Test void unregisteredAddressAndPortCanUseLastConfirmedTargetBeforeAndAfterRestart() throws Exception {
|
||||
Settings settings = settings(directory.resolve("persisted-gateway"));
|
||||
CoordinatorLocator locator = mock(CoordinatorLocator.class);
|
||||
PeerClient peer = mock(PeerClient.class);
|
||||
when(locator.locate()).thenReturn("http://127.0.0.1:18100");
|
||||
try (DatagramSocket collector = loopbackSocket(); DatagramSocket unknown = loopbackSocket(); DatagramSocket pxhj = loopbackSocket()) {
|
||||
when(peer.request(anyString(), anyString(), anyString(), any())).thenReturn(routes(collector.getLocalPort(), freePort(), pxhj.getLocalPort()));
|
||||
ObjectNode plan = routes(collector.getLocalPort(), freePort(), pxhj.getLocalPort());
|
||||
((ObjectNode) plan.path("routes").get(0)).put("sourceHost", "192.0.2.1");
|
||||
when(peer.request(anyString(), anyString(), anyString(), any())).thenReturn(plan);
|
||||
GatewayService gateway = new GatewayService(settings, locator, peer, new ObjectMapper());
|
||||
try {
|
||||
gateway.heartbeat();
|
||||
byte[] bytes = opaqueBytes(96);
|
||||
unknown.send(new DatagramPacket(bytes, bytes.length, InetAddress.getLoopbackAddress(), gateway.status().path("inputPort").asInt()));
|
||||
pxhj.setSoTimeout(250);
|
||||
assertThrows(SocketTimeoutException.class, () -> receive(pxhj));
|
||||
assertEquals(1, gateway.status().path("unknownSource").asLong());
|
||||
assertArrayEquals(bytes, payload(receive(pxhj)));
|
||||
} finally { gateway.close(); }
|
||||
|
||||
gateway = new GatewayService(settings, locator, peer, new ObjectMapper());
|
||||
@@ -123,14 +127,140 @@ class GatewayTest {
|
||||
when(peer.request(anyString(), anyString(), anyString(), any())).thenReturn(unconfirmed);
|
||||
gateway.heartbeat();
|
||||
assertEquals(1, gateway.status().path("routeVersion").asLong());
|
||||
pxhj.setSoTimeout(3000);
|
||||
byte[] bytes = opaqueBytes(160);
|
||||
collector.send(new DatagramPacket(bytes, bytes.length, InetAddress.getLoopbackAddress(), gateway.status().path("inputPort").asInt()));
|
||||
unknown.send(new DatagramPacket(bytes, bytes.length, InetAddress.getLoopbackAddress(), gateway.status().path("inputPort").asInt()));
|
||||
assertArrayEquals(bytes, payload(receive(pxhj)));
|
||||
} finally { gateway.close(); }
|
||||
}
|
||||
}
|
||||
|
||||
@Test void sendsEachDatagramOnceToTheFirstPlatformAndKeepsConcurrentReplyAddressesDistinct() throws Exception {
|
||||
CoordinatorLocator locator = mock(CoordinatorLocator.class);
|
||||
PeerClient peer = mock(PeerClient.class);
|
||||
when(locator.locate()).thenReturn("http://127.0.0.1:18100");
|
||||
try (DatagramSocket known = loopbackSocket(); DatagramSocket otherKnown = loopbackSocket();
|
||||
DatagramSocket first = loopbackSocket(); DatagramSocket second = loopbackSocket(); DatagramSocket platform = loopbackSocket();
|
||||
DatagramSocket otherTarget = loopbackSocket();
|
||||
AutoCloseableGateway managed = new AutoCloseableGateway(settings(directory), locator, peer, new ObjectMapper())) {
|
||||
int knownRelayPort = freePort();
|
||||
ObjectNode plan = routes(known.getLocalPort(), knownRelayPort, platform.getLocalPort());
|
||||
when(peer.request(anyString(), anyString(), anyString(), any())).thenReturn(plan);
|
||||
GatewayService gateway = managed.gateway;
|
||||
gateway.heartbeat();
|
||||
|
||||
ObjectNode secondRoute = ((ObjectNode) plan.path("routes").get(0)).deepCopy();
|
||||
int otherRelayPort = freePort();
|
||||
secondRoute.put("endpointId", "collector-b").put("sourcePort", otherKnown.getLocalPort())
|
||||
.put("targetPort", otherTarget.getLocalPort()).put("relayPort", otherRelayPort);
|
||||
plan.withArray("routes").add(secondRoute);
|
||||
plan.put("routeVersion", 2);
|
||||
gateway.heartbeat();
|
||||
|
||||
InetSocketAddress ingress = new InetSocketAddress(InetAddress.getLoopbackAddress(),
|
||||
gateway.status().path("inputPort").asInt());
|
||||
DatagramSocket[] senders = {known, otherKnown, first, second};
|
||||
for (int index = 0; index < senders.length; index++) {
|
||||
byte[] bytes = {(byte) index};
|
||||
senders[index].send(new DatagramPacket(bytes, bytes.length, ingress));
|
||||
}
|
||||
|
||||
DatagramPacket[] upstream = new DatagramPacket[senders.length];
|
||||
for (int index = 0; index < senders.length; index++) {
|
||||
DatagramPacket packet = receive(platform);
|
||||
assertEquals(1, packet.getLength());
|
||||
int sender = Byte.toUnsignedInt(packet.getData()[0]);
|
||||
assertTrue(sender < senders.length);
|
||||
assertNull(upstream[sender], "每个报文应只到达一次");
|
||||
upstream[sender] = packet;
|
||||
}
|
||||
assertEquals(knownRelayPort, upstream[0].getPort());
|
||||
assertEquals(otherRelayPort, upstream[1].getPort());
|
||||
assertEquals(senders.length, Arrays.stream(upstream).map(DatagramPacket::getPort).distinct().count());
|
||||
|
||||
for (int index = senders.length - 1; index >= 0; index--) {
|
||||
byte[] reply = {(byte) (10 + index)};
|
||||
platform.send(new DatagramPacket(reply, reply.length, upstream[index].getSocketAddress()));
|
||||
}
|
||||
for (int index = 0; index < senders.length; index++) {
|
||||
DatagramPacket reply = receive(senders[index]);
|
||||
assertArrayEquals(new byte[]{(byte) (10 + index)}, payload(reply));
|
||||
assertEquals(ingress.getPort(), reply.getPort());
|
||||
}
|
||||
platform.setSoTimeout(250);
|
||||
otherTarget.setSoTimeout(250);
|
||||
assertThrows(SocketTimeoutException.class, () -> receive(platform));
|
||||
assertThrows(SocketTimeoutException.class, () -> receive(otherTarget));
|
||||
}
|
||||
}
|
||||
|
||||
@Test void explicitPlatformForwardsWithoutRoutesAndTakesPrecedenceOverRouteTargets() throws Exception {
|
||||
CoordinatorLocator locator = mock(CoordinatorLocator.class);
|
||||
PeerClient peer = mock(PeerClient.class);
|
||||
when(locator.locate()).thenReturn("http://127.0.0.1:18100");
|
||||
try (DatagramSocket sender = loopbackSocket(); DatagramSocket platform = loopbackSocket();
|
||||
DatagramSocket otherTarget = loopbackSocket()) {
|
||||
Settings configured = new Settings(environment(directory)
|
||||
.withProperty("fusion.forward-target-host", "127.0.0.1")
|
||||
.withProperty("fusion.forward-target-port", Integer.toString(platform.getLocalPort())));
|
||||
try (AutoCloseableGateway managed = new AutoCloseableGateway(configured, locator, peer, new ObjectMapper())) {
|
||||
GatewayService gateway = managed.gateway;
|
||||
InetSocketAddress ingress = new InetSocketAddress(InetAddress.getLoopbackAddress(),
|
||||
gateway.status().path("inputPort").asInt());
|
||||
for (int size : new int[]{0, 54, 60000}) {
|
||||
byte[] bytes = opaqueBytes(size);
|
||||
sender.send(new DatagramPacket(bytes, bytes.length, ingress));
|
||||
assertArrayEquals(bytes, payload(receive(platform)));
|
||||
}
|
||||
|
||||
when(peer.request(anyString(), anyString(), anyString(), any())).thenReturn(
|
||||
routes(sender.getLocalPort(), freePort(), otherTarget.getLocalPort()));
|
||||
gateway.heartbeat();
|
||||
byte[] bytes = opaqueBytes(73);
|
||||
sender.send(new DatagramPacket(bytes, bytes.length, ingress));
|
||||
assertArrayEquals(bytes, payload(receive(platform)));
|
||||
otherTarget.setSoTimeout(250);
|
||||
assertThrows(SocketTimeoutException.class, () -> receive(otherTarget));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test void formerPlatformCannotSendDelayedRepliesAfterTargetChanges() throws Exception {
|
||||
CoordinatorLocator locator = mock(CoordinatorLocator.class);
|
||||
PeerClient peer = mock(PeerClient.class);
|
||||
when(locator.locate()).thenReturn("http://127.0.0.1:18100");
|
||||
try (DatagramSocket sender = loopbackSocket(); DatagramSocket former = loopbackSocket();
|
||||
DatagramSocket current = loopbackSocket();
|
||||
AutoCloseableGateway managed = new AutoCloseableGateway(settings(directory), locator, peer, new ObjectMapper())) {
|
||||
GatewayService gateway = managed.gateway;
|
||||
int relayPort = freePort();
|
||||
ObjectNode plan = routes(0, relayPort, former.getLocalPort());
|
||||
ObjectNode route = (ObjectNode) plan.path("routes").get(0);
|
||||
route.put("sourceHost", "192.0.2.1");
|
||||
when(peer.request(anyString(), anyString(), anyString(), any())).thenReturn(plan);
|
||||
gateway.heartbeat();
|
||||
InetSocketAddress ingress = new InetSocketAddress(InetAddress.getLoopbackAddress(),
|
||||
gateway.status().path("inputPort").asInt());
|
||||
byte[] data = opaqueBytes(25);
|
||||
sender.send(new DatagramPacket(data, data.length, ingress));
|
||||
DatagramPacket beforeSwitch = receive(former);
|
||||
assertArrayEquals(data, payload(beforeSwitch));
|
||||
|
||||
route.put("targetPort", current.getLocalPort());
|
||||
plan.put("routeVersion", 2);
|
||||
gateway.heartbeat();
|
||||
sender.send(new DatagramPacket(data, data.length, ingress));
|
||||
DatagramPacket afterSwitch = receive(current);
|
||||
assertArrayEquals(data, payload(afterSwitch));
|
||||
byte[] stale = opaqueBytes(13), fresh = opaqueBytes(17);
|
||||
former.send(new DatagramPacket(stale, stale.length, beforeSwitch.getSocketAddress()));
|
||||
sender.setSoTimeout(250);
|
||||
assertThrows(SocketTimeoutException.class, () -> receive(sender));
|
||||
current.send(new DatagramPacket(fresh, fresh.length, afterSwitch.getSocketAddress()));
|
||||
sender.setSoTimeout(3000);
|
||||
assertArrayEquals(fresh, payload(receive(sender)));
|
||||
}
|
||||
}
|
||||
|
||||
@Test void imageNegotiationRepliesUseTheirOwnSocketWithoutChangingLegacyReplyDestination() throws Exception {
|
||||
Settings settings = settings(directory.resolve("image-negotiation-gateway"));
|
||||
CoordinatorLocator locator = mock(CoordinatorLocator.class);
|
||||
@@ -188,10 +318,14 @@ class GatewayTest {
|
||||
}
|
||||
|
||||
private Settings settings(Path data) throws Exception {
|
||||
return new Settings(new MockEnvironment().withProperty("fusion.role", "gateway")
|
||||
return new Settings(environment(data));
|
||||
}
|
||||
|
||||
private MockEnvironment environment(Path data) {
|
||||
return new MockEnvironment().withProperty("fusion.role", "gateway")
|
||||
.withProperty("fusion.token", "unit-test-credential-not-deployed")
|
||||
.withProperty("fusion.data-dir", data.toString()).withProperty("fusion.gateway-port", "0")
|
||||
.withProperty("fusion.advertised-host", "127.0.0.1").withProperty("fusion.discovery-enabled", "false"));
|
||||
.withProperty("fusion.advertised-host", "127.0.0.1").withProperty("fusion.discovery-enabled", "false");
|
||||
}
|
||||
|
||||
private ObjectNode routes(int source, int relay, int target) {
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
package com.xtrh.input;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.google.protobuf.DynamicMessage;
|
||||
import com.xtrh.Application;
|
||||
import com.xtrh.common.config.Settings;
|
||||
import com.xtrh.communication.client.PeerClient;
|
||||
import com.xtrh.input.protocol.FusionInputProtocol;
|
||||
import io.grpc.Server;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.Timeout;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.springframework.boot.builder.SpringApplicationBuilder;
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.nio.file.Path;
|
||||
import java.util.concurrent.LinkedBlockingQueue;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import static com.xtrh.common.util.Jsons.object;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class FusionInputIntegrationTest {
|
||||
@TempDir Path directory;
|
||||
private ConfigurableApplicationContext start(String role,String name,int grpc,String coordinator){
|
||||
return new SpringApplicationBuilder(Application.class).run("--server.port=0","--server.address=127.0.0.1",
|
||||
"--fusion.role="+role,"--fusion.data-dir="+directory.resolve(name),"--fusion.node-name="+name,
|
||||
"--fusion.token=integration-only-fusion-input-credential","--fusion.capacity=1","--fusion.discovery-enabled=false",
|
||||
"--fusion.advertised-host=127.0.0.1","--fusion.coordinator-url="+coordinator,"--fusion.image-port=0",
|
||||
"--fusion.input-grpc.enabled=true","--fusion.input-grpc.port="+grpc,"--logging.level.root=WARN");
|
||||
}
|
||||
private String base(ConfigurableApplicationContext app){return "http://127.0.0.1:"+app.getBean(Settings.class).port;}
|
||||
|
||||
@Test @Timeout(60) void masterAndWorkerDeliverToTheirOwnGrpcServersAndKeepEquipmentAffinity()throws Exception{
|
||||
var a=new LinkedBlockingQueue<DynamicMessage>();var b=new LinkedBlockingQueue<DynamicMessage>();
|
||||
Server grpcA=LocalFusionInputTest.server(0,a,new AtomicBoolean());Server grpcB=LocalFusionInputTest.server(0,b,new AtomicBoolean());
|
||||
try(var master=start("coordinator","master",grpcA.getPort(),"")){
|
||||
try(var worker=start("worker","worker",grpcB.getPort(),base(master))){
|
||||
PeerClient peer=master.getBean(PeerClient.class);
|
||||
long until=System.nanoTime()+TimeUnit.SECONDS.toNanos(15);boolean online=false;
|
||||
while(System.nanoTime()<until){
|
||||
JsonNode snapshot=peer.request(base(master),"/control/snapshot","GET",null);
|
||||
if(snapshot.path("nodes").size()==2){online=true;break;}Thread.sleep(50);
|
||||
}
|
||||
assertTrue(online);
|
||||
var first=LocalFusionInputTest.input("first-data","DATA");
|
||||
var second=LocalFusionInputTest.input("second-data","DATA").put("equipmentId","equipment-B");
|
||||
assertTrue(peer.request(base(master),"/control/input","POST",first).path("accepted").asBoolean());
|
||||
assertTrue(peer.request(base(master),"/control/input","POST",second).path("accepted").asBoolean());
|
||||
DynamicMessage fromA=a.poll(5,TimeUnit.SECONDS),fromB=b.poll(5,TimeUnit.SECONDS);assertNotNull(fromA);assertNotNull(fromB);
|
||||
var mapper=new com.fasterxml.jackson.databind.ObjectMapper();
|
||||
String equipmentA=mapper.readTree(fromA.getField(FusionInputProtocol.DESCRIPTOR.findFieldByNumber(1)).toString()).path("equipmentId").asText();
|
||||
String equipmentB=mapper.readTree(fromB.getField(FusionInputProtocol.DESCRIPTOR.findFieldByNumber(1)).toString()).path("equipmentId").asText();
|
||||
assertNotEquals(equipmentA,equipmentB);
|
||||
var image=LocalFusionInputTest.input("same-equipment-image","IMAGE");
|
||||
peer.request(base(master),"/control/input","POST",image);
|
||||
var expected=equipmentA.equals("equipment-A")?a:b;var other=expected==a?b:a;
|
||||
assertNotNull(expected.poll(5,TimeUnit.SECONDS));assertNull(other.poll(100,TimeUnit.MILLISECONDS));
|
||||
int status=HttpClient.newHttpClient().send(HttpRequest.newBuilder(URI.create(base(worker)+"/node/input"))
|
||||
.POST(HttpRequest.BodyPublishers.ofString(first.toString())).header("Content-Type","application/json").build(),HttpResponse.BodyHandlers.discarding()).statusCode();
|
||||
assertEquals(401,status);
|
||||
var bindings=object().put("observedAt",System.currentTimeMillis());
|
||||
bindings.putArray("bindings").add(object().put("sourceEndpointId","source-A").put("equipmentId","equipment-A")
|
||||
.put("trialId","trial-A").put("validFrom",999)
|
||||
.put("simulationObjectId","Go2_C__23ED298C4C2EA1D896F521AC7AF643D6")
|
||||
.put("scenarioEquipmentId","dog-object").put("scenarioCacheId","scenario-cache")
|
||||
.put("scenarioId","scenario-external").put("participantCode","dog"));
|
||||
peer.request(base(master),"/control/input-bindings","POST",bindings);
|
||||
image.remove("equipmentId");image.remove("trialId");image.put("sourceTime",1001);
|
||||
image.put("simulationObjectId","untrusted-image-input");
|
||||
assertTrue(peer.request(base(master),"/control/input-image","POST",image).path("accepted").asBoolean());
|
||||
var original=expected.poll(5,TimeUnit.SECONDS);assertNotNull(original);
|
||||
var originalJson=mapper.readTree(original.getField(FusionInputProtocol.DESCRIPTOR.findFieldByNumber(1)).toString());
|
||||
assertEquals("Go2_C__23ED298C4C2EA1D896F521AC7AF643D6",originalJson.path("simulationObjectId").asText());
|
||||
assertEquals("first-data",originalJson.path("dataMessageId").asText());
|
||||
assertEquals(0,originalJson.path("data").path("values").path("position_x").asInt());
|
||||
assertEquals("LATEST_SAME_MODULE",originalJson.path("dataAssociation").asText());
|
||||
var real=LocalFusionInputTest.realModuleInput("real-data","DATA",2000).put("trialId","real-trial");
|
||||
peer.request(base(master),"/control/input","POST",real);
|
||||
assertNotNull(expected.poll(5,TimeUnit.SECONDS));
|
||||
bindings.put("observedAt",System.currentTimeMillis());
|
||||
bindings.putArray("bindings").add(object().put("sourceEndpointId","source-A").put("equipmentId","equipment-A")
|
||||
.put("trialId","real-trial").put("validFrom",1999).put("participantCode","dog")
|
||||
.put("moduleNo","0b").put("moduleType","02").put("collectionWay","EXTERNAL_MODULE"));
|
||||
peer.request(base(master),"/control/input-bindings","POST",bindings);
|
||||
image.put("sourceTime",1998);
|
||||
assertFalse(peer.request(base(master),"/control/input-image","POST",image).path("accepted").asBoolean());
|
||||
image.put("sourceTime",2001);
|
||||
assertTrue(peer.request(base(master),"/control/input-image","POST",image).path("accepted").asBoolean());
|
||||
var realImage=expected.poll(5,TimeUnit.SECONDS);assertNotNull(realImage);
|
||||
var realJson=mapper.readTree(realImage.getField(FusionInputProtocol.DESCRIPTOR.findFieldByNumber(1)).toString());
|
||||
assertEquals("real-trial",realJson.path("trialId").asText());assertEquals("0b",realJson.path("moduleNo").asText());
|
||||
assertEquals("real-data",realJson.path("dataMessageId").asText());assertFalse(realJson.has("simulationObjectId"));
|
||||
assertFalse(realJson.has("scenarioId"));assertEquals("dog",realJson.path("participantCode").asText());
|
||||
bindings.put("observedAt",System.currentTimeMillis());bindings.putArray("bindings");
|
||||
peer.request(base(master),"/control/input-bindings","POST",bindings);
|
||||
assertFalse(peer.request(base(master),"/control/input-image","POST",image).path("accepted").asBoolean());
|
||||
}
|
||||
}finally{grpcA.shutdownNow().awaitTermination(5,TimeUnit.SECONDS);grpcB.shutdownNow().awaitTermination(5,TimeUnit.SECONDS);}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.xtrh.input;
|
||||
|
||||
import com.xtrh.input.protocol.ImageUploadMetadata;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class ImageUploadMetadataTest {
|
||||
private byte[] annotated(String json){
|
||||
byte[] comment=("HD-UPLOAD: "+json).getBytes(StandardCharsets.UTF_8);
|
||||
return ByteBuffer.allocate(comment.length+8).putShort((short)0xffd8).putShort((short)0xfffe)
|
||||
.putShort((short)(comment.length+2)).put(comment).putShort((short)0xffd9).array();
|
||||
}
|
||||
@Test void parsesTodaysJpegAnnotationWithoutChangingUnsignedHexIdOrTimes(){
|
||||
byte[] jpeg=annotated("{\"mode\":\"FIXED_30\",\"frameId\":\"ffffffffffffffff\",\"time\":2000,\"sourceTime\":1000,\"reused\":true}");
|
||||
byte[] before=jpeg.clone();var metadata=ImageUploadMetadata.read(jpeg);
|
||||
assertNotNull(metadata);assertEquals("ffffffffffffffff",metadata.path("frameId").asText());
|
||||
assertEquals(2000,metadata.path("time").asLong());assertEquals(1000,metadata.path("sourceTime").asLong());
|
||||
assertTrue(metadata.path("reused").asBoolean());assertArrayEquals(before,jpeg);
|
||||
}
|
||||
@Test void badMetadataOrTruncatedCommentsDoNotCreateAPairing(){
|
||||
assertNull(ImageUploadMetadata.read(annotated("{\"mode\":\"FIXED_30\",\"frameId\":\"123\",\"time\":2000,\"reused\":true}")));
|
||||
assertNull(ImageUploadMetadata.read(new byte[]{(byte)255,(byte)216,(byte)255,(byte)254,0,50,1,2}));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
package com.xtrh.input;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import com.google.protobuf.ByteString;
|
||||
import com.google.protobuf.DynamicMessage;
|
||||
import com.google.protobuf.Empty;
|
||||
import com.xtrh.common.config.Settings;
|
||||
import com.xtrh.input.protocol.FusionInputProtocol;
|
||||
import com.xtrh.input.service.LocalFusionInput;
|
||||
import io.grpc.*;
|
||||
import io.grpc.stub.ServerCalls;
|
||||
import io.grpc.stub.StreamObserver;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.springframework.mock.env.MockEnvironment;
|
||||
import java.nio.file.Path;
|
||||
import java.net.ServerSocket;
|
||||
import java.net.InetSocketAddress;
|
||||
import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder;
|
||||
import java.util.Base64;
|
||||
import java.util.concurrent.LinkedBlockingQueue;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.function.BooleanSupplier;
|
||||
import static com.xtrh.common.util.Jsons.object;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class LocalFusionInputTest {
|
||||
@TempDir Path directory;
|
||||
private static final byte[] JPEG={(byte)255,(byte)216,8,7,6,(byte)255,(byte)217};
|
||||
public static ObjectNode input(String id,String kind){
|
||||
ObjectNode event=object().put("messageId",id).put("kind",kind).put("equipmentId","equipment-A")
|
||||
.put("equipmentCode","EQ-001").put("trialId","trial-A").put("sourceEndpointId","source-A")
|
||||
.put("sourceTime",1000).put("receivedTime",1100).put("frameId","fedcba9876543210")
|
||||
.put("simulationObjectId","Go2_C__23ED298C4C2EA1D896F521AC7AF643D6")
|
||||
.put("scenarioEquipmentId","dog-object").put("scenarioCacheId","scenario-cache")
|
||||
.put("scenarioId","scenario-external").put("participantCode","dog");
|
||||
event.putObject("upload").put("mode","FIXED_30").put("time",1050).put("reused",true).put("frameId","fedcba9876543210");
|
||||
if(kind.equals("IMAGE"))event.put("imageBase64",Base64.getEncoder().encodeToString(JPEG));
|
||||
else event.putObject("data").putObject("values").put("position_x",0).put("event_type","TEST_EVENT").put("event_time",999);
|
||||
return event;
|
||||
}
|
||||
private LocalFusionInput client(int port,int capacity,int timeout)throws Exception{
|
||||
return client("127.0.0.1",port,capacity,timeout);
|
||||
}
|
||||
private LocalFusionInput client(String host,int port,int capacity,int timeout)throws Exception{
|
||||
MockEnvironment env=new MockEnvironment().withProperty("fusion.role","worker")
|
||||
.withProperty("fusion.data-dir",directory.toString()).withProperty("fusion.token","local-grpc-test-credential-only")
|
||||
.withProperty("fusion.input-grpc.enabled","true").withProperty("fusion.input-grpc.host",host).withProperty("fusion.input-grpc.port",String.valueOf(port))
|
||||
.withProperty("fusion.input-grpc.queue-capacity",String.valueOf(capacity)).withProperty("fusion.input-grpc.timeout-ms",String.valueOf(timeout));
|
||||
return new LocalFusionInput(new Settings(env),env);
|
||||
}
|
||||
public static Server server(int port,LinkedBlockingQueue<DynamicMessage> inputs,AtomicBoolean fail)throws Exception{
|
||||
return server("127.0.0.1",port,inputs,fail);
|
||||
}
|
||||
private static Server server(String host,int port,LinkedBlockingQueue<DynamicMessage> inputs,AtomicBoolean fail)throws Exception{
|
||||
return NettyServerBuilder.forAddress(new InetSocketAddress(host,port)).addService(ServerServiceDefinition.builder(FusionInputProtocol.SERVICE)
|
||||
.addMethod(FusionInputProtocol.PUSH,ServerCalls.asyncClientStreamingCall(response->new StreamObserver<DynamicMessage>(){
|
||||
public void onNext(DynamicMessage input){inputs.add(input);}
|
||||
public void onError(Throwable error){}
|
||||
public void onCompleted(){
|
||||
if(fail.getAndSet(false)){response.onError(Status.UNAVAILABLE.asRuntimeException());return;}
|
||||
response.onNext(Empty.getDefaultInstance());response.onCompleted();
|
||||
}
|
||||
})).build()).build().start();
|
||||
}
|
||||
@Test void actualGrpcPreservesJsonPairingBinaryBytesAndNoBusinessResponse()throws Exception{
|
||||
var received=new LinkedBlockingQueue<DynamicMessage>();Server server=server(0,received,new AtomicBoolean());
|
||||
try(LocalFusionInput client=client(server.getPort(),20,3000)){
|
||||
client.accept(input("data-one","DATA"));client.accept(input("image-one","IMAGE"));client.start();
|
||||
DynamicMessage data=received.poll(5,TimeUnit.SECONDS),image=received.poll(5,TimeUnit.SECONDS);
|
||||
assertNotNull(data);assertNotNull(image);
|
||||
var mapper=new ObjectMapper();var dataJson=mapper.readTree(data.getField(FusionInputProtocol.DESCRIPTOR.findFieldByNumber(1)).toString());
|
||||
var imageJson=mapper.readTree(image.getField(FusionInputProtocol.DESCRIPTOR.findFieldByNumber(1)).toString());
|
||||
assertEquals(dataJson.path("frameId"),imageJson.path("frameId"));assertEquals("fedcba9876543210",imageJson.path("frameId").asText());
|
||||
assertEquals("equipment-A",imageJson.path("equipmentId").asText());assertTrue(imageJson.path("upload").path("reused").asBoolean());
|
||||
assertEquals("Go2_C__23ED298C4C2EA1D896F521AC7AF643D6",dataJson.path("simulationObjectId").asText());
|
||||
assertEquals(dataJson.path("simulationObjectId"),imageJson.path("simulationObjectId"));
|
||||
assertFalse(imageJson.has("imageBase64"));assertFalse(imageJson.has("imagePath"));
|
||||
assertArrayEquals(JPEG,((ByteString)image.getField(FusionInputProtocol.DESCRIPTOR.findFieldByNumber(2))).toByteArray());
|
||||
assertEquals(0,dataJson.path("data").path("values").path("position_x").asInt());
|
||||
await(()->client.status().path("rpcCompleted").asInt()==2);assertEquals(0,client.status().path("bufferedBytes").asLong());
|
||||
assertTrue(client.accept(input("image-one","IMAGE").put("receivedTime",1200)).path("duplicate").asBoolean());
|
||||
assertNull(received.poll(100,TimeUnit.MILLISECONDS));
|
||||
}finally{server.shutdownNow().awaitTermination(5,TimeUnit.SECONDS);}
|
||||
}
|
||||
@Test void grpcImageContainsConvertedFieldsForTheCurrentRealVehicleAndModuleWithoutFramePairing()throws Exception{
|
||||
var received=new LinkedBlockingQueue<DynamicMessage>();Server server=server(0,received,new AtomicBoolean());
|
||||
try(LocalFusionInput client=client(server.getPort(),20,3000)){
|
||||
var data=realModuleInput("module-data","DATA",1000);
|
||||
data.putObject("data").putObject("values").put("ct_acceleration_x",0).put("ct_battery",27);
|
||||
client.accept(data);
|
||||
var wrongModule=realModuleInput("other-module","DATA",1001).put("moduleNo","0a");
|
||||
wrongModule.putObject("data").putObject("values").put("ct_acceleration_x",999);
|
||||
client.accept(wrongModule);
|
||||
var latest=realModuleInput("latest-received-data","DATA",900);
|
||||
latest.putObject("data").putObject("values").put("ct_acceleration_x",0).put("ct_battery",27);client.accept(latest);
|
||||
var image=realModuleInput("module-image","IMAGE",326314511).put("frameId","0000000000000012");
|
||||
client.accept(image);
|
||||
var newer=realModuleInput("newer-data","DATA",1005);
|
||||
newer.putObject("data").putObject("values").put("ct_acceleration_x",2);client.accept(newer);
|
||||
assertTrue(client.accept(image.deepCopy().put("receivedTime",1300)).path("duplicate").asBoolean());
|
||||
client.start();
|
||||
com.fasterxml.jackson.databind.JsonNode sentImage=null;
|
||||
var mapper=new ObjectMapper();
|
||||
for(int i=0;i<5;i++){
|
||||
var wire=received.poll(5,TimeUnit.SECONDS);assertNotNull(wire);
|
||||
var json=mapper.readTree(wire.getField(FusionInputProtocol.DESCRIPTOR.findFieldByNumber(1)).toString());
|
||||
if(json.path("kind").asText().equals("IMAGE")){
|
||||
sentImage=json;
|
||||
assertArrayEquals(JPEG,((ByteString)wire.getField(FusionInputProtocol.DESCRIPTOR.findFieldByNumber(2))).toByteArray());
|
||||
}
|
||||
}
|
||||
assertNotNull(sentImage);assertEquals("equipment-A",sentImage.path("equipmentId").asText());
|
||||
assertEquals("trial-A",sentImage.path("trialId").asText());assertEquals("0b",sentImage.path("moduleNo").asText());
|
||||
assertFalse(sentImage.has("simulationObjectId"));
|
||||
assertEquals(0,sentImage.path("data").path("values").path("ct_acceleration_x").asInt());
|
||||
assertEquals(27,sentImage.path("data").path("values").path("ct_battery").asInt());
|
||||
assertEquals("latest-received-data",sentImage.path("dataMessageId").asText());
|
||||
assertEquals(900,sentImage.path("dataSourceTime").asLong());
|
||||
assertEquals("NODE_RECEIPT",sentImage.path("dataAssociationTimeBasis").asText());
|
||||
assertEquals("LATEST_SAME_MODULE",sentImage.path("dataAssociation").asText());
|
||||
assertEquals(1,client.status().path("imagesWithData").asInt());
|
||||
assertNull(received.poll(100,TimeUnit.MILLISECONDS));
|
||||
}finally{server.shutdownNow().awaitTermination(5,TimeUnit.SECONDS);}
|
||||
}
|
||||
public static ObjectNode realModuleInput(String id,String kind,long time){
|
||||
var event=input(id,kind).put("sourceTime",time).put("moduleNo","0b").put("moduleType","02")
|
||||
.put("collectionWay","EXTERNAL_MODULE");
|
||||
event.remove(java.util.List.of("simulationObjectId","scenarioEquipmentId","scenarioCacheId","scenarioId","upload"));
|
||||
if(kind.equals("DATA"))event.putNull("frameId");
|
||||
return event;
|
||||
}
|
||||
@Test void configuredHostReceivesBothDataAndImageOnAnotherLoopbackAddress()throws Exception{
|
||||
var received=new LinkedBlockingQueue<DynamicMessage>();
|
||||
Server receiver=server("127.0.0.2",0,received,new AtomicBoolean());
|
||||
try(LocalFusionInput client=client("127.0.0.2",receiver.getPort(),20,3000)){
|
||||
client.accept(input("remote-data","DATA"));client.accept(input("remote-image","IMAGE"));client.start();
|
||||
assertNotNull(received.poll(5,TimeUnit.SECONDS));assertNotNull(received.poll(5,TimeUnit.SECONDS));
|
||||
await(()->client.status().path("rpcCompleted").asInt()==2);
|
||||
assertEquals("127.0.0.2",client.status().path("host").asText());
|
||||
assertEquals(0,client.status().path("queued").asInt());
|
||||
}finally{receiver.shutdownNow().awaitTermination(5,TimeUnit.SECONDS);}
|
||||
assertThrows(IllegalArgumentException.class,()->client(" ",50051,20,3000));
|
||||
}
|
||||
@Test void transientRpcFailureRetainsInputsForRetry()throws Exception{
|
||||
var received=new LinkedBlockingQueue<DynamicMessage>();Server server=server(0,received,new AtomicBoolean(true));
|
||||
try(LocalFusionInput client=client(server.getPort(),20,3000)){
|
||||
client.accept(input("retry-me","DATA"));client.start();
|
||||
await(()->client.status().path("rpcCompleted").asInt()==1);
|
||||
assertTrue(client.status().path("retries").asLong()>=1);assertEquals(2,received.size());
|
||||
assertEquals(0,client.status().path("bufferedBytes").asLong());
|
||||
}finally{server.shutdownNow().awaitTermination(5,TimeUnit.SECONDS);}
|
||||
}
|
||||
@Test void fullQueueRejectsExplicitlyAndConflictingIdsCannotReplaceQueuedInput()throws Exception{
|
||||
try(LocalFusionInput client=client(50051,1,100)){
|
||||
client.accept(input("one","DATA"));assertTrue(client.accept(input("one","DATA")).path("duplicate").asBoolean());
|
||||
ObjectNode conflict=input("one","DATA");((ObjectNode)conflict.path("data")).put("extra",true);
|
||||
assertThrows(IllegalArgumentException.class,()->client.accept(conflict));
|
||||
assertThrows(IllegalStateException.class,()->client.accept(input("two","DATA")));
|
||||
assertEquals(1,client.status().path("queued").asInt());assertEquals(1,client.status().path("rejected").asInt());
|
||||
}
|
||||
}
|
||||
@Test void frameConflictsAreRejectedAndUnpairedLegacyDataRemainsUnpaired()throws Exception{
|
||||
try(LocalFusionInput client=client(50051,4,100)){
|
||||
assertThrows(IllegalArgumentException.class,()->client.accept(input("bad","IMAGE").put("frameId","0000000000000001")));
|
||||
ObjectNode legacy=input("legacy","DATA");legacy.remove("upload");legacy.putNull("frameId");
|
||||
assertFalse(LocalFusionInput.validate(legacy).path("pairingAvailable").asBoolean());client.accept(legacy);
|
||||
assertThrows(IllegalArgumentException.class,()->client.accept(input("image-no-id","IMAGE").putNull("frameId")));
|
||||
}
|
||||
}
|
||||
@Test void sameEquipmentCanPreserveSeveralTrialReferencesWithoutInventingCurrentTrial(){
|
||||
var event=input("shared-equipment","DATA");event.putNull("trialId");
|
||||
event.putArray("trialIds").add("trial-B").add("trial-A");
|
||||
var accepted=LocalFusionInput.validate(event);
|
||||
assertTrue(accepted.path("trialId").isNull());assertEquals("trial-A",accepted.path("trialIds").path(0).asText());
|
||||
assertEquals(2,accepted.path("trialIds").size());
|
||||
assertThrows(IllegalArgumentException.class,()->LocalFusionInput.validate(event.put("trialId","trial-C")));
|
||||
}
|
||||
@Test void missingSimulationObjectCannotReachGrpc(){
|
||||
var value=input("missing-object","DATA");value.remove("simulationObjectId");
|
||||
assertThrows(IllegalArgumentException.class,()->LocalFusionInput.validate(value));
|
||||
}
|
||||
@Test void realVehicleNeedsATrialParticipantButNoSimulatorObject(){
|
||||
var real=realModuleInput("real-vehicle","DATA",1000);
|
||||
assertEquals("dog",LocalFusionInput.validate(real).path("participantCode").asText());
|
||||
real.remove("participantCode");
|
||||
assertThrows(IllegalArgumentException.class,()->LocalFusionInput.validate(real));
|
||||
}
|
||||
@Test void changingTargetDrainsTheExistingQueueAndSurvivesRestart() throws Exception {
|
||||
var received = new LinkedBlockingQueue<DynamicMessage>();
|
||||
Server replacement = server(0, received, new AtomicBoolean());
|
||||
try (var unavailable = new java.net.ServerSocket(0)) {
|
||||
try (var client = client(unavailable.getLocalPort(), 20, 300)) {
|
||||
client.start();
|
||||
client.accept(input("during-change", "DATA"));
|
||||
await(() -> client.status().path("retries").asLong() > 0);
|
||||
assertThrows(IllegalArgumentException.class, () -> client.changeTarget("invalid/host", 50051));
|
||||
client.changeTarget("127.0.0.1", replacement.getPort());
|
||||
assertNotNull(received.poll(5, TimeUnit.SECONDS));
|
||||
await(() -> client.status().path("rpcCompleted").asInt() == 1);
|
||||
assertEquals(0, client.status().path("queued").asInt());
|
||||
}
|
||||
try (var reopened = client(unavailable.getLocalPort(), 20, 300)) {
|
||||
assertEquals(replacement.getPort(), reopened.status().path("port").asInt());
|
||||
reopened.start();
|
||||
reopened.accept(input("after-restart", "DATA"));
|
||||
assertNotNull(received.poll(5, TimeUnit.SECONDS));
|
||||
}
|
||||
} finally { replacement.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); }
|
||||
}
|
||||
private static void await(BooleanSupplier predicate)throws Exception{
|
||||
long until=System.nanoTime()+TimeUnit.SECONDS.toNanos(8);
|
||||
while(!predicate.getAsBoolean()&&System.nanoTime()<until)Thread.sleep(20);
|
||||
assertTrue(predicate.getAsBoolean());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.xtrh.input;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.xtrh.communication.client.PeerClient;
|
||||
import com.xtrh.discovery.service.CoordinatorLocator;
|
||||
import com.xtrh.input.service.LocalFusionInput;
|
||||
import com.xtrh.input.service.OriginalInputRelay;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import java.util.Base64;
|
||||
import java.util.concurrent.LinkedBlockingQueue;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import static com.xtrh.common.util.Jsons.object;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class OriginalInputRelayTest {
|
||||
@Test void directNodeImagesKeepTheirWireHexIdAndExactJpegBytes()throws Exception{
|
||||
var peer=mock(PeerClient.class);var locator=mock(CoordinatorLocator.class);var local=mock(LocalFusionInput.class);
|
||||
when(local.enabled()).thenReturn(true);when(locator.locate()).thenReturn("http://127.0.0.1:1");
|
||||
var messages=new LinkedBlockingQueue<JsonNode>();
|
||||
when(peer.request(anyString(),eq("/control/input-image"),eq("POST"),any())).thenAnswer(call->{messages.add(call.getArgument(3));return object().put("accepted",true);});
|
||||
try(var relay=new OriginalInputRelay(peer,locator,local)){
|
||||
byte[] jpeg={(byte)255,(byte)216,2,3,(byte)255,(byte)217};byte[] original=jpeg.clone();
|
||||
relay.received("source",-1,1000,1100,jpeg);jpeg[2]=9;relay.start();
|
||||
JsonNode received=messages.poll(3,TimeUnit.SECONDS);assertNotNull(received);
|
||||
assertEquals("ffffffffffffffff",received.path("frameId").asText());
|
||||
assertArrayEquals(original,Base64.getDecoder().decode(received.path("imageBase64").asText()));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package com.xtrh.input.service;
|
||||
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static com.xtrh.common.util.Jsons.object;
|
||||
|
||||
class RecentModuleInputTest {
|
||||
private static ObjectNode sample(String id,long time) {
|
||||
ObjectNode event=object().put("messageId",id).put("sourceTime",time).put("receivedTime",time+10)
|
||||
.put("equipmentId","vehicle-A").put("participantCode","p-A").put("sourceEndpointId","source-A")
|
||||
.put("moduleNo","0b").put("moduleType","02").put("collectionWay","EXTERNAL_MODULE");
|
||||
event.putArray("trialIds").add("trial-A");event.putObject("data").putObject("values").put("ct_acceleration_x",0);
|
||||
return event;
|
||||
}
|
||||
@Test void preventsCrossVehicleTrialEndpointModuleAndSimulationAssociations() {
|
||||
var cache=new RecentModuleInput(15000);cache.remember(sample("data",1000));
|
||||
for(String field:List.of("equipmentId","participantCode","sourceEndpointId","moduleNo","moduleType","collectionWay",
|
||||
"simulationObjectId","scenarioEquipmentId","scenarioCacheId","scenarioId")) {
|
||||
var image=sample("image",1010).put(field,"different");image.remove("data");
|
||||
assertFalse(cache.attach(image),field);assertFalse(image.has("data"));
|
||||
}
|
||||
var differentTrial=sample("image",1010);differentTrial.putArray("trialIds").add("trial-B");
|
||||
assertFalse(cache.attach(differentTrial));
|
||||
var matching=sample("image",1010);assertTrue(cache.attach(matching));
|
||||
assertEquals("data",matching.path("dataMessageId").asText());
|
||||
}
|
||||
@Test void freshReceiptsCanReuseOldSourceTimesButExpireOnTheNodeClock() {
|
||||
var now=new AtomicLong(0);var cache=new RecentModuleInput(15000,now::get);
|
||||
cache.remember(sample("initial",1000));cache.remember(sample("latest-receipt",900));
|
||||
var image=sample("different-source-clock",326314511);assertTrue(cache.attach(image));
|
||||
assertEquals("latest-receipt",image.path("dataMessageId").asText());
|
||||
assertEquals(900,image.path("dataSourceTime").asLong());
|
||||
assertEquals(910,image.path("dataReceivedTime").asLong());
|
||||
assertEquals("NODE_RECEIPT",image.path("dataAssociationTimeBasis").asText());
|
||||
assertTrue(cache.attach(sample("image-clock-behind-data",100)));
|
||||
now.set(TimeUnit.MILLISECONDS.toNanos(15001));
|
||||
assertFalse(cache.attach(sample("delayed-image",326314511)));
|
||||
assertEquals(1,cache.missCounts().path("CACHE_EXPIRED").asInt());
|
||||
}
|
||||
@Test void continuousReusedSourceTimestampsCombineEveryImageWithoutMatchingFrameIds() {
|
||||
var now=new AtomicLong(0);var cache=new RecentModuleInput(15000,now::get);
|
||||
for(int i=0;i<90;i++) {
|
||||
now.set(TimeUnit.MILLISECONDS.toNanos(i*33));
|
||||
cache.remember(sample("data-"+i,1000));
|
||||
var image=sample("image-"+i,326314511+i*33);
|
||||
assertTrue(cache.attach(image));
|
||||
assertEquals("data-"+i,image.path("dataMessageId").asText());
|
||||
assertEquals(1000,image.path("dataSourceTime").asLong());
|
||||
}
|
||||
}
|
||||
@Test void preservesNullAndZeroAndBoundsTheNumberOfCachedModules() {
|
||||
var cache=new RecentModuleInput(15000);var data=sample("original",1000);
|
||||
((ObjectNode)data.path("data").path("values")).putNull("ct_battery");cache.remember(data);
|
||||
((ObjectNode)data.path("data").path("values")).put("ct_acceleration_x",99);
|
||||
var image=sample("image",1010);assertTrue(cache.attach(image));
|
||||
assertEquals(0,image.path("data").path("values").path("ct_acceleration_x").asInt());
|
||||
assertTrue(image.path("data").path("values").path("ct_battery").isNull());
|
||||
for(int i=0;i<512;i++)cache.remember(sample("data-"+i,1000).put("moduleNo","module-"+i));
|
||||
assertFalse(cache.attach(sample("evicted",1010)));
|
||||
assertTrue(cache.attach(sample("retained",1010).put("moduleNo","module-511")));
|
||||
}
|
||||
@Test void legacyEmptyModuleIdentityStillUsesTheAuthenticatedSourceAndVehicle() {
|
||||
var cache=new RecentModuleInput(15000);
|
||||
cache.remember(sample("legacy-data",1000).put("moduleNo","").put("moduleType","").put("collectionWay",""));
|
||||
assertTrue(cache.attach(sample("image",1010).put("moduleNo","").put("moduleType","").put("collectionWay","")));
|
||||
assertFalse(cache.attach(sample("image",1010).put("moduleNo","").put("moduleType","").put("collectionWay","").put("sourceEndpointId","other")));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user