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 inputs,AtomicBoolean fail)throws Exception{ return server("127.0.0.1",port,inputs,fail); } private static Server server(String host,int port,LinkedBlockingQueue 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(){ 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();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();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(); 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();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(); 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()