新增融合输入接入并调整 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
+5 -5
View File
@@ -11,10 +11,10 @@
| 角色 | 功能 | 安装脚本默认 HTTP 端口 | | 角色 | 功能 | 安装脚本默认 HTTP 端口 |
|---|---|---:| |---|---|---:|
| `coordinator` | 总控并默认兼任执行节点,保存上下文与路由、分配任务、处理本机视频、汇总播放地址 | 18100 | | `coordinator` | 总控并默认兼任执行节点,保存上下文与路由、分配任务、处理本机视频、汇总播放地址 | 18100 |
| `gateway` | 接收采集器原始 UDP 字节,按登记来源转发,反向转送 PXHJ 的回执 | 18110 | | `gateway` | 接收任意来源的 UDP 报文,原样转发到同一平台,并将平台回复送回发送方 | 18110 |
| `worker` | 自动发现并注册到总控,领取多个任务,接收原图或生成演示视频 | 18120 | | `worker` | 自动发现并注册到总控,领取多个任务,接收原图或生成演示视频 | 18120 |
采集网关的默认 UDP 入口是 `19002`。PXHJ 的现有采集入口 `19001` 保留;同机部署时两个接收端口必须不同。每个采集器使用一个固定 UDP 转发源端口,PXHJ 中对应采集器的可信来源也必须同步更新。 采集网关的默认 UDP 入口是 `19002`。在网关配置中填写 `fusion.forward-target-host` 即可指定平台地址,`fusion.forward-target-port` 默认是 `19001`。已有部署也可沿用总控最后确认的第一条路由的目标地址和端口。网关状态中的 `forwardTargetHost` 和 `forwardTargetPort` 显示实际目标。
总控的控制与执行在**同一个 Java 进程、同一个 18100 端口、同一个稳定身份**中运行,不需要再为主电脑启动额外 worker 进程。主节点默认容量 2 路,普通子节点仍可部署在其他电脑。总控快照用 `nodeRole=COORDINATOR` 标识主节点、`WORKER` 标识子节点,PXHJ 可统一配置两种节点的路数。 总控的控制与执行在**同一个 Java 进程、同一个 18100 端口、同一个稳定身份**中运行,不需要再为主电脑启动额外 worker 进程。主节点默认容量 2 路,普通子节点仍可部署在其他电脑。总控快照用 `nodeRole=COORDINATOR` 标识主节点、`WORKER` 标识子节点,PXHJ 可统一配置两种节点的路数。
@@ -29,12 +29,12 @@
- 总控使用 H2 持久化。总控重启后提高调度代次、撤销旧许可,等待 PXHJ 重新确认上下文。 - 总控使用 H2 持久化。总控重启后提高调度代次、撤销旧许可,等待 PXHJ 重新确认上下文。
- 节点心跳失联后任务许可到期;页面不会永久保留失效播放地址。 - 节点心跳失联后任务许可到期;页面不会永久保留失效播放地址。
- 内部 HTTP 请求和响应使用共享凭证生成 HMAC 签名,含时间和一次性随机数校验;发现到的候选地址不会收到明文凭证。 - 内部 HTTP 请求和响应使用共享凭证生成 HMAC 签名,含时间和一次性随机数校验;发现到的候选地址不会收到明文凭证。
- UDP 原始字节不改变,不依赖报文文本或自造标记。未知/歧义来源丢弃,队列和内存有上限。 - 所有来源的 UDP 报文均原样向同一目标转发一份。唯一匹配登记信息的采集器使用既有固定出口,其他发送方按实际 IP 和源端口使用独立临时出口,平台可向该出口回复。PXHJ 按自身的采集器配置和协议校验处理收到的数据。
- 网关保存最后确认的路由;总控暂时失联或网关重启后继续按这些路由转发。 - 网关保存最后确认的路由;总控暂时失联或网关重启后继续按这些路由转发。
- 原图接入在试验准备时就可建立,不依赖正式轮次开始;采集器通过网关协商后直接上传接收节点。 - 原图接入在试验准备时就可建立,不依赖正式轮次开始;采集器通过网关协商后直接上传接收节点。
- 原图迁移先发布新旧两个目标,等新节点收到完整首帧才切换 PXHJ 取图;许可到期回退原图片上传地址。 - 原图迁移先发布新旧两个目标,等新节点收到完整首帧才切换 PXHJ 取图;许可到期回退原图片上传地址。
当前调度依据 PXHJ 配置的容量和节点在线状态,不会测量 CPU/GPU 负载后自动修改容量。网关现阶段按采集器来源转发不透明字节,正式协议解析仍由 PXHJ 完成;网关内的数据解析、装备状态标准化、订阅分发和独立图片分片组装尚未实现。 当前调度依据 PXHJ 配置的容量和节点在线状态,不会测量 CPU/GPU 负载后自动修改容量。网关转发原始字节,正式协议解析仍由 PXHJ 完成;网关内的数据解析、装备状态标准化、订阅分发和独立图片分片组装尚未实现。
图片由执行节点认证和组装,网关只转发协商。接入流程、配置和边界见 [图片直传协商与准备取图](docs/图片直传协商与准备取图.md)。原图接入与演示任务各计一路;新部署的协商开关默认关闭。本次已按授权为 RK3588 开启协商,实际部署与联调见 [开发板记录](docs/开发板图片协商联调记录.md)。 图片由执行节点认证和组装,网关只转发协商。接入流程、配置和边界见 [图片直传协商与准备取图](docs/图片直传协商与准备取图.md)。原图接入与演示任务各计一路;新部署的协商开关默认关闭。本次已按授权为 RK3588 开启协商,实际部署与联调见 [开发板记录](docs/开发板图片协商联调记录.md)。
@@ -69,7 +69,7 @@ PXHJ 的新增业务同样采用 `fusion.controller`、`fusion.service`、`fusio
产物为 `target/xtrh-services-1.0.0.jar`。脚本先执行测试,测试失败不会返回成功。 产物为 `target/xtrh-services-1.0.0.jar`。脚本先执行测试,测试失败不会返回成功。
`CoordinatorTest` 验证容量预留、超额等待、迁移准备和正式切换、容量不足保留输出、会话/版本隔离、轮次结束、离线租约及总控重启后的上下文确认。`GatewayTest` 使用真实 UDP 套接字验证二进制字节保持、固定转发源端口、反向回复、未知来源拒绝、总控失联及路由恢复。`ServiceSecurityTest` 和 `PeerClientTest` 验证请求篡改、重放、过期请求、伪造响应及凭证不出现在 HTTP 头中。这些是本机自动化验证,不能替代多台物理电脑、真实采集器与网络环境验收。 `CoordinatorTest` 验证容量预留、超额等待、迁移准备和正式切换、容量不足保留输出、会话/版本隔离、轮次结束、离线租约及总控重启后的上下文确认。`GatewayTest` 使用真实 UDP 套接字验证任意来源的单目标转发、原始字节、已登记采集器的固定出口、多来源回包、总控失联和路由恢复。`ServiceSecurityTest` 和 `PeerClientTest` 验证请求篡改、重放、过期请求、伪造响应及凭证不出现在 HTTP 头中。这些是本机自动化验证,不能替代多台物理电脑、真实采集器与网络环境验收。
增加主节点执行能力后,XTRH 全部 **24 项测试通过**:原有 19 项,加 4 项角色能力条件与 1 项随机端口主进程执行集成测试。后者真实读取主端口 JPEG,检查自动注册、唯一主身份、任务就绪及结束撤销。上一阶段 PXHJ 融合后端 17 项和 1 项真实业务串联测试通过;业务串联使用真实 Spring 业务服务、正式接口层登录会话和 CSRF、隔离 H2,连接实际总控和两个子节点,验证保存绑定、动态迁移和正式轮次操作。真实 UDP 加密数据、心跳认证及中转配置回程也有针对性测试。详细范围见 [本机验证记录](docs/本机验证记录.md)。 增加主节点执行能力后,XTRH 全部 **24 项测试通过**:原有 19 项,加 4 项角色能力条件与 1 项随机端口主进程执行集成测试。后者真实读取主端口 JPEG,检查自动注册、唯一主身份、任务就绪及结束撤销。上一阶段 PXHJ 融合后端 17 项和 1 项真实业务串联测试通过;业务串联使用真实 Spring 业务服务、正式接口层登录会话和 CSRF、隔离 H2,连接实际总控和两个子节点,验证保存绑定、动态迁移和正式轮次操作。真实 UDP 加密数据、心跳认证及中转配置回程也有针对性测试。详细范围见 [本机验证记录](docs/本机验证记录.md)。
+5
View File
@@ -11,3 +11,8 @@ fusion.discovery-enabled=true
# fusion.advertised-host=192.168.10.21 # fusion.advertised-host=192.168.10.21
# 同网段默认自动发现总控;跨网段可由统一部署配置预置域名。 # 同网段默认自动发现总控;跨网段可由统一部署配置预置域名。
# fusion.coordinator-url=http://fusion-control.example.internal:18100 # fusion.coordinator-url=http://fusion-control.example.internal:18100
# gRPC 融合输入;host 可填写接收程序所在电脑的局域网 IP 或主机名。
fusion.input-grpc.enabled=false
fusion.input-grpc.host=127.0.0.1
fusion.input-grpc.port=50051
+110
View File
@@ -0,0 +1,110 @@
# 融合输入 gRPC 接口
本接口用于试验记录、仿真和展示的数据交接。系统融合软件负责装备归属、分发和输入交付;外部进程负责自身处理。本次不接收融合结果,不实现图片删除回调。
## 接口约定
协议文件:`src/main/proto/fusion_input.proto`。
- 服务:`xtrh.fusion.v1.FusionInputService`
- 方法:`Push(stream FusionInput) returns (google.protobuf.Empty)`
- 每台执行节点连接配置的 `fusion.input-grpc.host:<port>`,默认地址为 `127.0.0.1:50051`,也可指定局域网接收程序地址。
- `equipmentId`、`equipmentCode`、`participantCode` 和 `trialId/trialIds` 从当前有效试验的模块及车辆绑定中解析,优先正在运行的试验。真实车辆不要求配置仿真对象;存在完整仿真绑定时,另保留 `simulationObjectId`、`scenarioId`、`scenarioCacheId`、`scenarioEquipmentId`。多个候选绑定的车辆、参与方或仿真上下文有冲突时不发送。
- `FusionInput.json` 为 UTF-8 JSON 文本;`FusionInput.image` 为原始 JPEG 二进制。DATA 消息的 image 为空。
- 为兼顾实时发送、流量上限和失败重试,客户端复用 Channel,发送一个或多个消息后结束当前短流,不等待凑满批次。最多每批 32 条,总大小约 4 MiB;单张图片上限 2 MiB。
- 服务端在读完本批后返回一个 Empty 和 OK 状态。它只表示本批 RPC 接收成功,不表示融合已经完成。客户端不读取算法输出。
- 失败会重试当前批次,接收方须按 `messageId` 去重;不承诺跨进程重启、跨节点迁移的“恰好一次”。
数据 JSON 示例:
```json
{
"schemaVersion": 1,
"kind": "DATA",
"messageId": "data/packet-001/trial-001",
"trialId": "trial-001",
"equipmentId": "equipment-001",
"equipmentCode": "EQ-001",
"participantCode": "vehicle-slot-001",
"sourceEndpointId": "collector-connection-001",
"collectionWay": "CONTROL_TERMINAL",
"moduleNo": "04",
"moduleType": "04",
"packetId": "packet-001",
"frameId": "fedcba9876543210",
"sourceTime": 1793934000000,
"receivedTime": 1793934000050,
"upload": {
"mode": "FIXED_30",
"time": 1793934000033,
"reused": false,
"frameId": "fedcba9876543210"
},
"data": { "values": { "example_position": 0, "example_attitude": 0 } }
}
```
IMAGE 消息携带相同的装备与来源标识、`frameId`、采样/上传时间,另有 `imageContentType=image/jpeg` 和 `imageBytes`;图片正文位于同一条 protobuf 的 image 字段中。存在当前试验、同一车辆、同一来源及同一模块的新鲜采集数据时,图片 JSON 同时包含 `data`,其中 `data.values` 为已转换的采集参数字段。示例中的参数名仅用于展示,实际字段由平台采集参数目录决定。
固定外加模块按已登记的 `moduleNo` 查询模块类型,再把已解码值转换为启用的采集参数代码(如 `ct_*`、`fixed_wq_*`、`wqz_*`)。gRPC 与操控终端共用 `data.values` 格式,仅包含目录中对应类型的字段。原始模块数据继续保存在平台采集记录,不加入 gRPC 的 data 层。XTRH 不按设备编号硬编码字段,不重新解释单位或补造事件。
## 关联与时间
沿用 2026-11-06 采集改动:`upload.frameId` 是 16 位小写十六进制字符串,和 JPG1 分片头、JPEG 的 `HD-UPLOAD: ` 注释保持一致。转发 JSON 同时提供顶层 frameId,保留 upload 原对象中的模式、时间和 reused 标记,不重新生成帧号,也不转成十进制。
图片 JSON 的字段组合不依赖 `frameId`。执行节点按 `(equipmentId, trialIds, participantCode, sourceEndpointId, moduleNo, moduleType, collectionWay)` 及可选仿真上下文精确隔离,取执行节点当前最近收到的一份 DATA。缓存上限为 512 个绑定及 4 MiB;使用执行节点单调时钟控制 15 秒接收新鲜度,不比较图片和数据的源时间。设备可能复用旧采样时间,也可能使用不同源时钟;这些源时间以及原始接收时间均原样保留,不能据此宣称采样同步。该窗口可用 `fusion.input-grpc.image-data-max-age-ms` 调整。
合并后的 IMAGE JSON 增加 `data`、`dataSourceTime`、`dataReceivedTime`、`dataMessageId` 、`dataAssociation="LATEST_SAME_MODULE"` 和 `dataAssociationTimeBasis="NODE_RECEIPT"`,表示最新同模块字段快照,不声称逐帧配对。没有匹配数据、数据超时、图片先到或合并元数据超限时,图片仍发送但没有这些数据字段。重新发送同一 `messageId` 不会替换首次入队时的数据快照。
原有 `frameId`、`sourceTime`、`receivedTime` 和 `upload.time` 仍保留协议语义;`pairingAvailable` 只描述帧号是否存在。重复使用旧采样值时保留 `upload.reused=true`;图片原始采样时间如已提供,保留在 `upload.sourceTime`。
归属以装备唯一为准,优先使用正在运行的试验绑定。同一模块被多个有效试验引用、且都指向同一装备时只转发一份,并在 `trialIds` 中保留全部关联试验;只有一个时同时提供 `trialId`,多个时 `trialId` 为 null,不臆造当前试验。多个候选装备仍视为歧义,不转发。执行节点的输入路由按装备保持一致。
原有 SOURCE 模式或旧设备没有 upload.frameId 时,DATA 的 frameId 为 null、pairingAvailable 为 false,仍发送真实数据。pairingAvailable 只表示存在关联标识,不表示另一条消息已经到达。没有装备绑定或存在歧义时不转发,状态计数会记录 unbound。
## 分发与内存
高清视频平台从已认证、已保存的数据接收入口发布逐条事件;事务回滚的数据不发布,不使用页面每两秒刷新的最新值代替事件流。
平台沿用签名 HTTP 通道把事件交给系统融合总控。总控按试验/装备选择有效执行节点,优先沿用该装备的活动任务;没有视频任务的数据装备也可分配给启用输入能力的节点。同一装备的数据和图像走同一节点,该节点最后调用配置的 gRPC 接收端。跨节点的内部 HTTP 图片正文采用有界 Base64;最终 gRPC 使用独立 bytes 字段。
图片直接到系统融合节点时,节点在完成认证、组装和 JPEG 校验后发布,使用平台同步的唯一装备绑定;绑定过期、撤销或图片早于新绑定时不猜归属。准备阶段可以接收图片,但未绑定到装备的图片仅供原有预览。
接收队列和预览缓存分别管理。gRPC 的发送队列在收到本批 RPC 成功状态后释放引用,外部进程管理自己的图片内存;算法释放内存不会删除页面预览。平台启用输入转发时,实时图片预览默认使用有界内存缓存,既有 HTTP 图片接口保持不变。系统融合节点继续保留现有近期帧缓存。
每个队列有 64 MiB 总预算和条数限制,满时报告拒绝/丢弃计数,原采集流程继续运行。重试期间数据保留在内存;本次没有持久化发件箱,进程退出或长时间拥塞可能造成未交付输入丢失。不能将 sent/rpcCompleted 解释为“算法已用完图片”。
## 启用配置
外部融合进程按 proto 实现接收端;同机部署时监听本机地址,跨机部署时监听接收电脑的局域网地址并开放对应端口。以下开关默认关闭,修改源代码不会自动启用或部署。
每台系统融合主/从执行节点:
```properties
fusion.input-grpc.enabled=true
fusion.input-grpc.host=127.0.0.1
fusion.input-grpc.port=50051
fusion.input-grpc.timeout-ms=3000
fusion.input-grpc.queue-capacity=2048
fusion.input-grpc.max-buffer-bytes=67108864
fusion.input-grpc.image-data-max-age-ms=15000
```
高清视频平台:
```properties
app.fusion.input-enabled=true
app.image-udp.memory-only=true
```
沿用已有 `app.fusion.enabled`、总控地址及服务签名配置,不在本文件填写凭证。平台的 `memory-only` 缺省值随 input-enabled 开关;如需继续使用原本地预览文件,可明确配置 false,gRPC 仍直接传二进制。缓存不保证重启后还能查看旧帧,本次不清理以前留在磁盘上的文件。
例如接收程序部署在 `192.168.2.3:50051` 时,将执行节点的 `fusion.input-grpc.host` 设置为 `192.168.2.3`、端口设置为 `50051`,重启执行节点后生效。每个执行节点可以独立指定目标地址;当前连接采用明文 gRPC,用于可达的内部网络。
## 状态与验证
- 平台:`GET /api/field/fusion/input-status`,沿用登录与采集读取权限,只允许全量数据范围账号查看全局计数。
- 执行节点:`GET /node/input/status`,沿用服务签名认证,包含目标主机、端口、排队、缓冲字节、RPC 完成、重试、拒绝及直传图片计数;`imagesWithData` / `imagesWithoutData` 分别记录附带和未附带字段的图片条数,`imageDataMaxAgeMs` 为数据接收新鲜度窗口,`imageDataTimeBasis=NODE_RECEIPT`。`imageDataMissReasons` 记录未合并原因:`NO_SAME_MODULE_DATA`(无同身份缓存)、`CACHE_EXPIRED`(缓存过期)及 `METADATA_TOO_LARGE`(合并后元数据超限),不含业务正文。
- 这些状态不返回图像、业务数据、凭证或算法结果。
自动化测试包括实际 gRPC 二进制接收、固定帧号和 upload 元数据保持、错误后重试、队列满拒绝、两个执行节点各自调用本机接收端、装备分发、服务签名保护,以及平台逐条发布、事务回滚、装备绑定歧义、内存预览独立生命周期。隔离测试接收器不代表已与实际算法进程联调,也不代表真实多机或持续 30 fps 容量验收。
+4 -1
View File
@@ -2,8 +2,11 @@
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>3.5.11</version><relativePath/></parent> <parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>3.5.11</version><relativePath/></parent>
<groupId>com.xtrh</groupId><artifactId>xtrh-services</artifactId><version>1.0.0</version> <groupId>com.xtrh</groupId><artifactId>xtrh-services</artifactId><version>1.0.0</version>
<properties><java.version>17</java.version></properties> <properties><java.version>17</java.version><grpc.version>1.77.0</grpc.version></properties>
<dependencies> <dependencies>
<dependency><groupId>io.grpc</groupId><artifactId>grpc-netty-shaded</artifactId><version>${grpc.version}</version></dependency>
<dependency><groupId>io.grpc</groupId><artifactId>grpc-protobuf</artifactId><version>${grpc.version}</version></dependency>
<dependency><groupId>io.grpc</groupId><artifactId>grpc-stub</artifactId><version>${grpc.version}</version></dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency> <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency>
<dependency><groupId>com.h2database</groupId><artifactId>h2</artifactId><scope>runtime</scope></dependency> <dependency><groupId>com.h2database</groupId><artifactId>h2</artifactId><scope>runtime</scope></dependency>
<dependency><groupId>org.jmdns</groupId><artifactId>jmdns</artifactId><version>3.5.12</version></dependency> <dependency><groupId>org.jmdns</groupId><artifactId>jmdns</artifactId><version>3.5.12</version></dependency>
@@ -21,6 +21,7 @@ public class Settings {
public final String role, cluster, token, id, bootId, name, coordinator, advertisedHost, bindHost; public final String role, cluster, token, id, bootId, name, coordinator, advertisedHost, bindHost;
public final Path directory; public final Path directory;
public final int capacity, gatewayPort, targetPort; public final int capacity, gatewayPort, targetPort;
public final String forwardTargetHost;
// HTTP 就绪事件发布实际端口,随机端口部署不能继续上报配置中的 0。 // HTTP 就绪事件发布实际端口,随机端口部署不能继续上报配置中的 0。
public volatile int port; public volatile int port;
private volatile boolean serverReady; private volatile boolean serverReady;
@@ -68,6 +69,7 @@ public class Settings {
// HTTP 管理、网关 UDP 接入和 PXHJ 接收端口各自配置,不能混为同一入口。 // HTTP 管理、网关 UDP 接入和 PXHJ 接收端口各自配置,不能混为同一入口。
port = env.getProperty("server.port", Integer.class, 18100); port = env.getProperty("server.port", Integer.class, 18100);
gatewayPort = env.getProperty("fusion.gateway-port", Integer.class, 19002); 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); targetPort = env.getProperty("fusion.forward-target-port", Integer.class, 19001);
// 授权有效期交给业务服务用单调时钟计时;这里仅校验部署值范围。 // 授权有效期交给业务服务用单调时钟计时;这里仅校验部署值范围。
@@ -82,10 +82,13 @@ public class ServiceSecurity extends OncePerRequestFilter {
return; 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 requestPath = path + (req.getQueryString() == null ? "" : "?" + req.getQueryString());
String expected = Signatures.request(settings.token, req.getMethod(), requestPath, time, nonce, body); 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) { || nonces.putIfAbsent(nonce, timestamp) != null) {
reject(res, "Invalid service signature"); reject(res, "Invalid service signature");
return; return;
@@ -35,6 +35,40 @@ public class CoordinatorService {
private final ImageSourceRegistry imageSources = new ImageSourceRegistry(); private final ImageSourceRegistry imageSources = new ImageSourceRegistry();
// 保存失败后停止继续派发,避免内存中的新授权与磁盘中的旧状态发生分歧。 // 保存失败后停止继续派发,避免内存中的新授权与磁盘中的旧状态发生分歧。
private boolean storageHealthy = true; 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 @org.springframework.beans.factory.annotation.Autowired
public CoordinatorService(Settings settings, ObjectMapper mapper) throws Exception { public CoordinatorService(Settings settings, ObjectMapper mapper) throws Exception {
@@ -113,6 +147,7 @@ public class CoordinatorService {
String imageHost=input.path("imageHost").asText(""); String imageHost=input.path("imageHost").asText("");
require(imagePort==0||(imagePort>0&&imagePort<=65535&&ImageSourceRegistry.ipv4(imageHost)),"Invalid node image input"); require(imagePort==0||(imagePort>0&&imagePort<=65535&&ImageSourceRegistry.ipv4(imageHost)),"Invalid node image input");
n.put("imageInputPort",imagePort).put("imageHost",imageHost); 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(); 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); 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"); String revision=input.path("configurationVersion").asText("0");
var c=map("contexts").has(trialId)?(ObjectNode)map("contexts").get(trialId):object(); var c=map("contexts").has(trialId)?(ObjectNode)map("contexts").get(trialId):object();
boolean enabled=input.path("enabled").asBoolean(true); 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) 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()); .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); 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.DatagramSocket;
import java.net.InetAddress; import java.net.InetAddress;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.SocketTimeoutException; import java.net.SocketTimeoutException;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.util.ArrayList; import java.util.ArrayList;
@@ -47,9 +48,8 @@ public class GatewayService {
// 字节限额与报文数限额配合,大报文不能绕过队列长度限制。 // 字节限额与报文数限额配合,大报文不能绕过队列长度限制。
private static final long MAX_BUFFERED_BYTES = 16L * 1024 * 1024; private static final long MAX_BUFFERED_BYTES = 16L * 1024 * 1024;
// 收包时保留来源及匹配的路由,发送线程无需重复猜测采集器身份。 private record Routes(List<Relay> registered, InetSocketAddress target) {}
// 字节数组专属这一报文,与接收循环复用的缓冲区不共享。 private record Packet(byte[] bytes, InetSocketAddress source, InetSocketAddress target, Relay relay) {}
private record Packet(byte[] bytes, InetSocketAddress source, Relay relay) {}
private final Settings settings; private final Settings settings;
private final CoordinatorLocator locator; private final CoordinatorLocator locator;
@@ -57,16 +57,18 @@ public class GatewayService {
// 路由持久化经 DAO 完成;业务服务不包含表结构或 SQL 语句。 // 路由持久化经 DAO 完成;业务服务不包含表结构或 SQL 语句。
private final StateStore store; private final StateStore store;
private final DatagramSocket ingress; private final DatagramSocket ingress;
private final InetSocketAddress configuredTarget;
private final UdpForwardSessions sessions;
// 上行接收与发送解耦,避免目标发送迟缓阻塞所有采集器的接收。 // 上行接收与发送解耦,避免目标发送迟缓阻塞所有采集器的接收。
private final ArrayBlockingQueue<Packet> queue = new ArrayBlockingQueue<>(2048); private final ArrayBlockingQueue<Packet> queue = new ArrayBlockingQueue<>(2048);
// 计数描述本次进程运行,重启恢复的是路由,而不是历史报文统计。 // 计数描述本次进程运行,重启恢复的是路由,而不是历史报文统计。
// 原子计数可同时由上行线程和各采集器回传线程更新。 // 原子计数可同时由上行线程和各采集器回传线程更新。
// 未登记、队列丢弃和发送错误分别计数,PXHJ 可区分数据缺失原因。 // 缺少转发目标、队列丢弃和发送错误分别计数。
private final AtomicLong received = new AtomicLong(), forwarded = new AtomicLong(); 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 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 boolean closed;
private volatile long routeVersion = -1; private volatile long routeVersion = -1;
private volatile JsonNode appliedRoutes = array(); private volatile JsonNode appliedRoutes = array();
@@ -89,11 +91,29 @@ public class GatewayService {
ingress = new DatagramSocket(null); ingress = new DatagramSocket(null);
// 增大内核收包缓冲区以应对短时突发,实际可用大小仍由操作系统决定。 // 增大内核收包缓冲区以应对短时突发,实际可用大小仍由操作系统决定。
// 内核缓冲区和业务队列是两层容量,业务队列满时会显式累计丢弃数。 // 内核缓冲区和业务队列是两层容量,业务队列满时会显式累计丢弃数。
ingress.setReceiveBufferSize(4 * 1024 * 1024); try {
ingress.bind(new InetSocketAddress(settings.gatewayPort)); ingress.setReceiveBufferSize(4 * 1024 * 1024);
ObjectNode saved = store.load(); ingress.bind(new InetSocketAddress(settings.gatewayPort));
if (saved.path("routes").isArray()) { sessions = new UdpForwardSessions(ingress, errors);
apply(saved.path("routes"), saved.path("routeVersion").asLong(), false); } 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-receive", this::receive);
daemon("xtrh-udp-forward", this::forward); daemon("xtrh-udp-forward", this::forward);
@@ -121,7 +141,7 @@ public class GatewayService {
} }
/** /**
* 仅接收唯一匹配的登记来源;未登记和歧义来源统一丢弃并计数。 * 接收任意来源的报文,将每个报文发往同一个平台地址一次。
* 接收缓冲区循环复用,入队前复制有效字节,防止下一报文覆盖旧内容。 * 接收缓冲区循环复用,入队前复制有效字节,防止下一报文覆盖旧内容。
* 队列同时限制报文数和累计字节数,避免高频或大报文耗尽内存。 * 队列同时限制报文数和累计字节数,避免高频或大报文耗尽内存。
*/ */
@@ -133,15 +153,16 @@ public class GatewayService {
ingress.receive(packet); ingress.receive(packet);
received.incrementAndGet(); received.incrementAndGet();
InetSocketAddress source = (InetSocketAddress) packet.getSocketAddress(); InetSocketAddress source = (InetSocketAddress) packet.getSocketAddress();
Relay match = matchSource(source); Routes routes = active;
if (match == null) { if (routes.target == null) {
unknown.incrementAndGet(); noTarget.incrementAndGet();
continue; continue;
} }
Relay match = registeredRelay(routes.registered, source);
// 不改原始密文、报文长度和采样时间,PXHJ 继续按既有协议解析。 // 不改原始密文、报文长度和采样时间,PXHJ 继续按既有协议解析。
byte[] bytes = Arrays.copyOf(buffer, packet.getLength()); byte[] bytes = Arrays.copyOf(buffer, packet.getLength());
long reserved = buffered.addAndGet(bytes.length); 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); buffered.addAndGet(-bytes.length);
overflow.incrementAndGet(); overflow.incrementAndGet();
} }
@@ -153,10 +174,8 @@ public class GatewayService {
} }
} }
// 同一来源若匹配多条路由就拒绝转发,防止把数据归入错误采集器。 // 登记信息仅用于选择原有固定出口。其余来源使用独立会话。
private Relay matchSource(InetSocketAddress source) { private Relay registeredRelay(List<Relay> relays, InetSocketAddress source) {
// 匹配依据来源 IP 与登记端口,内容中的模块编号仍交给 PXHJ 校验。
// 动态源端口由各 Relay 的 sourcePort=0 明确允许,不放宽来源 IP。
Relay match = null; Relay match = null;
for (Relay relay : relays) { for (Relay relay : relays) {
if (relay.matches(source)) { if (relay.matches(source)) {
@@ -184,7 +203,11 @@ public class GatewayService {
continue; continue;
} }
try { 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(); forwarded.incrementAndGet();
} catch (Exception failure) { } catch (Exception failure) {
errors.incrementAndGet(); 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,再发布新的列表快照。
* 相同采集器及相同转发端口复用 socket,保留回传线程与端口身份。 * 相同采集器及相同转发端口复用 socket,保留回传线程与端口身份。
* 准备失败时关闭本次新开的端口,不关闭仍在服务的旧路由。 * 准备失败时关闭本次新开的端口,不关闭仍在服务的旧路由。
*/ */
private synchronized void apply(JsonNode routes, long version, boolean save) throws Exception { 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<>(); Map<String, Relay> existing = new HashMap<>();
for (Relay relay : relays) { for (Relay relay : active.registered) {
existing.put(relay.id, relay); existing.put(relay.id, relay);
} }
List<Relay> next = new ArrayList<>(), opened = new ArrayList<>(); List<Relay> next = new ArrayList<>(), opened = new ArrayList<>();
@@ -218,13 +256,12 @@ public class GatewayService {
String id = required(route, "endpointId"); String id = required(route, "endpointId");
ObjectNode config = (ObjectNode) route.deepCopy(); ObjectNode config = (ObjectNode) route.deepCopy();
InetAddress.getByName(required(route, "sourceHost")); InetAddress.getByName(required(route, "sourceHost"));
InetAddress.getByName(required(route, "targetHost"));
Relay old = existing.get(id); Relay old = existing.get(id);
if (old != null && old.route.path("relayPort").asInt() == route.path("relayPort").asInt()) { if (old != null && old.route.path("relayPort").asInt() == route.path("relayPort").asInt()) {
next.add(old); next.add(old);
updates.put(old, config); updates.put(old, config);
} else { } else {
Relay fresh = new Relay(config); Relay fresh = new Relay(config, target);
opened.add(fresh); opened.add(fresh);
next.add(fresh); next.add(fresh);
} }
@@ -236,11 +273,12 @@ public class GatewayService {
store.save(snapshot); store.save(snapshot);
} }
for (Map.Entry<Relay, ObjectNode> entry : updates.entrySet()) { 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。 // 旧列表不再修改;新列表发布后才关闭已撤销的旧 socket。
relays = List.copyOf(next); sessions.setTarget(target);
active = new Routes(List.copyOf(next), target);
routeVersion = version; routeVersion = version;
appliedRoutes = routes.deepCopy(); appliedRoutes = routes.deepCopy();
routeState = "APPLIED"; routeState = "APPLIED";
@@ -292,13 +330,18 @@ public class GatewayService {
// 控制层读取统计快照,不接触 socket、队列或可变路由对象。 // 控制层读取统计快照,不接触 socket、队列或可变路由对象。
public ObjectNode status() { public ObjectNode status() {
Routes routes = active;
ObjectNode result = object().put("connection", connection).put("routeState", routeState) ObjectNode result = object().put("connection", connection).put("routeState", routeState)
.put("routeVersion", routeVersion).put("inputPort", ingress.getLocalPort()) .put("routeVersion", routeVersion).put("inputPort", ingress.getLocalPort())
.put("received", received.get()).put("forwarded", forwarded.get()) .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()); .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"); ArrayNode entries = result.putArray("routeStatus");
for (Relay relay : relays) { for (Relay relay : routes.registered) {
entries.add(relay.status()); entries.add(relay.status());
} }
return result; return result;
@@ -306,10 +349,11 @@ public class GatewayService {
// 先关闭 socket 唤醒阻塞接收,再关闭持久化连接。 // 先关闭 socket 唤醒阻塞接收,再关闭持久化连接。
@PreDestroy @PreDestroy
public void close() throws Exception { public synchronized void close() throws Exception {
closed = true; closed = true;
ingress.close(); ingress.close();
for (Relay relay : relays) { sessions.close();
for (Relay relay : active.registered) {
relay.close(); relay.close();
} }
store.close(); store.close();
@@ -331,14 +375,14 @@ public class GatewayService {
private volatile InetSocketAddress lastNegotiationSource; private volatile InetSocketAddress lastNegotiationSource;
private final AtomicLong sent = new AtomicLong(), replies = new AtomicLong(); 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(); id = config.path("endpointId").asText();
socket = new DatagramSocket(null); socket = new DatagramSocket(null);
try { try {
// 专属转发端口是 PXHJ 识别原采集器的映射,不随视频任务迁移。 // 专属转发端口是 PXHJ 识别原采集器的映射,不随视频任务迁移。
socket.bind(new InetSocketAddress(config.path("relayPort").asInt())); socket.bind(new InetSocketAddress(config.path("relayPort").asInt()));
socket.setSoTimeout(1000); socket.setSoTimeout(1000);
update(config); update(config, target);
daemon("xtrh-relay-" + id, this::reply); daemon("xtrh-relay-" + id, this::reply);
} catch (Exception failure) { } catch (Exception failure) {
socket.close(); socket.close();
@@ -351,16 +395,18 @@ public class GatewayService {
* 来源配置变化时清空最近设备地址,避免回执发到旧采集器。 * 来源配置变化时清空最近设备地址,避免回执发到旧采集器。
* 更新和发送共用对象锁,避免发送期间切换目标 socket 连接。 * 更新和发送共用对象锁,避免发送期间切换目标 socket 连接。
*/ */
synchronized void update(ObjectNode config) throws Exception { synchronized void update(ObjectNode config, InetSocketAddress target) throws Exception {
sourceAddress = InetAddress.getByName(config.path("sourceHost").asText()); sourceAddress = InetAddress.getByName(config.path("sourceHost").asText());
if (route == null || !route.path("sourceHost").equals(config.path("sourceHost")) 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; lastSource = null;
lastNegotiationSource = null; lastNegotiationSource = null;
} }
socket.disconnect(); if (!target.equals(socket.getRemoteSocketAddress())) {
socket.connect(new InetSocketAddress(config.path("targetHost").asText(), socket.disconnect();
config.path("targetPort").asInt())); socket.connect(target);
}
route = config; 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,不能据此新增路由或认定报文可信。 // 类型字节只用于选择回程 socket,不能据此新增路由或认定报文可信。
// 协商请求不能覆盖既有配置回执的设备端口,普通上行也不能覆盖协商端口。 // 协商请求不能覆盖既有配置回执的设备端口,普通上行也不能覆盖协商端口。
if (frameType(bytes, bytes.length, 0x14)) { 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 @Service
@Conditional(WorkerCapabilityCondition.class) @Conditional(WorkerCapabilityCondition.class)
public class ImageIngressService implements AutoCloseable { public class ImageIngressService implements AutoCloseable {
@Autowired(required = false) private com.xtrh.input.service.OriginalInputRelay fusionInput;
// 一个 FND 帧最多承载 1024 字节明文,其中 36 字节属于 JPG1 分片头。 // 一个 FND 帧最多承载 1024 字节明文,其中 36 字节属于 JPG1 分片头。
// 重组最多 32 帧、64MiB;完整帧缓存另有 64MiB 预算,不随设备持续上传而增长。 // 重组最多 32 帧、64MiB;完整帧缓存另有 64MiB 预算,不随设备持续上传而增长。
// 图片解码串行执行,实际尺寸也受限制,压缩 JPEG 不能扩大到任意像素数。 // 图片解码串行执行,实际尺寸也受限制,压缩 JPEG 不能扩大到任意像素数。
@@ -404,6 +405,7 @@ public class ImageIngressService implements AutoCloseable {
require(Byte.toUnsignedInt(assembly.data[0]) == 255 && Byte.toUnsignedInt(assembly.data[1]) == 216 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); && Byte.toUnsignedInt(assembly.data[size - 2]) == 255 && Byte.toUnsignedInt(assembly.data[size - 1]) == 217);
validateJpeg(assembly.data, width, height); 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, 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 CoordinatorLocator locator;
private final PeerClient peer; private final PeerClient peer;
private final ImageIngressService images; private final ImageIngressService images;
@Autowired(required = false) private com.xtrh.input.service.LocalFusionInput fusionInput;
// 心跳、画面生成和 HTTP 播放会同时访问任务,键包含任务号及分配版本。 // 心跳、画面生成和 HTTP 播放会同时访问任务,键包含任务号及分配版本。
private final ConcurrentMap<String, MediaTask> tasks = new ConcurrentHashMap<>(); private final ConcurrentMap<String, MediaTask> tasks = new ConcurrentHashMap<>();
private volatile String session = "", connection = "WAITING"; private volatile String session = "", connection = "WAITING";
@@ -144,6 +145,7 @@ public class WorkerService {
.put("nodeRole", settings.role.equals("coordinator") ? "COORDINATOR" : "WORKER") .put("nodeRole", settings.role.equals("coordinator") ? "COORDINATOR" : "WORKER")
.put("name", settings.name).put("capacity", settings.capacity) .put("name", settings.name).put("capacity", settings.capacity)
.put("baseUrl", NodeAddress.url(settings, coordinator)); .put("baseUrl", NodeAddress.url(settings, coordinator));
registration.put("inputForwarding", fusionInput != null && fusionInput.enabled());
// 图片直达节点 UDP 端口;控制与浏览器媒体接口仍复用现有 HTTP 端口。 // 图片直达节点 UDP 端口;控制与浏览器媒体接口仍复用现有 HTTP 端口。
// 广播和注册中只有地址与能力,设备 SM4/HMAC 密钥只存在私有任务计划。 // 广播和注册中只有地址与能力,设备 SM4/HMAC 密钥只存在私有任务计划。
if (images != null && imagePort > 0) { 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);
}
@@ -31,7 +31,8 @@ class GatewayTest {
CoordinatorLocator locator = mock(CoordinatorLocator.class); CoordinatorLocator locator = mock(CoordinatorLocator.class);
PeerClient peer = mock(PeerClient.class); PeerClient peer = mock(PeerClient.class);
when(locator.locate()).thenReturn("http://127.0.0.1:18100"); 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())) when(peer.request(anyString(), anyString(), anyString(), any()))
.thenReturn(routes(collector.getLocalPort(), freePort(), pxhj.getLocalPort())); .thenReturn(routes(collector.getLocalPort(), freePort(), pxhj.getLocalPort()));
GatewayService gateway = new GatewayService(settings, locator, peer, new ObjectMapper()); GatewayService gateway = new GatewayService(settings, locator, peer, new ObjectMapper());
@@ -41,6 +42,8 @@ class GatewayTest {
byte[] bytes = opaqueBytes(64); byte[] bytes = opaqueBytes(64);
collector.send(new DatagramPacket(bytes, bytes.length, InetAddress.getLoopbackAddress(), ingressPort)); collector.send(new DatagramPacket(bytes, bytes.length, InetAddress.getLoopbackAddress(), ingressPort));
assertArrayEquals(bytes, payload(receive(pxhj))); 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); ObjectNode confirmedClear = object().put("routeVersion", 1).put("routesConfirmed", true);
@@ -50,9 +53,10 @@ class GatewayTest {
assertEquals(1, gateway.status().path("routeVersion").asLong()); assertEquals(1, gateway.status().path("routeVersion").asLong());
assertEquals(0, gateway.status().path("routeStatus").size()); assertEquals(0, gateway.status().path("routeStatus").size());
collector.send(new DatagramPacket(bytes, bytes.length, InetAddress.getLoopbackAddress(), ingressPort)); collector.send(new DatagramPacket(bytes, bytes.length, InetAddress.getLoopbackAddress(), ingressPort));
unknown.send(new DatagramPacket(bytes, bytes.length, InetAddress.getLoopbackAddress(), ingressPort));
pxhj.setSoTimeout(250); pxhj.setSoTimeout(250);
assertThrows(SocketTimeoutException.class, () -> receive(pxhj)); assertThrows(SocketTimeoutException.class, () -> receive(pxhj));
assertEquals(1, gateway.status().path("unknownSource").asLong()); assertEquals(2, gateway.status().path("unknownSource").asLong());
} finally { gateway.close(); } } 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")); Settings settings = settings(directory.resolve("persisted-gateway"));
CoordinatorLocator locator = mock(CoordinatorLocator.class); CoordinatorLocator locator = mock(CoordinatorLocator.class);
PeerClient peer = mock(PeerClient.class); PeerClient peer = mock(PeerClient.class);
when(locator.locate()).thenReturn("http://127.0.0.1:18100"); when(locator.locate()).thenReturn("http://127.0.0.1:18100");
try (DatagramSocket collector = loopbackSocket(); DatagramSocket unknown = 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())); 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()); GatewayService gateway = new GatewayService(settings, locator, peer, new ObjectMapper());
try { try {
gateway.heartbeat(); gateway.heartbeat();
byte[] bytes = opaqueBytes(96); byte[] bytes = opaqueBytes(96);
unknown.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()));
pxhj.setSoTimeout(250); assertArrayEquals(bytes, payload(receive(pxhj)));
assertThrows(SocketTimeoutException.class, () -> receive(pxhj));
assertEquals(1, gateway.status().path("unknownSource").asLong());
} finally { gateway.close(); } } finally { gateway.close(); }
gateway = new GatewayService(settings, locator, peer, new ObjectMapper()); gateway = new GatewayService(settings, locator, peer, new ObjectMapper());
@@ -123,14 +127,140 @@ class GatewayTest {
when(peer.request(anyString(), anyString(), anyString(), any())).thenReturn(unconfirmed); when(peer.request(anyString(), anyString(), anyString(), any())).thenReturn(unconfirmed);
gateway.heartbeat(); gateway.heartbeat();
assertEquals(1, gateway.status().path("routeVersion").asLong()); assertEquals(1, gateway.status().path("routeVersion").asLong());
pxhj.setSoTimeout(3000);
byte[] bytes = opaqueBytes(160); 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))); assertArrayEquals(bytes, payload(receive(pxhj)));
} finally { gateway.close(); } } 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 { @Test void imageNegotiationRepliesUseTheirOwnSocketWithoutChangingLegacyReplyDestination() throws Exception {
Settings settings = settings(directory.resolve("image-negotiation-gateway")); Settings settings = settings(directory.resolve("image-negotiation-gateway"));
CoordinatorLocator locator = mock(CoordinatorLocator.class); CoordinatorLocator locator = mock(CoordinatorLocator.class);
@@ -188,10 +318,14 @@ class GatewayTest {
} }
private Settings settings(Path data) throws Exception { 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.token", "unit-test-credential-not-deployed")
.withProperty("fusion.data-dir", data.toString()).withProperty("fusion.gateway-port", "0") .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) { 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")));
}
}